Something went wrong. Try again.
A Discord bot that does Osu renders with Danser. Not built for scale, but instead small friend-group servers.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import { Client, type ClientOptions, Collection, DiscordAPIError, Events, type Interaction, RESTJSONErrorCodes, Routes,} from "discord.js";import { env } from "./env.ts";import type { Command, Services } from "./types.ts";
export class Bot extends Client { readonly commands = new Collection<string, Command>(); readonly services: Services;
constructor(options: ClientOptions, services: Services) { super(options); this.services = services;
this.on(Events.InteractionCreate, (interaction) => { // Event listeners must return void, so the promise is settled here // instead of awaited; a rejection must never escape a listener. // eslint-disable-next-line unicorn/prefer-await -- cannot await inside a void-returning listener this.handleInteraction(interaction).catch((error: unknown) => { console.error("Unhandled error while running a command:", error); }); }); }
private async handleInteraction(interaction: Interaction): Promise<void> { if (!interaction.isChatInputCommand()) { return; }
const command = this.commands.get(interaction.commandName);
if (!command) { console.warn(`Received unknown command /${interaction.commandName}.`);
return; }
await command.execute(interaction, this.services); }
/** Registers a local slash command to later be published to Discord's API. */ registerSlashCommand(command: Command): void { this.commands.set(command.definition.name, command); }
/** Publishes all registered slash commands to every guild in ALLOWED_GUILD_IDS. Guild commands are live immediately. Each guild's command list is overwritten wholesale, so removed commands disappear too. Uses the client's own REST instance, which is authenticated by login(), so call this after login. */ async publishSlashCommands(): Promise<void> { console.info("Publishing slash commands...");
const body = this.commands.map((command) => command.definition.toJSON());
for (const guildId of env.ALLOWED_GUILD_IDS) { try { await this.rest.put( Routes.applicationGuildCommands(env.DISCORD_APP_ID, guildId), { body }, );
console.info( `Published ${String(body.length)} slash commands to guild ${guildId}.`, ); } catch (error) { // The bot has not been invited to this guild yet. Keep going so one // missing guild does not block the others. if ( error instanceof DiscordAPIError && error.code === RESTJSONErrorCodes.MissingAccess ) { console.warn( `Skipped guild ${guildId}: the bot is not a member of it.`, ); } else { throw error; } } } }}