A pure-Rust serverless discord chatbot hosted on Cloudflare Workers.

Overview

About

A pure-Rust serverless discord chatbot hosted on Cloudflare Workers. With a free account you have up to 100k requests per day. For storing state you can use the bundled workers-rs crate to access KV or Durable objects.

This template is designed for compiling Rust to WebAssembly and publishing the resulting worker to Cloudflare's edge infrastructure.

Setup

  1. Signup for a Cloudflare account, in the dashboard setup a subdomain (i.e <mydomain>.workers.dev)
  2. Setup a worker project named bot (i.e bot.<mydomain>.workers.dev) or pick your own name and update wrangler.toml
  3. Install wrangler CLI with cargo install wrangler and authenticate with cloudflare via wrangler config
  4. Create a new discord app at https://discord.com/developers/applications and copy your token/application_id/public_key
  5. Pass those secrets to your bot with wrangler secret put DISCORD_TOKEN, wrangler secret put DISCORD_PUBLIC_KEY, wrangler secret put DISCORD_APPLICATION_ID
  6. Add bot permissions and grab your Oauth url to invite the bot to your server
  7. Publish the demo app with wrangler publish. The template bot contains a single hello command with a dummy autocomplete argument.
  8. Put your bot domain https://bot.<mydomain>.workers.dev in the INTERACTIONS ENDPOINT URL in your discord app page from step 4
  9. After initial deployment and each time you add a new command on your bot you need to register it with the discord api. To do that simply curl -X POST http://bot.<mydomain>.workers.dev/register

You should now be able to run the /hello command on discord

Adding new commands

To add a new command simply implement the Command trait. For example to add a ping command

  1. create a file src/commands/ping.rs
use crate::interaction::{
    InteractionApplicationCommandCallbackData, ApplicationCommandOption, ApplicationCommandOptionChoice, ApplicationCommandInteractionDataOption, ApplicationCommandOptionType
};
use crate::error::InteractionError;
use crate::command::Command;

use async_trait::async_trait;


pub(crate) struct Ping {}

#[async_trait(?Send)]
impl Command for Ping {
    async fn respond(&self, _options: &Option<Vec<ApplicationCommandInteractionDataOption>>, _ctx: &mut worker::RouteContext<()>) -> Result<InteractionApplicationCommandCallbackData, InteractionError>{
        Ok(InteractionApplicationCommandCallbackData {
            content: Some("Pong".to_string()),
            choices: None,
            embeds: None
        })
    }

    fn name(&self) -> String{
        "ping".into()
    }

    fn description(&self) -> String {
        "Send a ping".into()
    }

    fn options(&self) -> Option<Vec<ApplicationCommandOption>> {
        // add any arguments/choices here, more info at https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure
        None
    }

    async fn autocomplete(&self, _options: &Option<Vec<ApplicationCommandInteractionDataOption>>, _ctx: &mut worker::RouteContext<()>) -> 
        None
    }
  1. add your new module in src/commands/mod.rs
  2. Register your command in init_commands in src/command.rs
pub(crate) fn init_commands() -> Vec<Box<dyn Command + Sync>> {
    let mut v : Vec<Box<dyn Command + Sync>> = Vec::new();
    v.push(Box::new(commands::hello::Hello {}));
    // Add this line
    v.push(Box::new(commands::ping::Ping {}));
    v
}
  1. publish your package with wrangler publish
  2. register your new command with discord with curl -X POST http://bot.<mydomain>.workers.dev/register

You can store and access state using the ctx context object passed to the respond and autocomplete methods, for example:

let kv = ctx.kv("my_namespace")?;  // the namespace must be first registered on cloudflare dashboard
let my_val =  kv.get("my_key").text().await?;
kv.put("foo", "bar")?.execute().await?;

Local Dev

With wrangler, you can build, test, and deploy your Worker with the following commands:

# compiles your project to WebAssembly and will warn of any issues
wrangler build 

# run your Worker in an ideal development workflow (with a local server, file watcher & more)
wrangler dev

# deploy your Worker globally to the Cloudflare network (update your wrangler.toml file for configuration)
wrangler publish

you can use ngrok to tunnel traffic into your local machine, more info here

WebAssembly

workers-rs (the Rust SDK for Cloudflare Workers used in this template) is meant to be executed as compiled WebAssembly, and as such so must all the code you write and depend upon. All crates and modules used in Rust-based Workers projects have to compile to the wasm32-unknown-unknown triple.

Read more about this on the workers-rs project README.

Credits

based on stateless-discord-bot

You might also like...
Rust bindings to Cloudflare Worker KV Stores using wasm-bindgen and js-sys.

worker-kv Rust bindings to Cloudflare Worker KV Stores using wasm-bindgen and js-sys

Cloudflare worker for embedding polls anywhere.

poll.fizzy.wtf Cloudflare worker for embedding polls anywhere. ๐Ÿ• Pineapple on pizza? ๐Ÿ Yes ๐Ÿ‘ No ๐Ÿ‘Ž Total Features Unlimited polls and unlimited opt

CLI to create redirections in CloudFlare to Zoom meetings.
CLI to create redirections in CloudFlare to Zoom meetings.

boteco boteco is a CLI to create redirections in CloudFlare to Zoom meetings. Requirements CloudFlare page rules In the domain you want to use, you ne

