This guide provides a basic outline to set up a Discord bot and integrate it with Cloudflare Workers. Further details and code specifics for each step will be needed based on your specific requirements and programming language preferences.

This guide assumes you are having a cloudflare account
We are going to use typescript in this guide
1

Creating Discord Application

Creating a Discord Bot and Obtaining Credentials

  1. Go to the Discord Developer Portal.
  2. Click on “New Application” and give it a name.
  3. Navigate to the “Bot” tab on the left sidebar.
  4. Click “Add Bot” and confirm.
  5. Note down the Client ID under the “APP DETAILS” section.
  6. Click “Copy” under the “TOKEN” section to get the bot token.
2

Inviting Bot to Server

  1. Still in the Developer Portal, go to the “OAuth2” tab.
  2. Under “OAuth2 URL Generator,” select “bot” and “application commands” in scopes.
  3. Copy the generated URL and paste it into your browser.
  4. Authorize the bot to a server you have access to
3

Creating a new project

  1. Open your favorite code editor
  2. Create a new folder
  3. Run npm init/yarn init/pnpm init to initialize a package.json
  4. Run npm install yor.ts@latest/yarn add yor.ts@latest/pnpm install yor.ts@latest to install yor.ts
4

Downloading cloudflare workers cli

  1. Run npm install -g wrangler/yarn global add wrangler/pnpm add -g wrangler to install the cli

  2. Run wrangler login to login to your cloudflare account

  3. Run wrangler init to create a new project

  4. Put the following in wrangler.toml:

name = "interactions"
main = "./dist/index.js"
node_compat = true
compatibility_date = "2023-10-22"

vars = {
  DISCORD_APP_ID = "CLIENT_ID"
  DISCORD_BOT_TOKEN = "BOT_TOKEN"
  DISCORD_PUBLIC_KEY = "PUBLIC_KEY"
}
5

Creating src/index.ts

  1. Add the following to src/index.ts:
import { CommandContext, YorClient, YorSlashCommand } from "yor.ts";
import { SlashCommandBuilder } from "yor.ts/builders";

export interface Env {
    DISCORD_APP_ID: string;
    DISCORD_BOT_TOKEN: string;
    DISCORD_PUBLIC_KEY: string;
}

class PingCommand extends YorSlashCommand {
    public builder = new SlashCommandBuilder()
        .setName("ping")
        .setDescription("Replies with Pong!");

    public execute = (context: CommandContext) => {
        context.send({ content: "Pong!" });
    }
}

export default {
    fetch: async (request: Request, env: Env, ctx: ExecutionContext) => {
        const client = new YorClient({
            application: {
                id: env.DISCORD_APP_ID,
                publicKey: env.DISCORD_PUBLIC_KEY
            },
            token: env.DISCORD_BOT_TOKEN
        });

        const command = new PingCommand();
        client.registerCommand(command);

        const response = await yor.handleRequest(request, env, ctx);

        return new Response(JSON.stringify(response), {
            headers: {
                "content-type": "application/json"
            }
        });
    }
}
6

Esbuild and polyfill

  1. Install esbuild and esbuild-plugin-node-polyfill: Run npm install --save-dev esbuild esbuild-plugin-node-polyfill or yarn add --dev esbuild esbuild-plugin-node-polyfill or pnpm add --save-dev esbuild esbuild-plugin-node-polyfill to install these packages as dev dependencies.

  2. Update the package.json file: Add the following scripts to the scripts section of your package.json file:

"build": "node build.js",
  1. Create build.js.

  2. Add the following to the build.js config file:

const { polyfillNode } = require('esbuild-plugin-polyfill-node');

require('esbuild')
   .build({
     minify: true,
     bundle: true,
     format: 'esm',
     entryPoints: ['src/index.ts'],
     outdir: 'dist',
     platform: 'browser',
     target: 'esnext',
     sourcemap: true,
     logLevel: 'info',
     plugins: [
         polyfillNode({
            polyfills: {
              url: true,
              util: true,
           },
        }),
    ],
}).catch(() => process.exit(1));
7

Running the project

  1. Run npm run build or yarn build or pnpm build to build the project
  2. Run wrangler deploy to deploy your project
8

Testing the bot

  1. Pick the URL from the wrangler logs
  2. Open the URL in your browser
  3. Go to the discord developer portal and add the URL and submit it as interactions endpoint
9

Testing to see if it works

  1. Open discord server you invited your bot into
  2. Run /ping

Was this page helpful?