@voiceflow/channels-discord 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Voiceflow, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # @voiceflow/channels-discord
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Voiceflow agent in Discord: mentions, threads, direct messages, buttons,
4
+ cards and a slash command, with one command to set it up.
5
+
6
+ > **Status:** an early release. Expect changes between versions before 1.0.
7
+ > Built on Chat SDK's Discord adapter. Tested against a stand-in for Discord's
8
+ > API, and run in Discord itself: a mention and its thread, a direct message,
9
+ > buttons and `/ask`.
10
+
11
+ ## Connect
12
+
13
+ ```bash
14
+ npx voiceflow-channels connect discord --env-file .env.local
15
+ ```
16
+
17
+ Discord has no way to make an application from a command, so that one step is
18
+ by hand, and connect walks you through it. It opens
19
+ [the page that makes one](https://discord.com/developers/applications?new_application=true)
20
+ and says what to name it (your agent's name: Discord has no way to fill that
21
+ in). You create it, open its **Bot** page, click **Reset Token**, and paste the
22
+ token at connect's hidden prompt. That is all you do in the portal.
23
+
24
+ It shows its whole plan and asks before it changes anything:
25
+
26
+ ```
27
+ Discord: app "My app" (1234567890), bot My app
28
+ ~ name the bot "Support", your agent's name in Voiceflow (it is "My app" now; --name keep leaves it)
29
+ + set the bot's picture to the agent's avatar in Voiceflow (Voiceflow's icon if Discord won't take it): https://…/avatar.png
30
+ + turn on the Message Content intent, so the bot is sent what people write
31
+ + add the /ask command
32
+ · slash commands and buttons need your server's address: `voiceflow-channels dev` gives it to Discord each time it starts
33
+ Voiceflow: project "Support" (64f…) in workspace a1B2c3, environment development: the variables go on its draft
34
+ + 8 variables for your agent's prompts (discord_user_id, discord_user_name, …)
35
+ ~ compile the environment's draft
36
+ Then:
37
+ · nothing is published, and nothing has to be: the variables are live once you publish development
38
+ + you get the link that adds the bot to a server
39
+ ```
40
+
41
+ - **The bot looks like your agent.** A new app's bot gets the agent's name in
42
+ Voiceflow, and a bot with no picture gets the agent's avatar, or Voiceflow's
43
+ icon when the agent has none. A bot connected before keeps its name, and a
44
+ bot with a picture keeps it: `--name <name>` and `--icon <url>` set them
45
+ anyway, and `--name keep` and `--icon none` leave a new bot as it is. The
46
+ application's own name, shown on the page that adds the bot, is the one you
47
+ typed in the portal: Discord has no call to change it.
48
+ - **What it writes:** `DISCORD_PUBLIC_KEY` and `DISCORD_APPLICATION_ID`, read
49
+ from Discord, go in the `--env-file` with anything it had to ask for. A value
50
+ already there is never changed. The bot token goes to Discord and that file,
51
+ and never to Voiceflow.
52
+ - **The bot token** comes from `--token-file`, `DISCORD_BOT_TOKEN` in the
53
+ environment, the same name in `--env-file`, or a hidden prompt.
54
+ - **Pages are opened only for a person who is there**, in a browser that is
55
+ theirs: never for a script or a coding agent, never over SSH or in CI, and
56
+ never with `--no-open`. The links are always printed.
57
+ - **With nobody at the terminal** (a script, a coding agent) connect asks
58
+ nothing. It stops with exit code 3 and says, in the one stop, everything a
59
+ person has to do: the token, which agent, its key. Exit 0 is done, 1 a
60
+ failure, 2 a mistake in the command.
61
+ - **Adding the bot to a server** is a page connect opens, and a link it
62
+ prints: whoever opens it picks the server and authorizes. `--server <id>` has
63
+ it open with your server chosen. It asks for the permissions the bot uses:
64
+ to see channels, send messages (in threads too), open and manage threads,
65
+ read history, react, embed links, attach files and use slash commands.
66
+ - **Connect waits for the bot to be added**, when a person is there: up to
67
+ five minutes, then it says which server the bot is in, and the bot messages
68
+ you in Discord to say it's connected (you, because the application is
69
+ yours; nothing is posted in the server). `--no-wait` and `--no-greeting`
70
+ turn each off.
71
+ - **`voiceflow-channels dev` runs connect for you** the first time, when the
72
+ bot was never connected from here and a person is there. So in an app the
73
+ starter made, `npm run dev` is the one command.
74
+ - **Nothing is published.** The bot works as soon as it's connected. The
75
+ `discord_*` variables are for your agent's prompts, and are live once you
76
+ publish the environment. `--publish` does that here: the whole draft goes live.
77
+ - **Running it again** only adds what's missing. `--dry-run` shows the plan
78
+ and changes nothing.
79
+ - **`disconnect discord`** deletes the slash command and clears the address
80
+ Discord sends to. The application and its bot are yours to remove.
81
+
82
+ ## How Discord reaches your server
83
+
84
+ Discord reaches a bot two ways, and this package uses both.
85
+
86
+ | What | How it arrives |
87
+ |---|---|
88
+ | Slash commands, button clicks | Discord sends them to an address, signed with the app's key. |
89
+ | What people write, reactions | Over a standing connection (Discord's Gateway) that something has to hold. Whatever holds it passes each event on to the same route. |
90
+
91
+ **On your machine,** `voiceflow-channels dev -- <your server's command>` does
92
+ both: it opens a tunnel, gives Discord the tunnel's address
93
+ (`point discord`), and holds the connection, passing events to your server.
94
+
95
+ **Deployed,** give Discord your address with
96
+ `connect discord --public-url https://<host>` (it checks your server answers
97
+ there), and hold the connection yourself. On a host that doesn't keep a
98
+ process running, a scheduled route does it:
99
+ [`examples/nextjs-discord`](../../examples/nextjs-discord) has one, with its
100
+ schedule. Use a second Discord application for development: while `dev` runs,
101
+ Discord sends that bot's slash commands and buttons to your machine, and a
102
+ bot connected from two places answers twice.
103
+
104
+ ## In your server
105
+
106
+ ```ts
107
+ import { discord } from '@voiceflow/channels-discord';
108
+
109
+ const channels = await createChannels({
110
+ voiceflow: { apiKey: process.env.VOICEFLOW_API_KEY!, projectID: process.env.VOICEFLOW_PROJECT_ID! },
111
+ channels: [discord()], // reads DISCORD_BOT_TOKEN, DISCORD_PUBLIC_KEY and DISCORD_APPLICATION_ID
112
+ state,
113
+ });
114
+ // One route takes everything: channels.webhook('discord', request, { waitUntil })
115
+ ```
116
+
117
+ In a bundled server, keep the Discord adapter out of the bundle: it loads
118
+ optional native modules by name. In Next.js that is
119
+ `serverExternalPackages: ['@chat-adapter/discord']`.
120
+
121
+ ### What happens in Discord
122
+
123
+ - **A mention in a channel** opens a thread on the message, named after what
124
+ was asked, and the agent answers there. The conversation carries on in the
125
+ thread with no mention needed.
126
+ - **A direct message** is answered where it was sent.
127
+ - **`/ask question: …`** posts the question where everyone can see it, and
128
+ answers in a thread on it. In a direct message or a thread, it answers in place.
129
+ - **Buttons, cards, carousels and images** from the agent are Discord buttons
130
+ and embeds. A click sends the button's own request, as the person who clicked.
131
+ - **A long answer** goes as several messages, cut where the text breaks:
132
+ Discord shows 2,000 characters in one.
133
+
134
+ ### Options
135
+
136
+ | Option | Default | What it does |
137
+ |---|---|---|
138
+ | `adapter` | the environment | The Discord adapter's own config: `botToken`, `publicKey`, `applicationId`, `respondToChannelIds`, `mentionRoleIds`, `logger`, … |
139
+ | `context` | `true` | Set who and where as `discord_*` variables on every turn. |
140
+ | `titles` | `true` | Name the thread opened for a conversation after the first message. A thread people made is never renamed. |
141
+ | `slashCommands` | `true` | Answer the app's slash command. |
142
+
143
+ The adapter logs every event it's passed, and Discord's connection passes on
144
+ many that aren't for the bot. By default only its warnings and errors are
145
+ printed: pass `adapter: { logger }` for more.
146
+
147
+ ### Variables
148
+
149
+ Set on every turn, empty when unknown. The agent sees one only where its
150
+ instructions or global prompt reference it (`{discord_user_name}`).
151
+
152
+ | Variable | What it holds |
153
+ |---|---|
154
+ | `discord_user_id` | The Discord user ID of the person in this conversation. |
155
+ | `discord_user_name` | The person's display name in Discord. |
156
+ | `discord_user_handle` | The person's Discord username (their unique handle). |
157
+ | `discord_guild_id` | The Discord server (guild) ID. Empty in a direct message. |
158
+ | `discord_channel_id` | The channel this conversation is in: for a thread, the channel it was started in. |
159
+ | `discord_thread_id` | The thread this conversation is in. Empty when it isn't in one. |
160
+ | `discord_channel_type` | `channel`, `thread` or `dm`. |
161
+ | `discord_message_id` | The ID of the person's latest message. Empty when the turn came from a button or a slash command. |
162
+
163
+ ## What it doesn't do yet
164
+
165
+ - **No Discord tools for the agent.** Slack's package installs tools that act
166
+ in Slack; this one installs none.
167
+ - **No forms, tables or charts.** Buttons, cards and carousels are shown;
168
+ Slack's other presentation traces have no Discord equivalent here yet.
169
+ - **No streamed answers.** Each reply is posted whole, with Discord's typing
170
+ indicator while the agent works: the core streams only where a platform
171
+ streams natively.
@@ -0,0 +1,62 @@
1
+ import type { Thread } from 'chat';
2
+ /** Where a conversation is: a server's channel, a thread in one, or a direct message (`guildId` is `@me`). */
3
+ export interface DiscordThreadId {
4
+ guildId: string;
5
+ channelId: string;
6
+ threadId?: string;
7
+ }
8
+ export interface DiscordAdapterLike {
9
+ readonly name: string;
10
+ decodeThreadId(threadId: string): DiscordThreadId;
11
+ encodeThreadId(data: DiscordThreadId): string;
12
+ getUser(userId: string): Promise<{
13
+ fullName?: string;
14
+ userName?: string;
15
+ } | null>;
16
+ setThreadTitle(threadId: string, title: string): Promise<void>;
17
+ /**
18
+ * How the adapter opens a thread on a message, as it does for a mention. It
19
+ * isn't in the adapter's public types, so it's used only where it's there:
20
+ * without it a slash command is answered in the channel.
21
+ */
22
+ createDiscordThread?(channelId: string, messageId: string): Promise<{
23
+ id: string;
24
+ }>;
25
+ }
26
+ /**
27
+ * Makes two of the adapter's messages ones Discord takes as they're meant.
28
+ *
29
+ * The adapter sends every card as an embed beside its buttons. A turn's choices are a card of buttons alone, so
30
+ * the embed is empty, and Discord refuses the whole message (400, "embeds.0.description: This field is
31
+ * required"): the empty embed is left out, and the buttons go as they are.
32
+ *
33
+ * And a card with no buttons, sent over one that had them, says nothing of buttons at all, so Discord keeps the
34
+ * old ones: once a choice is made they'd stay there to be clicked. It is sent with none, which takes them off.
35
+ *
36
+ * Both are the adapter's to fix (docs/upstream.md). This reads how the adapter builds a message, which isn't in
37
+ * its public types: where that has changed, nothing is patched, and a refused message still goes as text.
38
+ */
39
+ export declare function fitMessages(adapter: unknown): void;
40
+ export interface ThreadNames {
41
+ /** The name for the thread about to be started on a message. */
42
+ want(messageId: string, name: string): void;
43
+ /** Whether a thread was given its name as it was made, so it needs no renaming. */
44
+ made(threadId: string): boolean;
45
+ }
46
+ /**
47
+ * Names a conversation's thread as it's made. The adapter makes every thread as "Thread" and the date, and a
48
+ * rename afterwards leaves "changed the channel name" in the thread as its first line. So the name is put in as
49
+ * the adapter asks Discord for the thread: the one asked for with `want`, or else what the message it starts
50
+ * from says, read back from Discord.
51
+ *
52
+ * This goes through how the adapter calls Discord, which isn't in its public types (docs/upstream.md). Where
53
+ * that has changed, or the message can't be read, the thread is made as the adapter names it, `made` says so,
54
+ * and it is renamed afterwards.
55
+ */
56
+ export declare function nameThreads(adapter: unknown, titleOf: (text: string) => string): ThreadNames;
57
+ export declare const SLUG = "discord";
58
+ /** The guild part of a direct message's thread ID. */
59
+ export declare const DM_GUILD = "@me";
60
+ export declare function discordAdapter(thread: Thread<any, any>): DiscordAdapterLike;
61
+ /** The Discord server, channel and thread a Chat SDK thread ID names. */
62
+ export declare function where(thread: Thread<any, any>): DiscordThreadId;
@@ -0,0 +1,100 @@
1
+ /** An embed with nothing to show: the adapter's colour and no more. */
2
+ const bare = (embed) => Object.keys(embed).every((key) => key === 'color' || key === 'type');
3
+ /**
4
+ * Makes two of the adapter's messages ones Discord takes as they're meant.
5
+ *
6
+ * The adapter sends every card as an embed beside its buttons. A turn's choices are a card of buttons alone, so
7
+ * the embed is empty, and Discord refuses the whole message (400, "embeds.0.description: This field is
8
+ * required"): the empty embed is left out, and the buttons go as they are.
9
+ *
10
+ * And a card with no buttons, sent over one that had them, says nothing of buttons at all, so Discord keeps the
11
+ * old ones: once a choice is made they'd stay there to be clicked. It is sent with none, which takes them off.
12
+ *
13
+ * Both are the adapter's to fix (docs/upstream.md). This reads how the adapter builds a message, which isn't in
14
+ * its public types: where that has changed, nothing is patched, and a refused message still goes as text.
15
+ */
16
+ export function fitMessages(adapter) {
17
+ const target = adapter;
18
+ const build = target.buildMessagePayload;
19
+ if (typeof build !== 'function')
20
+ return;
21
+ target.buildMessagePayload = function (...args) {
22
+ const built = build.apply(this, args);
23
+ const payload = built?.payload;
24
+ // Only a card has embeds: a message of text is left as it is.
25
+ if (!built || !payload || !Array.isArray(payload.embeds))
26
+ return built;
27
+ const buttons = payload.components ?? [];
28
+ payload.components = buttons;
29
+ if (buttons.length && payload.embeds.every(bare)) {
30
+ payload.embeds = [];
31
+ built.embedCount = 0;
32
+ }
33
+ return built;
34
+ };
35
+ }
36
+ const STARTS_THREAD = /^\/channels\/(\d+)\/messages\/(\d+)\/threads$/;
37
+ /** How many threads named here are remembered: enough for the turns that follow at once. */
38
+ const NAMED_KEPT = 200;
39
+ /**
40
+ * Names a conversation's thread as it's made. The adapter makes every thread as "Thread" and the date, and a
41
+ * rename afterwards leaves "changed the channel name" in the thread as its first line. So the name is put in as
42
+ * the adapter asks Discord for the thread: the one asked for with `want`, or else what the message it starts
43
+ * from says, read back from Discord.
44
+ *
45
+ * This goes through how the adapter calls Discord, which isn't in its public types (docs/upstream.md). Where
46
+ * that has changed, or the message can't be read, the thread is made as the adapter names it, `made` says so,
47
+ * and it is renamed afterwards.
48
+ */
49
+ export function nameThreads(adapter, titleOf) {
50
+ const wanted = new Map();
51
+ const named = new Set();
52
+ const names = {
53
+ want(messageId, name) {
54
+ if (name)
55
+ wanted.set(messageId, name);
56
+ },
57
+ made: (threadId) => named.has(threadId),
58
+ };
59
+ const target = adapter;
60
+ const ask = target.discordFetch;
61
+ if (typeof ask !== 'function')
62
+ return names;
63
+ target.discordFetch = async function (path, method, body) {
64
+ const starts = method === 'POST' ? STARTS_THREAD.exec(path) : null;
65
+ if (!starts)
66
+ return ask.call(this, path, method, body);
67
+ const [, channelId, messageId] = starts;
68
+ let name = wanted.get(messageId);
69
+ wanted.delete(messageId);
70
+ if (!name) {
71
+ try {
72
+ const message = (await (await ask.call(this, `/channels/${channelId}/messages/${messageId}`, 'GET')).json());
73
+ name = titleOf(message.content ?? '');
74
+ }
75
+ catch {
76
+ // The message can't be read (the bot may not see the channel's history): the adapter's name stands for now.
77
+ }
78
+ }
79
+ if (!name)
80
+ return ask.call(this, path, method, body);
81
+ const response = await ask.call(this, path, method, { ...body, name });
82
+ // A thread started from a message has that message's ID.
83
+ named.add(messageId);
84
+ if (named.size > NAMED_KEPT)
85
+ named.delete(named.values().next().value);
86
+ return response;
87
+ };
88
+ return names;
89
+ }
90
+ export const SLUG = 'discord';
91
+ /** The guild part of a direct message's thread ID. */
92
+ export const DM_GUILD = '@me';
93
+ export function discordAdapter(thread) {
94
+ return thread.adapter;
95
+ }
96
+ /** The Discord server, channel and thread a Chat SDK thread ID names. */
97
+ export function where(thread) {
98
+ return discordAdapter(thread).decodeThreadId(thread.id);
99
+ }
100
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAgCA,uEAAuE;AACvE,MAAM,IAAI,GAAG,CAAC,KAA8B,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,GAA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,IAAI,CAAC,IAAI;YAAE,OAAO,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QACrD,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAI,IAAgC,EAAE,IAAI,EAAE,CAAC,CAAC;QACpG,yDAAyD;QACzD,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACrB,IAAI,KAAK,CAAC,IAAI,GAAG,UAAU;YAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAe,CAAC,CAAC;QACjF,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;IACF,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,SAAS,CAAC;AAC9B,sDAAsD;AACtD,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,CAAC;AAE9B,MAAM,UAAU,cAAc,CAAC,MAAwB;IACrD,OAAO,MAAM,CAAC,OAAwC,CAAC;AACzD,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,KAAK,CAAC,MAAwB;IAC5C,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,51 @@
1
+ export declare const DISCORD_API = "https://discord.com/api/v10";
2
+ export declare const DEVELOPER_PORTAL = "https://discord.com/developers/applications";
3
+ /** The Developer Portal with its "new application" dialog open: the one place an application can be made. */
4
+ export declare const NEW_APPLICATION = "https://discord.com/developers/applications?new_application=true";
5
+ /** Application flags a bot token can turn on for itself, and the one only Discord grants. */
6
+ export declare const APP_FLAGS: {
7
+ /** The Message Content intent, granted by Discord to a verified app. */
8
+ readonly GATEWAY_MESSAGE_CONTENT: number;
9
+ /** The Message Content intent, for an app in fewer than 100 servers: the switch in the portal's Bot page. */
10
+ readonly GATEWAY_MESSAGE_CONTENT_LIMITED: number;
11
+ };
12
+ /** The permissions the bot asks a server for when it's added. */
13
+ export declare const PERMISSIONS: {
14
+ readonly ADD_REACTIONS: bigint;
15
+ readonly VIEW_CHANNEL: bigint;
16
+ readonly SEND_MESSAGES: bigint;
17
+ readonly EMBED_LINKS: bigint;
18
+ readonly ATTACH_FILES: bigint;
19
+ readonly READ_MESSAGE_HISTORY: bigint;
20
+ readonly USE_APPLICATION_COMMANDS: bigint;
21
+ readonly MANAGE_THREADS: bigint;
22
+ readonly CREATE_PUBLIC_THREADS: bigint;
23
+ readonly SEND_MESSAGES_IN_THREADS: bigint;
24
+ };
25
+ export declare const BOT_PERMISSIONS: bigint;
26
+ /** A Discord ID, as a server's or an application's is written. */
27
+ export declare function isSnowflake(value: string): boolean;
28
+ /**
29
+ * The link that adds the bot to a server, with its slash command and the permissions it uses: whoever opens it
30
+ * picks the server and authorizes. With `server` (a server's ID) the page opens with that server chosen.
31
+ */
32
+ export declare function installLink(applicationId: string, options?: {
33
+ server?: string;
34
+ }): string;
35
+ export interface DiscordApiOptions {
36
+ /** The bot's token. Never printed. */
37
+ token: string;
38
+ apiUrl?: string;
39
+ fetch?: typeof fetch;
40
+ wait?: (ms: number) => Promise<void>;
41
+ }
42
+ export declare class DiscordApiError extends Error {
43
+ readonly status: number;
44
+ /** Discord's own error code, where it gave one. */
45
+ readonly code?: number | undefined;
46
+ constructor(message: string, status: number,
47
+ /** Discord's own error code, where it gave one. */
48
+ code?: number | undefined);
49
+ }
50
+ export type DiscordApi = <T = any>(method: string, path: string, body?: unknown) => Promise<T>;
51
+ export declare function createDiscordApi(options: DiscordApiOptions): DiscordApi;
@@ -0,0 +1,108 @@
1
+ // Discord's HTTP API, for connect: the calls a bot token can make about its
2
+ // own application. Discord has no way to make an application from outside its
3
+ // Developer Portal, so everything here starts from a token a person copied.
4
+ // The token is sent to Discord and nowhere else, and never comes back in an error.
5
+ export const DISCORD_API = 'https://discord.com/api/v10';
6
+ export const DEVELOPER_PORTAL = 'https://discord.com/developers/applications';
7
+ /** The Developer Portal with its "new application" dialog open: the one place an application can be made. */
8
+ export const NEW_APPLICATION = `${DEVELOPER_PORTAL}?new_application=true`;
9
+ /** Application flags a bot token can turn on for itself, and the one only Discord grants. */
10
+ export const APP_FLAGS = {
11
+ /** The Message Content intent, granted by Discord to a verified app. */
12
+ GATEWAY_MESSAGE_CONTENT: 1 << 18,
13
+ /** The Message Content intent, for an app in fewer than 100 servers: the switch in the portal's Bot page. */
14
+ GATEWAY_MESSAGE_CONTENT_LIMITED: 1 << 19,
15
+ };
16
+ /** The permissions the bot asks a server for when it's added. */
17
+ export const PERMISSIONS = {
18
+ ADD_REACTIONS: 1n << 6n,
19
+ VIEW_CHANNEL: 1n << 10n,
20
+ SEND_MESSAGES: 1n << 11n,
21
+ EMBED_LINKS: 1n << 14n,
22
+ ATTACH_FILES: 1n << 15n,
23
+ READ_MESSAGE_HISTORY: 1n << 16n,
24
+ USE_APPLICATION_COMMANDS: 1n << 31n,
25
+ MANAGE_THREADS: 1n << 34n,
26
+ CREATE_PUBLIC_THREADS: 1n << 35n,
27
+ SEND_MESSAGES_IN_THREADS: 1n << 38n,
28
+ };
29
+ export const BOT_PERMISSIONS = Object.values(PERMISSIONS).reduce((all, bit) => all | bit, 0n);
30
+ /** A Discord ID, as a server's or an application's is written. */
31
+ export function isSnowflake(value) {
32
+ return /^\d{17,20}$/.test(value);
33
+ }
34
+ /**
35
+ * The link that adds the bot to a server, with its slash command and the permissions it uses: whoever opens it
36
+ * picks the server and authorizes. With `server` (a server's ID) the page opens with that server chosen.
37
+ */
38
+ export function installLink(applicationId, options = {}) {
39
+ const link = `https://discord.com/oauth2/authorize?client_id=${encodeURIComponent(applicationId)}&scope=bot+applications.commands&permissions=${BOT_PERMISSIONS}`;
40
+ return options.server ? `${link}&guild_id=${encodeURIComponent(options.server)}` : link;
41
+ }
42
+ export class DiscordApiError extends Error {
43
+ status;
44
+ code;
45
+ constructor(message, status,
46
+ /** Discord's own error code, where it gave one. */
47
+ code) {
48
+ super(message);
49
+ this.status = status;
50
+ this.code = code;
51
+ this.name = 'DiscordApiError';
52
+ }
53
+ }
54
+ export function createDiscordApi(options) {
55
+ const base = (options.apiUrl ?? DISCORD_API).replace(/\/+$/, '');
56
+ const doFetch = options.fetch ?? fetch;
57
+ const wait = options.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
58
+ return async function call(method, path, body) {
59
+ for (let attempt = 0;; attempt++) {
60
+ const res = await doFetch(`${base}${path}`, {
61
+ method,
62
+ headers: {
63
+ authorization: `Bot ${options.token}`,
64
+ // Discord refuses a request that doesn't say what sent it.
65
+ 'user-agent': 'DiscordBot (https://github.com/voiceflow/channels-sdk, 0)',
66
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
67
+ },
68
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
69
+ });
70
+ const text = await res.text();
71
+ let parsed;
72
+ try {
73
+ parsed = text ? JSON.parse(text) : {};
74
+ }
75
+ catch {
76
+ parsed = undefined;
77
+ }
78
+ // Asked to slow down: wait as long as Discord says, a couple of times.
79
+ if (res.status === 429 && attempt < 2) {
80
+ await wait(Math.min(Math.max(Number(parsed?.retry_after) || 1, 0.1), 5) * 1000);
81
+ continue;
82
+ }
83
+ if (res.ok)
84
+ return (parsed ?? {});
85
+ const said = parsed?.message ? `${parsed.message}${fieldErrors(parsed.errors)}` : text.slice(0, 300);
86
+ throw new DiscordApiError(`Discord ${method} ${path} answered ${res.status}: ${said.split(options.token).join('[bot token]')}`, res.status, typeof parsed?.code === 'number' ? parsed.code : undefined);
87
+ }
88
+ };
89
+ }
90
+ /** Discord's per-field errors (`{ field: { _errors: [{ message }] } }`), as "(field: message; …)". */
91
+ function fieldErrors(errors) {
92
+ const found = [];
93
+ const walk = (node, path) => {
94
+ if (!node || typeof node !== 'object')
95
+ return;
96
+ for (const [key, value] of Object.entries(node)) {
97
+ if (key === '_errors' && Array.isArray(value)) {
98
+ for (const e of value)
99
+ found.push(`${path || 'request'}: ${String(e?.message ?? '')}`);
100
+ }
101
+ else
102
+ walk(value, path ? `${path}.${key}` : key);
103
+ }
104
+ };
105
+ walk(errors, '');
106
+ return found.length ? ` (${found.join('; ').slice(0, 400)})` : '';
107
+ }
108
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/connect/api.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAC9E,4EAA4E;AAC5E,mFAAmF;AAEnF,MAAM,CAAC,MAAM,WAAW,GAAG,6BAA6B,CAAC;AACzD,MAAM,CAAC,MAAM,gBAAgB,GAAG,6CAA6C,CAAC;AAC9E,6GAA6G;AAC7G,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,gBAAgB,uBAAuB,CAAC;AAE1E,6FAA6F;AAC7F,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,wEAAwE;IACxE,uBAAuB,EAAE,CAAC,IAAI,EAAE;IAChC,6GAA6G;IAC7G,+BAA+B,EAAE,CAAC,IAAI,EAAE;CAChC,CAAC;AAEX,iEAAiE;AACjE,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,aAAa,EAAE,EAAE,IAAI,EAAE;IACvB,YAAY,EAAE,EAAE,IAAI,GAAG;IACvB,aAAa,EAAE,EAAE,IAAI,GAAG;IACxB,WAAW,EAAE,EAAE,IAAI,GAAG;IACtB,YAAY,EAAE,EAAE,IAAI,GAAG;IACvB,oBAAoB,EAAE,EAAE,IAAI,GAAG;IAC/B,wBAAwB,EAAE,EAAE,IAAI,GAAG;IACnC,cAAc,EAAE,EAAE,IAAI,GAAG;IACzB,qBAAqB,EAAE,EAAE,IAAI,GAAG;IAChC,wBAAwB,EAAE,EAAE,IAAI,GAAG;CAC3B,CAAC;AAEX,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,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AI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACpD,CAAC;IACH,CAAC,CAAC;IACF,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACjB,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AACpE,CAAC"}
@@ -0,0 +1,40 @@
1
+ import { type ForwardGatewayOptions } from '../gateway.js';
2
+ /** What the command reads and writes, for a test or a program that runs it: by default the console, the environment and `fetch`. */
3
+ export interface CliIO {
4
+ out?: (line: string) => void;
5
+ err?: (line: string) => void;
6
+ env?: Record<string, string | undefined>;
7
+ fetch?: typeof fetch;
8
+ /** Whether a person is there to answer a question. */
9
+ interactive?: boolean;
10
+ ask?: (question: string) => Promise<string>;
11
+ /** Asks for a secret, without showing what's typed. */
12
+ secret?: (question: string) => Promise<string>;
13
+ /** Opens a page in the person's browser, and says whether it could. Default: their own browser, where there is one here. */
14
+ open?: (url: string) => Promise<boolean>;
15
+ /** Waits, between looks at whether the bot has been added to a server. Default: a timer. */
16
+ wait?: (ms: number) => Promise<void>;
17
+ /** Holds Discord's Gateway connection, in place of the real one: for a test. */
18
+ gateway?: (options: ForwardGatewayOptions) => Promise<void>;
19
+ }
20
+ /** Runs the command. Returns its exit code: an error is printed, cleaned of every secret the command holds, and never thrown. */
21
+ export declare function cli(argv: string[], io?: CliIO): Promise<number>;
22
+ /**
23
+ * Whether a Discord bot has been connected from here: its token, its public key and its application's ID are all
24
+ * in the environment or the env file. `voiceflow-channels dev` asks, and runs connect first when it hasn't.
25
+ */
26
+ export declare function connected(options?: {
27
+ envFile?: string;
28
+ env?: Record<string, string | undefined>;
29
+ }): Promise<boolean>;
30
+ /**
31
+ * Holds Discord's Gateway connection open for `voiceflow-channels dev`, passing
32
+ * what people write to your server on this machine, until `signal` aborts.
33
+ */
34
+ export declare function listen(options: {
35
+ localUrl: string;
36
+ envFile?: string;
37
+ signal: AbortSignal;
38
+ out: (line: string) => void;
39
+ err: (line: string) => void;
40
+ }, io?: Pick<CliIO, 'env' | 'fetch' | 'gateway'>): Promise<void>;