@glenstack/cf-workers-discord-bot
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

Cloudflare Workers Discord Bot

Interact with Discord from within Cloudflare Workers.

Installation

npm install --save @glenstack/cf-workers-discord-bot

Usage

createSlashCommandHandler

import {
  createSlashCommandHandler,
  ApplicationCommand,
  InteractionHandler,
  Interaction,
  InteractionResponse,
  InteractionResponseType,
} from "@glenstack/cf-workers-discord-bot";

const helloCommand: ApplicationCommand = {
  name: "hello",
  description: "Bot will say hello to you!",
};

const helloHandler: InteractionHandler = async (
  interaction: Interaction
): Promise<InteractionResponse> => {
  const userID = interaction.member.user.id;

  return {
    type: InteractionResponseType.ChannelMessageWithSource,
    data: {
      content: `Hello, <@${userID}>!`,
      allowed_mentions: {
        users: [userID],
      },
    },
  };
};

const slashCommandHandler = createSlashCommandHandler({
  applicationID: "799627301675466772",
  applicationSecret: APPLICATION_SECRET, // You should store this in a secret
  publicKey: "1b780f7f71ac39645d44cc4dce8fa78c860d0157cb0912d755b7a7cb95394532",
  commands: [[helloCommand, helloHandler]],
});

addEventListener("fetch", (event) => {
  event.respondWith(slashCommandHandler(event.request));
});

createSlashCommandHandler takes one parameter:

  1. An object with the following parameters:

It returns a function which takes a Request and returns a Promise of a Response. It should typically be given to the event.respondWith function.

This makes your application respond to three types of Requests:

  • GET /: Redirects the user to Discord to authorize the bot on a server.
  • POST /interaction: The incoming webhook from Discord to respond to Slash Commands or Pings. Note: this URL needs to be configured in the Discord Developer Portal as the "Interactions Endpoint URL" e.g. https://my-discord-bot.workers.dev/interaction
  • GET /setup: Registers the commands with Discord. Note: this endpoint must be visited once to initialize the new commands, and again everytime the commands are updated.

Readme

Keywords

none

Package Sidebar

Install

npm i @glenstack/cf-workers-discord-bot

Weekly Downloads

3

Version

1.1.1

License

MIT

Unpacked Size

22.9 kB

Total Files

13

Last publish

Collaborators

  • gregbrimble