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
This commit is contained in:
parent
02730ff488
commit
6141dffa68
1 changed files with 20 additions and 1 deletions
21
src/index.ts
21
src/index.ts
|
@ -21,10 +21,23 @@ discord.on("ready", async event => {
|
||||||
console.log(`Connected to Discord as ${event.user.tag} (${event.user.id})`);
|
console.log(`Connected to Discord as ${event.user.tag} (${event.user.id})`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const channelsRunning: DiscordApi.Collection<string, DiscordApi.Message[]> = new DiscordApi.Collection();
|
||||||
|
|
||||||
discord.on("messageCreate", async message => {
|
discord.on("messageCreate", async message => {
|
||||||
if (message.author.bot) return;
|
if (message.author.bot) return;
|
||||||
if (!message.mentions.has(message.client.user)) 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 {
|
try {
|
||||||
let messages: DiscordApi.Collection<string, DiscordApi.Message> = await message.channel.messages.fetch({ limit: config.limits.messages, cache: false });
|
let messages: DiscordApi.Collection<string, DiscordApi.Message> = 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);
|
discord.login(config.tokens.Discord);
|
||||||
|
|
Loading…
Reference in a new issue