I’m working on a Discord bot using JavaScript and running into a problem with reaction handling. The bot should respond when users click on reactions, but it’s triggering multiple times when there are several messages with reactions present.
My bot is designed to roll dice and let users reroll by clicking a reaction emoji. Everything works fine with one message, but when multiple messages have the same reaction emoji, the bot processes all of them instead of just the one the user clicked.
Here’s my main handler:
bot.on('message', msg => {
if(!msg.content.startsWith(PREFIX) || msg.author.bot) return;
let params = msg.content.substring(PREFIX.length).split(" ");
switch (params[0].toLowerCase()) {
case "dice": case "d":
if(!params[1] || params[1].indexOf("d") == -1) return msg.channel.send('Bad dice format');
bot.commands.get('gamebot').HandleDice(msg, params, bot);
break;
}
});
And here’s the dice rolling module:
module.exports = {
name: 'gamebot',
description: 'Dice system for RPG',
async HandleDice(msg, params, botClient) {
const targetChannel = 'YYYYYYYYYYYYYYYYY';
const rollAgain = '🎲';
if(!params[2]) {
var result = RollCalculator(params[1]);
} else if (params[2] == "s" || params[2] == "S") {
var result = RollCalculator(params[1], true);
}
let diceMessage = await msg.channel.send(result);
diceMessage.react(rollAgain);
botClient.on('messageReactionAdd', async (reactionObj, userObj) => {
if(reactionObj.message.partial) await reactionObj.message.fetch();
if(reactionObj.partial) await reactionObj.fetch();
if(userObj.bot) return;
if(!reactionObj.message.guild) return;
if(reactionObj.message.channel.id == targetChannel) {
if(reactionObj.emoji.name === rollAgain) {
var freshRoll = RollCalculator(params[1]);
await msg.channel.send(freshRoll);
await reactionObj.users.remove(userObj);
}
}
});
}
}
How can I fix this so the bot only responds to reactions on the specific message instead of all messages with that emoji? I’m pretty new to Discord bot development so any help would be great.