{"id":15355512,"url":"https://github.com/mattipv4/workers-discord","last_synced_at":"2025-06-24T06:02:42.689Z","repository":{"id":206603619,"uuid":"717282340","full_name":"MattIPv4/workers-discord","owner":"MattIPv4","description":"Some wrappers for Discord applications in Workers ","archived":false,"fork":false,"pushed_at":"2024-12-05T20:55:18.000Z","size":73,"stargazers_count":10,"open_issues_count":5,"forks_count":5,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-06-22T09:47:24.567Z","etag":null,"topics":["cloudflare","cloudflare-worker","cloudflare-workers","discord","discord-api","discord-bot","discord-bot-framework","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/workers-discord","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MattIPv4.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-11-11T02:03:08.000Z","updated_at":"2024-12-28T18:48:14.000Z","dependencies_parsed_at":"2023-11-14T03:25:02.371Z","dependency_job_id":"534ed54d-db8e-4e40-81d5-c9f7cad8e96d","html_url":"https://github.com/MattIPv4/workers-discord","commit_stats":null,"previous_names":["mattipv4/workers-discord"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MattIPv4/workers-discord","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MattIPv4%2Fworkers-discord","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MattIPv4%2Fworkers-discord/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MattIPv4%2Fworkers-discord/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MattIPv4%2Fworkers-discord/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MattIPv4","download_url":"https://codeload.github.com/MattIPv4/workers-discord/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MattIPv4%2Fworkers-discord/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261273553,"owners_count":23133819,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cloudflare","cloudflare-worker","cloudflare-workers","discord","discord-api","discord-bot","discord-bot-framework","typescript"],"created_at":"2024-10-01T12:24:38.776Z","updated_at":"2025-06-24T06:02:42.117Z","avatar_url":"https://github.com/MattIPv4.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# workers-discord\n\nSome wrappers for Discord applications in Workers.\n\nProvides a request handler for Discord interactions at `/interactions` (and a health-check route at `/health`).\n\nProvides a method for registering commands with Discord, with logic for only updating commands with changes.\n\nRequest handler includes optional support for Sentry (tested with `workers-sentry`/`toucan-js`).\n\n## Usage\n\nWe'll be using TypeScript for this example, but the library can be used with JavaScript as well.\n\nInstall the library and the required packages for this example.\n\n```sh\nnpm install workers-discord discord-api-types\nnpm install --save-dev typescript tsup dotenv @cloudflare/workers-types wrangler\n```\n\nEnsure Typescript is setup with the correct exposed types for Workers.\n\n`tsconfig.json`:\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"lib\": [\"ESNext\"],\n    \"types\": [\"@cloudflare/workers-types\"],\n    \"noEmitOnError\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"removeComments\": false,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n  }\n}\n```\n\nDefine a `/ping` command that'll show `Pinging...` and then update to `Pong! \u003ccurrent time\u003e` after 5 seconds.\n\n`src/commands/ping.ts`:\n\n```ts\nimport { InteractionResponseType, MessageFlags, ComponentType } from 'discord-api-types/payloads';\nimport type { Command } from 'workers-discord';\n\nimport { component } from '../components/ping';\nimport type { CtxWithEnv } from '../env';\n\nconst pingCommand: Command\u003cCtxWithEnv\u003e = {\n    name: 'ping',\n    description: 'Ping the application to check if it is online.',\n    // Defining a type is optional for chat input (aka \"slash\") commands\n    // type: ApplicationCommandType.ChatInput,\n    execute: ({ response, wait, edit }) =\u003e {\n        wait((async () =\u003e {\n            await new Promise(resolve =\u003e setTimeout(resolve, 5000));\n\n            await edit({\n                content: `Pong! \\`${new Date().toISOString()}\\``,\n                components: [\n                    {\n                        type: ComponentType.ActionRow,\n                        components: [ component ],\n                    },\n                ],\n            });\n        })());\n\n        return response({\n            type: InteractionResponseType.ChannelMessageWithSource,\n            data: {\n                content: 'Pinging...',\n                flags: MessageFlags.Ephemeral,\n            },\n        });\n    },\n};\n\nexport default pingCommand;\n```\n\nDefine a refresh button component that we'll include in the `/ping` command response, which will update the message when clicked.\n\n`src/components/ping.ts`:\n\n```ts\nimport { InteractionResponseType, ComponentType, ButtonStyle, type APIButtonComponent } from 'discord-api-types/payloads';\nimport type { Component } from 'workers-discord';\n\nimport type { CtxWithEnv } from '../env';\n\nexport const component: APIButtonComponent = {\n    type: ComponentType.Button,\n    custom_id: 'ping',\n    style: ButtonStyle.Secondary,\n    label: 'Refresh',\n};\n\nconst pingComponent: Component\u003cCtxWithEnv\u003e = {\n    name: 'ping',\n    execute: async ({ response }) =\u003e response({\n        type: InteractionResponseType.UpdateMessage,\n        data: {\n            content: `Pong! \\`${new Date().toISOString()}\\``,\n            components: [\n                {\n                    type: ComponentType.ActionRow,\n                    components: [ component ],\n                },\n            ],\n        },\n    }),\n};\n\nexport default pingComponent;\n```\n\nDefine an `Echo` message context menu command that will repeat the content of the message:\n\n```ts\nimport { InteractionResponseType, MessageFlags, ApplicationCommandType } from 'discord-api-types/payloads';\nimport type { Command } from 'workers-discord';\n\nimport type { CtxWithEnv } from '../env';\n\nexport const echoCommand: Command\u003cCtxWithEnv, Request, Toucan\u003e = {\n  name: 'Echo',\n  type: ApplicationCommandType.Message,\n  execute: async ({ response, interaction }) =\u003e {\n    // `interaction` is resolved to the appropriate type based on the `type` above\n    // ApplicationCommandType.Message -\u003e APIMessageApplicationCommandInteraction\n    const message = interaction.data.resolved.messages[interaction.data.target_id]\n\n    return response({\n      type: InteractionResponseType.ChannelMessageWithSource,\n      data: {\n        content: message?.content,\n        flags: MessageFlags.Ephemeral,\n      },\n    })\n  },\n}\n```\n\nCreate a file to store our environment definition, so that we can use it in commands etc. if needed.\n\n`src/env.ts`:\n\n```ts\nexport interface Env {\n    DISCORD_PUBLIC_KEY: string;\n}\n\nexport interface CtxWithEnv extends ExecutionContext {\n    env: Env;\n}\n```\n\nDefine the Cloudflare Worker request handler with our command and component both registered.\n\n`src/index.ts`:\n\n```ts\nimport { createHandler } from 'workers-discord';\n\nimport pingCommand from './commands/ping';\nimport pingComponent from './components/ping';\nimport echoCommand from './commands/echo';\nimport type { Env, CtxWithEnv } from './env';\n\nlet handler: ReturnType\u003ctypeof createHandler\u003cCtxWithEnv\u003e\u003e;\n\nconst worker: ExportedHandler\u003cEnv\u003e = {\n    fetch: async (request, env, ctx) =\u003e {\n        // Create the handler if it doesn't exist yet\n        handler ??= createHandler\u003cCtxWithEnv\u003e(\n            [ pingCommand, echoCommand ], // Array of commands to handle interactions for\n            [ pingComponent ],            // Array of components to handle interactions for\n            env.DISCORD_PUBLIC_KEY,       // Discord application public key\n            true,                         // Whether to log warnings for any invalid commands/components passed\n        );\n\n        // Run the handler, passing the environment to the command/component context\n        (ctx as CtxWithEnv).env = env;\n        const resp = await handler(request, ctx as CtxWithEnv);\n        if (resp) return resp;\n\n        // Fallback for any requests not handled by the handler\n        return new Response('Not found', { status: 404 });\n    },\n};\n\nexport default worker;\n```\n\nAs part of the build process, make sure to register the ping command with Discord.\n\n`tsup.config.ts`:\n\n```js\nimport { defineConfig } from 'tsup';\nimport { registerCommands } from 'workers-discord';\nimport dotenv from 'dotenv';\n\nimport pingCommand from './src/commands/ping';\nimport echoCommand from './src/commands/echo';\n\ndotenv.config({ path: '.dev.vars' });\n\nexport default defineConfig({\n    entry: ['src/index.ts'],\n    format: ['esm'],\n    dts: true,\n    sourcemap: true,\n    clean: true,\n    outDir: 'dist',\n    outExtension: () =\u003e ({ js: '.js' }),\n    onSuccess: async () =\u003e {\n        await registerCommands(\n            process.env.DISCORD_CLIENT_ID!,     // Discord application client ID\n            process.env.DISCORD_CLIENT_SECRET!, // Discord application client secret\n            [ pingCommand, echoCommand ],       // Array of commands to register with Discord\n            true,                               // Whether to log warnings for any invalid commands passed\n            process.env.DISCORD_GUILD_ID,       // Optional guild ID to register guild-specific commands\n        );\n    },\n});\n```\n\nConfigure Wrangler to use the built worker, and to have our secrets available.\n\n`wrangler.toml`:\n\n```toml\nname = \"\u003cworker_name\u003e\"\nmain = \"dist/index.js\"\naccount_id = \"\u003caccount_id\u003e\"\nworkers_dev = true\ncompatibility_date = \"2023-10-25\"\n\n[build]\ncommand = \"npm run build\"\nwatch_dir = \"src\"\n```\n\n`.dev.vars`:\n\n```ini\nDISCORD_PUBLIC_KEY=\u003cdiscord_public_key\u003e\nDISCORD_CLIENT_ID=\u003cdiscord_client_id\u003e\nDISCORD_CLIENT_SECRET=\u003cdiscord_client_secret\u003e\n# DISCORD_GUILD_ID=\u003cdiscord_guild_id\u003e\n```\n\nRun `npx wrangler login` to get your account ID, which should be added to `wrangler.toml`.\nThen, you can run `npx wrangler dev` to start the development server and register your commands.\n\n_You may want to use a tool like `cloudflared` to expose your development server to the work, so that you can test your commands in Discord._\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmattipv4%2Fworkers-discord","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmattipv4%2Fworkers-discord","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmattipv4%2Fworkers-discord/lists"}