initial bot commit

This commit is contained in:
flyingtoasters
2025-03-26 12:19:43 -04:00
parent 4f5605f3e0
commit 01ca7d44d9
20 changed files with 7210 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/cloudflare-sample-app

Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

BIN
images/banner.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

6
package-lock.json generated Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "toyo-discord-bot",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

12
toyobot/.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space

172
toyobot/.gitignore vendored Normal file
View File

@@ -0,0 +1,172 @@
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
# wrangler project
.dev.vars
.wrangler/

6
toyobot/.prettierrc Normal file
View File

@@ -0,0 +1,6 @@
{
"printWidth": 140,
"singleQuote": true,
"semi": true,
"useTabs": true
}

5
toyobot/.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"files.associations": {
"wrangler.json": "jsonc"
}
}

3
toyobot/example.dev.vars Normal file
View File

@@ -0,0 +1,3 @@
DISCORD_APPLICATION_ID: ".."
DISCORD_PUBLIC_KEY: ".."
DISCORD_TOKEN: ".."

6652
toyobot/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
toyobot/package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "toyobot",
"author": "Chris Holt <holtcm01@gmail.com>",
"description": "A complex discord bot that interacts with Google Docs and yotoplay.com",
"type": "module",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "wrangler dev",
"dev": "wrangler dev",
"ngrok": "ngrok http 8787",
"test": "vitest",
"fix": "eslint --fix '**/*.js'",
"lint": "eslint '**/*.js'",
"register": "node src/register.js",
"publish": "wrangler deploy",
"deploy": "wrangler deploy"
},
"dependencies": {
"discord-interactions": "^4.0.0",
"itty-router": "^5.0.9"
},
"devDependencies": {
"@eslint/js": "^9.1.1",
"c8": "^10.1.2",
"chai": "^5.0.0",
"dotenv": "^16.0.3",
"eslint": "^9.1.0",
"eslint-config-prettier": "^10.0.2",
"eslint-plugin-prettier": "^5.1.3",
"globals": "^16.0.0",
"mocha": "^11.0.0",
"ngrok": "^5.0.0-beta.2",
"prettier": "^3.2.5",
"sinon": "^19.0.2",
"wrangler": "^4.4.1",
"@cloudflare/vitest-pool-workers": "^0.7.5",
"vitest": "~3.0.7"
}
}

10
toyobot/src/commands.js Normal file
View File

@@ -0,0 +1,10 @@
/**
* Share command metadata from a common spot to be used for both runtime
* and registration.
*/
export const AWW_COMMAND = {
name: 'awwww',
description: 'Drop some cuteness on this channel.',
};

15
toyobot/src/index.js Normal file
View File

@@ -0,0 +1,15 @@
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `npm run deploy` to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
export default {
async fetch(request, env, ctx) {
return new Response('Hello World!');
},
};

43
toyobot/src/reddit.js Normal file
View File

@@ -0,0 +1,43 @@
/**
* Reach out to the reddit API, and get the first page of results from
* r/aww. Filter out posts without readily available images or videos,
* and return a random result.
* @returns The url of an image or video which is cute.
*/
export async function getCuteUrl() {
const response = await fetch(redditUrl, {
headers: {
'User-Agent': 'justinbeckwith:awwbot:v1.0.0 (by /u/justinblat)',
},
});
if (!response.ok) {
let errorText = `Error fetching ${response.url}: ${response.status} ${response.statusText}`;
try {
const error = await response.text();
if (error) {
errorText = `${errorText} \n\n ${error}`;
}
} catch {
// ignore
}
throw new Error(errorText);
}
const data = await response.json();
const posts = data.data.children
.map((post) => {
if (post.is_gallery) {
return '';
}
return (
post.data?.media?.reddit_video?.fallback_url ||
post.data?.secure_media?.reddit_video?.fallback_url ||
post.data?.url
);
})
.filter((post) => !!post);
const randomIndex = Math.floor(Math.random() * posts.length);
const randomPost = posts[randomIndex];
return randomPost;
}
export const redditUrl = 'https://www.reddit.com/r/aww/hot.json';

56
toyobot/src/register.js Normal file
View File

