From 6141dffa68cd11bd6af36cea336aa34491008c98 Mon Sep 17 00:00:00 2001 From: Wroclaw Date: Sat, 25 Mar 2023 11:24:43 +0100 Subject: [PATCH] Defer responding to a message request Previously if two message requests appered in a short timespan in the same channel, the bot would reply twice (in two messages) for the first message. This commit fixes that, by queuing message requests and responding to them in the chronological order based on a channelId. (requests are queued to a queue identified by channelId) fixes #4 --- src/index.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index fe5a3bd..9737021 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,10 +21,23 @@ discord.on("ready", async event => { console.log(`Connected to Discord as ${event.user.tag} (${event.user.id})`); }); +const channelsRunning: DiscordApi.Collection = new DiscordApi.Collection(); + discord.on("messageCreate", async message => { if (message.author.bot) return; if (!message.mentions.has(message.client.user)) return; + const messagesForChannel = channelsRunning.ensure(message.channelId, () => {return [] as DiscordApi.Message[];} ); + const shouldStart = messagesForChannel.length == 0; + messagesForChannel.push(message); + if (shouldStart) + onMessage(message.channelId); +}); + +async function onMessage(channel: string) { + const channelQueue = channelsRunning.get(channel) as DiscordApi.Message[]; + const message = channelQueue.at(0) as DiscordApi.Message; + try { let messages: DiscordApi.Collection = await message.channel.messages.fetch({ limit: config.limits.messages, cache: false }); @@ -73,6 +86,12 @@ discord.on("messageCreate", async message => { } }); } -}); + + channelQueue.shift(); + if (channelQueue.length == 0) + channelsRunning.delete(channel); + else + onMessage(channel); +} discord.login(config.tokens.Discord);