char-slop/city-role-bot

discord auto role applicator bot for charlotte polycule city

git clone https://git.t4t.associates/char-slop/city-role-bot

Charlotte Somsimplifyd72003f

main
2.2 KiB57 linesraw
1import {
2  Client,
3  Intents,
4  type ClientEvents,
5  type CreateGuildApplicationCommandOptions
6} from 'oceanic.js'
7import reactrole from './commands/reactrole.ts'
8import { reactionKey } from './emoji.ts'
9import { rosepack } from './rosepack.ts'
10import { panels } from './store.ts'
11import { applyReaction, syncPanels } from './sync.ts'
12
13const registry = rosepack.createRegistry({ slashCommands: [reactrole] })
14
15const token = process.env.DISCORD_TOKEN
16const applicationID = process.env.DISCORD_APPLICATION_ID
17if (token === undefined || applicationID === undefined) {
18  throw new Error('set DISCORD_TOKEN and DISCORD_APPLICATION_ID in .env before starting.')
19}
20
21const client = new Client({
22  auth: `Bot ${token}`,
23  gateway: { intents: Intents.GUILDS | Intents.GUILD_MESSAGE_REACTIONS }
24})
25
26client.on('interactionCreate', (interaction) => registry.dispatch({ app: undefined, interaction }))
27
28const onReaction =
29  (reacted: boolean) =>
30  async (...[message, reactor, reaction]: ClientEvents['messageReactionRemove']) => {
31    const panel = panels.get(message.id)
32    if (panel === undefined || reactionKey(reaction.emoji) !== panel.emoji) return
33    if ('bot' in reactor && reactor.bot) return
34    await applyReaction(client, message.id, panel, reactor.id, reacted)
35  }
36client.on('messageReactionAdd', onReaction(true))
37client.on('messageReactionRemove', onReaction(false))
38
39client.once('ready', async () => {
40  if (client.application.id !== applicationID) {
41    throw new Error('DISCORD_APPLICATION_ID does not match the connected bot application.')
42  }
43  const devGuildID = process.env.DISCORD_DEV_GUILD_ID
44  if (devGuildID !== undefined && devGuildID !== '') {
45    // the registry only holds slash commands, so every payload is guild-installable
46    await client.rest.applications.bulkEditGuildCommands(applicationID, devGuildID, [
47      ...(registry.payload as readonly CreateGuildApplicationCommandOptions[])
48    ])
49    console.log(`registered ${registry.payload.length} commands in dev guild ${devGuildID}`)
50  } else {
51    const registered = await registry.registerGlobal({ applicationID, client })
52    console.log(`registered ${registered.length} global commands`)
53  }
54  await syncPanels(client)
55})
56
57await client.connect()