@@ -0,0 +1,56 @@
import { AWW_COMMAND } from './commands.js';
import dotenv from 'dotenv';
import process from 'node:process';
/**
* This file is meant to be run from the command line, and is not used by the
* application server. It's allowed to use node.js primitives, and only needs
* to be run once.
*/
dotenv.config({ path: '.dev.vars' });
const token = process.env.DISCORD_TOKEN;
const applicationId = process.env.DISCORD_APPLICATION_ID;
if (!token) {
throw new Error('The DISCORD_TOKEN environment variable is required.');
}
if (!applicationId) {
throw new Error(
'The DISCORD_APPLICATION_ID environment variable is required.',
);
}
/**
* Register all commands globally. This can take o(minutes), so wait until
* you're sure these are the commands you want.
*/
const url = `https://discord.com/api/v10/applications/${applicationId}/commands`;
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bot ${token}`,
},
method: 'PUT',
body: JSON.stringify([AWW_COMMAND]),
});
if (response.ok) {
console.log('Registered all commands');
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
} else {
console.error('Error registering commands');
let errorText = `Error registering commands \n ${response.url}: ${response.status} ${response.statusText}`;
try {
const error = await response.text();
if (error) {
errorText = `${errorText} \n\n ${error}`;
}
} catch (err) {
console.error('Error reading body from request:', err);
}
console.error(errorText);
}

111
toyobot/src/server.js Normal file
View File

@@ -0,0 +1,111 @@
/**
* The core server that runs on a Cloudflare worker.
*/
import { AutoRouter } from 'itty-router';
import {
InteractionResponseType,
InteractionType,
verifyKey,
} from 'discord-interactions';
import { AWW_COMMAND } from './commands.js';
import { getCuteUrl } from './reddit.js';
import { InteractionResponseFlags } from 'discord-interactions';
class JsonResponse extends Response {
constructor(body, init) {
const jsonBody = JSON.stringify(body);
init = init || {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
};
super(jsonBody, init);
}
}
const router = AutoRouter();
/**
* A simple :wave: hello page to verify the worker is working.
*/
router.get('/', (request, env) => {
return new Response(`👋 ${env.DISCORD_APPLICATION_ID}`);
});
/**
* Main route for all requests sent from Discord. All incoming messages will
* include a JSON payload described here:
* https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object
*/
router.post('/', async (request, env) => {
const { isValid, interaction } = await server.verifyDiscordRequest(
request,
env,
);
if (!isValid || !interaction) {
return new Response('Bad request signature.', { status: 401 });
}
if (interaction.type === InteractionType.PING) {
// The `PING` message is used during the initial webhook handshake, and is
// required to configure the webhook in the developer portal.
return new JsonResponse({
type: InteractionResponseType.PONG,
});
}
if (interaction.type === InteractionType.APPLICATION_COMMAND) {
// Most user commands will come as `APPLICATION_COMMAND`.
switch (interaction.data.name.toLowerCase()) {
case AWW_COMMAND.name.toLowerCase(): {
const cuteUrl = await getCuteUrl();
return new JsonResponse({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: cuteUrl,
},
});
}
case INVITE_COMMAND.name.toLowerCase(): {
const applicationId = env.DISCORD_APPLICATION_ID;
const INVITE_URL = `https://discord.com/oauth2/authorize?client_id=${applicationId}&scope=applications.commands`;
return new JsonResponse({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: INVITE_URL,
flags: InteractionResponseFlags.EPHEMERAL,
},
});
}
default:
return new JsonResponse({ error: 'Unknown Type' }, { status: 400 });
}
}
console.error('Unknown Type');
return new JsonResponse({ error: 'Unknown Type' }, { status: 400 });
});
router.all('*', () => new Response('Not Found.', { status: 404 }));
async function verifyDiscordRequest(request, env) {
const signature = request.headers.get('x-signature-ed25519');
const timestamp = request.headers.get('x-signature-timestamp');
const body = await request.text();
const isValidRequest =
signature &&
timestamp &&
(await verifyKey(body, signature, timestamp, env.DISCORD_PUBLIC_KEY));
if (!isValidRequest) {
return { isValid: false };
}
return { interaction: JSON.parse(body), isValid: true };
}
const server = {
verifyDiscordRequest,
fetch: router.fetch,
};
export default server;

View File

@@ -0,0 +1,20 @@
import { env, createExecutionContext, waitOnExecutionContext, SELF } from 'cloudflare:test';
import { describe, it, expect } from 'vitest';
import worker from '../src';
describe('Hello World worker', () => {
it('responds with Hello World! (unit style)', async () => {
const request = new Request('http://example.com');
// Create an empty context to pass to `worker.fetch()`.
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
// Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
await waitOnExecutionContext(ctx);
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`);
});
it('responds with Hello World! (integration style)', async () => {
const response = await SELF.fetch('http://example.com');
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`);
});
});

11
toyobot/vitest.config.js Normal file
View File

@@ -0,0 +1,11 @@
import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';
export default defineWorkersConfig({
test: {
poolOptions: {
workers: {
wrangler: { configPath: './wrangler.jsonc' },
},
},
},
});

47
toyobot/wrangler.jsonc Normal file
View File

@@ -0,0 +1,47 @@
/**
* For more details on how to configure Wrangler, refer to:
* https://developers.cloudflare.com/workers/wrangler/configuration/
*/
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "toyobot",
"main": "src/server.js",
"compatibility_date": "2025-03-21",
"observability": {
"enabled": true
}
/**
* Smart Placement
* Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
*/
// "placement": { "mode": "smart" },
/**
* Bindings
* Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform, including
* databases, object storage, AI inference, real-time communication and more.
* https://developers.cloudflare.com/workers/runtime-apis/bindings/
*/
/**
* Environment Variables
* https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
*/
// "vars": { "MY_VARIABLE": "production_value" },
/**
* Note: Use secrets to store sensitive data.
* https://developers.cloudflare.com/workers/configuration/secrets/
*/
/**
* Static Assets
* https://developers.cloudflare.com/workers/static-assets/binding/
*/
// "assets": { "directory": "./public/", "binding": "ASSETS" },
/**
* Service Bindings (communicate between multiple Workers)
* https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings
*/
// "services": [{ "binding": "MY_SERVICE", "service": "my-service" }]
}