CFD is a tool that allows you to check one or more domains to see if they are protected by CloudFlare or not.
CFD is a tool that allows you to check one or more domains to see if they are protected by CloudFlare or not.

CFD is a tool that allows you to check one or more domains to see if they are protected by CloudFlare or not. The check is carried out based on five criteria: 3 headers in the HTTP response, IP, and SSL certificate issuer. The check result can be displayed on the screen or saved to a file.

Pass cloudflare IUAM using headless chrome without hassle.
Pass cloudflare IUAM using headless chrome without hassle.

FlarelessHeadlessChrome Pass cloudflare turnstile challenge using patched chrome binary (Windows/Linux x64). How it works Currently, with new headless

๐Ÿฆ€ CLI for Cloudflare API ๐Ÿฆ€
๐Ÿฆ€ CLI for Cloudflare API ๐Ÿฆ€

๐Ÿ›  CLI๏ธ to interact with Cloudflare APIs ๐Ÿฅณ An excuse to write some Rust ๐Ÿ‘ท Under heavy development Setup Install Rust ๐Ÿ“ curl --proto '=https' --tlsv

Scan all IP nodes of CloudFlare to find the fastest IP node.
Scan all IP nodes of CloudFlare to find the fastest IP node.

ไธญๆ–‡็‰ˆ | English ๐Ÿ“– Introduction Scan all IP nodes of CloudFlare to find the fastest IP node. โšก๏ธ Get Started ๐Ÿ”จ๏ธ Build git clone https://github.com/golan

A Discord bot for sending GeoGuessr challenge links that uses the GeoGuessr API written in rust.

GeoGuessr-bot-rs This is a simple implementation of a discord bot that send GeoGuessr-challenge links on demand. Features: Slash-commands Lightning-fa

๐Ÿฆœ A hassle-free, highly performant, host it yourself Discord music bot built with Serenity in Rust. Powered by youtube-dl and Genius.

๐Ÿฆœ A hassle-free, highly performant and fast evolving Discord music bot built with Serenity in Rust. Deployment Usage Just create a bot account, copy

Comments
  • fix: crude allow interaction endpoint, domain verification request ping

    fix: crude allow interaction endpoint, domain verification request ping

    Note: I am very novice with rust so this is very likely to be the non optimal way of fixing this issue.

    Currently the application crashes if a domain verification request is sent to it (the interactions URL being added in the discord developer portal).

    This fix crudely handles the error and attempts to de-serialize with a verification request before outright failing the JSON parse.

    opened by yoroshikun 1
Owner
Mike Dallas
Mike Dallas
Blueboat is an open-source alternative to Cloudflare Workers. The monolithic engine for serverless web apps.

Blueboat Blueboat is an open-source alternative to Cloudflare Workers. Blueboat aims to be a developer-friendly, multi-tenant platform for serverless

Heyang Zhou 1.8k Jan 9, 2023
Verify Discord interactions on Cloudflare Workers with Twilight

twilight-cloudflare-workers Verify Discord interactions on Cloudflare Workers with Twilight. API The primary function in the API is process. It takes

Zeyla 5 Jun 6, 2022
Edgelord is a library for Cloudflare Workers. You can scaffold a basic bot for discord, slack, etc.

Edge Computing + chลซnibyล = Edgelord โœจ ?? Edgelord Edgelord is now working. You can contribute for it. Edgelord is a Rust library for cloudflare worke

null 23 Dec 26, 2022
Log your spending in seconds with short text snippets. Powered by Rust, Cloudflare Workers and Svelte.

FastSpend Log your daily spending lightning fast with short text snippets! FastSpend is a tool to log your spending in seconds, powered by a lightning

Phoomparin Mano 24 Sep 13, 2022
Telegram Bot Template with Cloudflare Workers

cf-workers-telegram-bot-template Usage This template starts you off with a src/lib.rs file, acting as an entrypoint for requests hitting your Worker.

Lee Taehoon 2 Sep 23, 2021
A template for kick starting a Cloudflare worker project using workers-rs.

Getting Started A template for kick starting a Cloudflare worker project using workers-rs. This template is designed for compiling Rust to WebAssembly

Abid Omar 1 Oct 13, 2021
A collection of serverless apps that show how Fermyon's Serverless AI

A collection of serverless apps that show how Fermyon's Serverless AI (currently in private beta) works. Reference: https://developer.fermyon.com/spin/serverless-ai-tutorial

Fermyon 15 Oct 20, 2023
A rust(serenity) based discord bot for the hacksquad discord server

A Discord Bot for Hacksquad How to Deploy? Requirements Docker Docker Compose Steps To Run Copy the docker-compose.yml and .env.example files to your

HackSquad 5 Jan 4, 2023
Temp repo to document problems with workers-rs

This is a temporarily repo to share some worker-rs code that is giving me problems. See also: https://github.com/cloudflare/workers-rs/issues/94 Versi

Andrew Chin 0 Dec 6, 2021
A Discord bot focused on addressing the inherent problems with Discord, to allow a more socialist/anarchist organization of servers.

ACABot A Discord bot focused on addressing the inherent problems with Discord, to allow a more socialist/anarchist organization of servers (or "guilds

null 4 May 3, 2022