From 81b75d3546b59018f9f93999b69506afae725fe9 Mon Sep 17 00:00:00 2001 From: James Shiffer Date: Sun, 8 Oct 2023 18:59:04 -0700 Subject: [PATCH] Random messages --- discord/.env.example | 5 +++++ discord/bot.ts | 39 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/discord/.env.example b/discord/.env.example index 6cccd4f..9962a74 100644 --- a/discord/.env.example +++ b/discord/.env.example @@ -1,3 +1,8 @@ TOKEN="sadkfl;jasdkl;fj" REACTIONS="💀,💯,😭" GUILD="123456789012345678" + +ENABLE_MOTD=1 +MOTD_CHANNEL="123456789012345678" +MOTD_HREF="https://fembooru.jp/post/list" +MOTD_QUERY="#tips" diff --git a/discord/bot.ts b/discord/bot.ts index 73f85db..3f188f9 100644 --- a/discord/bot.ts +++ b/discord/bot.ts @@ -3,7 +3,16 @@ * Scans the chat for reactions and updates the leaderboard database. */ -import { Client, Events, GatewayIntentBits, MessageReaction, PartialMessageReaction, Partials, User } from 'discord.js'; +import { + Client, + Events, + GatewayIntentBits, + MessageReaction, + PartialMessageReaction, + Partials, + TextChannel, + User +} from 'discord.js'; import { db, openDb, reactionEmojis, recordReaction, sync } from './util'; const client = new Client({ @@ -46,6 +55,31 @@ async function onMessageReactionChanged(reaction: MessageReaction | PartialMessa await recordReaction( reaction); } +async function fetchMotd() +{ + const res = await fetch(process.env.MOTD_HREF); + const xml = await res.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(xml, 'text/html'); + return doc.querySelector(process.env.MOTD_QUERY).textContent; +} + +async function scheduleRandomMessage(firstTime = false) +{ + if (!firstTime) { + const channel = await client.channels.fetch(process.env.MOTD_CHANNEL); + const randomMessage = await fetchMotd(); + await channel.send(randomMessage); + console.log(`[bot] Sent MOTD: ${randomMessage}`); + } + // wait between 2-8 hours + const timeoutMins = Math.random() * 360 + 120; + const scheduledTime = new Date(); + scheduledTime.setMinutes(scheduledTime.getMinutes() + timeoutMins); + console.log(`[bot] Next MOTD: ${scheduledTime}`); + setTimeout(scheduleRandomMessage, timeoutMins * 60 * 1000); +} + client.on(Events.MessageReactionAdd, onMessageReactionChanged); client.on(Events.MessageReactionRemove, onMessageReactionChanged); @@ -58,6 +92,9 @@ async function startup() { console.log("[bot] Logging in..."); await client.login(process.env.TOKEN); await sync(client.guilds); + if (process.env.ENABLE_MOTD) { + await scheduleRandomMessage(true); + } } startup();