I'm having problems while adding multiple reactions to a message (trying to add 8-9).
Basically, the script adds the reactions normally if you wait, but if you react to a emoji before the scripts add them all, it keeps trying to add the rest of the emojis even after the message already got deleted, throwing the error below.
(node:17500) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at RequestHandler.execute (C:\Users\#######\Documents\project-folder\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:89:5)
So, any idea of what I'm doing wrong?
// Context
message.channel.send({ embed: randomEmbed }).then((msg) => {
msg.react(emNumber[0]).then(() => {
for (let i = 0; i < dcArr.length && !msg.deleted; i++) {
if (dcArr[i]["server_id"] == user.server_id) continue;
msg.react(emNumber[i + 1]);
}
});
var filter = (reaction, user) => {
return (
emNumber.slice(0, dcArr.length - 1).includes(reaction.emoji.name) &&
user.id === discId
);
};
msg
.awaitReactions(filter, { max: 1, time: 20000, errors: ["time"] })
.then(async (collected) => {
msg.delete();
message.channel.send({ embed: anotherRandomEmbed }).then((msg) => {
msg.react(emThumbs[1]);
msg.react(emThumbs[0]);
// Something
var filter = (reaction, user) => {
return emThumbs.includes(reaction.emoji.name) && user.id === discId;
};
msg
.awaitReactions(filter, { max: 1, time: 20000, errors: ["time"] })
.then(async (collected) => {
// Something else
});
});
});
});
Related
I'm creating a discord bot command that gives a question and two emojis on the question's message for user to react. If you select the wrong emoji, the bot will tell you "Wrong", react again on the message, and wait for the user to react. I want to put this into an infinite loop that only stops when the user chooses the correct emoji. This is what I have worked so far:
message.channel.send(`Question?`).then(sentMessage => {
sentMessage.react('✅');
sentMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`; // bid = bot's id
};
sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
var reaction = collected.first();
if (reaction.emoji.name === '❌') {
var check = true;
while (check) {
console.log('?');
message.channel.send('Wrong').then(sentMessage => {
sentMessage.react('✅');
sentMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`;
};
sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
var reaction = collected.first();
if (reaction.emoji.name == '✅') check = false;
});
});
}
}
});
});
The idea is when the user finally reacts ✅ after first reacting some ❌, check will become false and the loop will stop. However, after first choosing ❌, the while loop is not running any code inside it other than looping console.log('?'). Can someone point out where I did wrong?
In your code, you send Wrong and put the reaction check logic inside then and wrap with while.
However, since Channel.send returns a Promise, it will end almost instantly, continue the loop while doing Channel.send and reaction logic simultaneously.
You can use an async function and call it recursively.
So the code would be this:
message.channel.send(`Question?`).then(sentMessage => {
sentMessage.react('✅');
sentMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`; // bid = bot's id
};
sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
var reaction = collected.first();
if (reaction.emoji.name === '❌') {
async function reactionLoop() {
console.log('?');
let sentMessage = await message.channel.send('Wrong');
await sentMessage.react('✅');
await sentMessage.react('❌');
const filter = (reaction, user) => ['✅', '❌'].includes(reaction.emoji.name) && user.id != `${bid}`;
let collected = await sentMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] })
var reaction = collected.first();
if (reaction.emoji.name == '✅') await reactionLoop();
}
reactionLoop();
}
});
});
I'm trying to display who win the poll but i run into a problem. While I want to get the number of the reactions with
.addField("🔴:", `${results.get("🔴").count}`)
My console says that the count is undefined. I've tried to search it but I didn't find anything and I tried so many ways but nothing.
The code:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require("discord.js")
module.exports = class HelpCommand extends BaseCommand {
constructor() {
super('vote', 'moderation', []);
}
async run(client, message, args) {
const filter = m => m.author.id == message.author.id;
let embed = new Discord.MessageEmbed()
.setFooter(`${message.author.tag} started the poll`)
.setTimestamp();
message.channel.send('what the question is?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.setTitle(msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
message.channel.send('first option?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.addField(`[🔴] the first option:`, msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
message.channel.send('second option?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.addField(`[🔵] the second option`, msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
try {
await message.channel.bulkDelete(7)
.then(message.channel.send(embed).then(sentMessage => sentMessage.react('🔴')).then(reaction => reaction.message.react('🔵')));
} catch (err) {
console.log(err);
}
const filters = (reaction) => reaction.emoji.name === "🔴" || reaction.emoji.name === "🔵";
const results = await message.awaitReactions(filters, { time: 15000 })
let resultsEmbed = new Discord.MessageEmbed()
.setTitle(`the poll result`)
.setDescription(`the result of the poll: ${args.join(" ")}`)
.addField("🔴:", `${results.get("🔴").count}`)
.addField("🔵:", `${results.get("🔵").count //if i dont type here the .count then i've got this embed but after the "🔵": says'undefined' }`)
.setColor("#84daf8")
.setTimestamp()
message.channel.send(resultsEmbed);
}
}
A szavazás eredménye = The poll result in my language. I see this when i dont write the .count there: .addField("🔴:", `${results.get("🔴").count}`)
and i see this when i write .count
The problem was that the bot was trying to retrieve the reactions of a deleted message I believe. In order to fix this, you'll have to put your resultsEmbed code inside of your chained then methods.
Code:
try {
await message.channel.bulkDelete(7)
.then(message.channel.send(embed)
.then(sentMessage => sentMessage.react('🔴'))
.then(reaction => reaction.message.react('🔵'))
.then(reaction => {
const filters = (reaction) => reaction.emoji.name === "🔴" || reaction.emoji.name === "🔵";
reaction.message.awaitReactions(filters, { time: 15000 }).then(collected => {
console.log(collected);
if (collected.get("🔴") !== undefined && collected.get("🔵") !== undefined) {
let optionOne = collected.get("🔴").count;
let optionTwo = collected.get("🔵").count;
let resultsEmbed = new Discord.MessageEmbed()
.setTitle("the poll result")
.setDescription(`the result of the poll: ${args.join(" ")}`)
.addField("🔴:", `${optionOne}`)
.addField("🔵:", `${optionTwo}`)
.setColor('#')
.setTimestamp()
message.channel.send(resultsEmbed);
} else {
//there were no votes for one of the options, thus it will not be able to get property
message.channel.send("There were no votes for one of the options.");
}
})
})
);
} catch (err) {
console.log(err);
}
Currently, I am using Discord.js to make a bot.
client.on('message', (message) => {
if (message.content === '$wa') {
message.channel.send({ embed: exampleEmbed }).then((embedMessage) => {
embedMessage.react('❤️');
embedMessage
.awaitReactions(
(filter = (reaction, user) => {
return reaction.emoji.name === '❤️' && user.id === message.author.id;
}),
{ max: 2, time: 60000, errors: ['time'] }
)
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === '❤️') {
message.channel.send(
':sparkling_heart: **Hanno** and **Roronoa Zoro** are now married! :sparkling_heart:'
);
}
});
});
}
});
If I type $wa the bot shows some embed. But the thing is that it automatically adds a heart to the embed. I want that if I click the heart as well (for a total count of 2 hearts) it executes the if statement at the bottom.
I've tried multiple methods but none worked. This is also my first time with Discord.js
You need to account for the bots own reaction. I recommend redoing your filter implementation to something like this.
The key takeaway is that you have to add !user.bot to the filter so that the bot's own reaction is ignored
const filter = (reaction, user) => {
return reaction.emoji.name === "❤️" && user.id === message.author.id && !user.bot
}
embedMessage.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
Please try this:
client.on('message', message => {
if (message.content === '$wa') {
message.channel.send({ embed: exampleEmbed }).then(embedMessage => {
embedMessage.react('❤️');
embedMessage.awaitReactions(filter = (reaction, user) => {
return reaction.emoji.name === '❤️' && user.id === message.author.id;
},
{ max: 1, time: 60000, errors: ['time'] }).then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '❤️') {
message.channel.send(':sparkling_heart: **Hanno** and **Roronoa Zoro** are now married! :sparkling_heart:');
}
}).catch(() => {
// user didn't react with ❤️ in given time (here: 60 secs)
message.channel.send('no reaction in time');
});
});
}
});
I changed the max value to 1 and also added a catch block to catch a UnhandledPromiseRejectionWarning. If you don't do so in the future, it might exit the program with an error. You can of course execute whatever you like when the user didn't react to the embedMessage in time.
How to fix this ? i want to delete message when user click reaction X
client.on('message', async message => {
if (message.channel.id === emojiChannelID) {
try {
await message.react('✅');
await message.react('✖');
} catch(err) {
console.error(err);
}
}
});```
There's an message.awaitReaction() in discord.js, that will return reactions from users
// Filter for only
const filter = function(reaction, user) {
return reaction.emoji.name === '✅' || reaction.emoji.name === '✖';
}
// {...}
let reactionMessage = await message.react('✅');
// Make sure to set max: 1 so that the promise returns after the first reaction
let reactionCollection = await reactionMessage.awaitReactions(filter, { max: 1});
// reactionCollection is a Collection<string, MessageReaction>
// Use first() to get the first (and only)
let reaction = reactionCollection.first();
Kian here,
This code should work for you,
if you would like I can go through and explain each line :)
Have a good day chief!
async function emojiMessage(message, validReactions) {
for (const reaction of validReactions) await message.react(reaction);
const filter = (reaction, user) => validReactions.includes(reaction.emoji.name) && (!user.bot)
return message
.awaitReactions(filter, {
max: 1,
time: 42000
})
.then(collected => collected.first() && collected.first().emoji.name);
}
async function deleteMessage(message) {
const emoji = await emojiMessage(message, ["✅", "❌"]);
console.log(emoji)
// if the emoji is a tick:
if (emoji === "✅") {
// delete their message
console.log("tick")
if (message.deletable == true) {
console.log("can delete")
console.log("attempting to delete")
message.delete()
}
if (!message.deletable == false) {
"cannot delete"
}
} else if (emoji === "❌") { // if the emoji is a cross
/*
* do something else
*/
return;
}
}
client.on('message', message => {
if (message.channel.id === emojiChannelID) {
// runs the function
deleteMessage(message)
}
/*
* do something else
*/
})
Note:
First upload 🎉
I've tried my best to make the code understandable/work , if there is any issues feel free to comment, I'll fix it :)
Example Usage:
const m = await message.channel.send('hi!');
reactionDelete(m, message, 20000); // assuming 'message' is the actual sent message
async function reactionDelete (botMessage, playerMessage, timeout) {
const filter = (reaction, user) => {
return ['🗑️'].includes(reaction.emoji.name) && user.id === playerMessage.author.id;
};
botMessage.react('🗑️');
botMessage.awaitReactions(filter, { max: 1, time: timeout})
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '🗑️') {
botMessage.delete();
}
})
.catch(collected => {
if (botMessage.deletable) botMessage.reactions.removeAll();
});
};
I am making my first Discord Bot, using Discord.js - I can make it read a command !makeraid and the bot will ask the first question, and store the response into an array.
I want to be able to ask multiple questions like raid name, description, date, and time. I have not yet got this far, after the first question is asked, as a test i want the bot to create the embed message.
However, i cannot make it trigger/fire the next question.
client.on('message', message => {
if (message.content.toLowerCase().startsWith("!makeraid")) {
const filter = m => m.author.id === message.author.id;
var raid = {};
var color = ((1 << 24) * Math.random() | 0).toString(16);
var raidImages = {'DDS':'https://i.imgur.com/izsm8ri.jpg','GR':'https://i.imgur.com/4S9NKtF.jpg','CR':'https://i.imgur.com/EnYiWka.jpg','OR':'https://i.imgur.com/VOYDUlO.jpg'};
message.reply('Raid Name?').then(r => r.delete(10000));
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
raid.title = collected.first().content;
console.log(raid);
collected.first().delete(5000);
})
.catch(() => {
message.channel.send('Raid Cancelled - Too Slow!').then(r => r.delete(5000));
});
while ( Object.keys(raid).length > 0 ) {
message.reply('Do you want to create the raid? Yes or No.').then(r => r.delete(10000));
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
if (collected.first().content.toLowerCase() === "yes") {
collected.first().delete();
var raidEmbed = new Discord.RichEmbed()
.setColor('#'+color)
.setAuthor('Raid Bot', client.user.avatarURL)
.setTitle(':star::star: '+raid.title+' :star::star:')
.setThumbnail(client.user.avatarURL)
.setDescription('Some description here')
.addField('Date', 'Some value here', true)
.addField('Time', 'Some value here', true)
.setTimestamp()
.setFooter('Raid created by: '+ message.member.user.tag, message.member.user.avatarURL);
message.channel.send(raidEmbed).then(async embedMessage => {
await embedMessage.react('✅');
await embedMessage.react('❓');
await embedMessage.react('🇽');
});
} else {
collected.first().delete();
message.channel.send('Raid Cancelled').then(r => r.delete(5000));
}
})
.catch(() => {
message.channel.send('Raid Cancelled - Too Slow! (Make)').then(r => r.delete(5000));
});
}
message.delete();
} else if (message.content.toLowerCase().startsWith("!help")) {
message.reply('You Suck 😃').then(r => r.delete(10000));
message.delete();
}
});
No errors are coming up in the terminal, it just does nothing after the first response has been collected and push into the array.