I'm trying to have a bot react when users click the emojis on the bot's embeds.
I'm receiving in the console:
UnhandledPromiseRejectionWarning: TypeError: chestEmbed.awaitReactions
is not a function
The code:
module.exports = {
name: 'enterhouse',
aliases: 'eh',
permissions: ["ADMINISTRATOR", "MANAGE_MESSAGES", "CONNECT"],
description: "Pick a number",
async execute(client, message, args, Discord){
const chestEmbed = new MessageEmbed()
.setColor('#FFA500')
.setImage('https://imageURL.jpg');
message.channel.send(chestEmbed).then(chestEmbed => {chestEmbed.react('1️⃣').then(() => chestEmbed.react('2️⃣').then(() => chestEmbed.react('3️⃣')))}
)
.catch(() => console.error('One of the emojis failed to react.'));
const filter = (reaction, user) => {
return (['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === message.author.id);
};
chestEmbed.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '1️⃣') {
chestEmbed.delete();
message.reply('you reacted with 1');
} else if (reaction.emoji.name === '2️⃣') {
message.reply('you reacted with 2');
} else {
message.reply('you reacted with 3');
}
})
.catch(collected => {
message.reply('Time is up, you did not react.');
});
}
}
It worked fine when it was message.awaitReactions instead.
Any help is really appreciated!
You are awaiting messages from the embed it's self not the message the embed is in.
Simple fix:
...
chestEmbed = await message.channel.send(chestEmbed)
...
Full Code:
module.exports = {
name: 'enterhouse',
aliases: 'eh',
permissions: ["ADMINISTRATOR", "MANAGE_MESSAGES", "CONNECT"],
description: "Pick a number",
async execute(client, message, args, Discord) {
const chestEmbed = new MessageEmbed()
.setColor('#FFA500')
.setImage('https://imageURL.jpg');
chestEmbed = await message.channel.send(chestEmbed)
chestEmbed.react('1️⃣').then(() => chestEmbed.react('2️⃣')).then(() => chestEmbed.react('3️⃣'))
const filter = (reaction, user) => {
return (['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === message.author.id);
};
chestEmbed.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '1️⃣') {
chestEmbed.delete();
message.reply('you reacted with 1');
} else if (reaction.emoji.name === '2️⃣') {
message.reply('you reacted with 2');
} else {
message.reply('you reacted with 3');
}
})
.catch(collected => {
message.reply('Time is up, you did not react.');
});
}
}
Related
I wanna send the suggestion to a channel with two reaction then if the admin reacted ✅ send it to another channel and if ❌ delete it.
I tried this but first it can't send embed it says Cannot read properties of undefined (reading 'discord') and I tried without embed and I used reactions but doesn't work
Code:
module.exports = {
name: "suggest",
category: "Suggestion",
description: "suggest something",
usage: "suggest [text]",
owner: false,
execute(message, args, client) {
message.reply({ content: "..." }).then(async(msg) => {
const sug = args[0];
const suggestion = args.join(" ");
if (!sug) {
message.delete();
msg.edit({
content: `[ You did not provide a suggestion ]`,
})
} else {
const acceptch = message.guild.channels.cache.get('980126282719313970');
if (err) {
message.delete();
msg.edit({
content: `[ ${err} ]`,
})
} else {
const embed = new client.discord.MessageEmbed()
.setColor('0b9494')
.setAuthor(message.author.tag, message.author.displayAvatarURL())
.setDescription(suggestion)
acceptch.send(embed)
.then(msg => {
msg.react('✅').then(() => msg.react('❌'));
msg.awaitReactions((reaction, user) => user.id == '746917945065865376' && (reaction.emoji.name == '✅' || reaction.emoji.name == '❌'), { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '❌') {
return message.author.send('**no**')
}
if (reaction.emoji.name === '✅') {
message.channel.send(`suggestion: ${suggestion}`)
}
});
}).catch(console.error);
}
}
})
}
}
If you check the discord.js documentation for "Client" class, there is no such thing as client.discord.
Which is why this line const embed = new client.discord.MessageEmbed() from your code throws error, because your are trying to access property "MessageEmbed" of object that is undefined.
You can add const { MessageEmbed } = require('discord.js') at the beginning of that file and then just use const embed = new MessageEmbed().
in discord js v13 we can't use acceptch.send(embed) anymore as they said in here we have to send embeds like this acceptch.send({ embeds: [embed] });
it worked on my last bot but now the permission overwrites wont work on the new bot i looked at documentation on discord.js was just wandering if someone could help me out as im at a dead end
code:
module.exports = {
name: 'ticket',
description: "creates ticket",
async execute(message, args, Discord){
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`);
channel.setParent('967965866035642408');
channel.permissionOverwrites.edit(message.guild.id, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false,
});
channel.permissionOverwrites.edit(message.author, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
const reactionMessage = await channel.send('Thank you for contacting support!');
try{
await reactionMessage.react("🔒");
await reactionMessage.react("⛔");
}catch(err){
channel.send('Error sending emojis!');
throw err;
}
const collector = reactionMessage.createReactionCollector(
(reaction, user) => message.guild.members.cache.find((member) => member.id === user.id).hasPermission("ADMINISTRATOR"),
{dispose: true }
);
collector.on("collect", (reaction, user) => {
switch (reaction.emoji.name) {
case "🔒":
channel.permissionOverwrites.edit(message.author, { SEND_MESSAGES: false });
break;
case "⛔":
channel.send('deleting this channel in 5 seconds');
setTimeout(() => channel.delete(), 5000);
break;
}
});
message.channel.send(`we will be right with you! ${channel}`).then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
}).catch((err) => {
throw err;
});
}
}
So the first part of this would be the command, and I seperated the command from the reaction, just in case the bot reboots or there was ever an error with the collector, this code will survive a reboot. I also tested this on my bot and it works without issue.
Command.js file
module.exports = {
name: 'ticket',
description: "creates ticket",
async execute(message, args, Discord) {
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`, {
parent: '967965866035642408',
permissionOverwrites: [{
id: message.guild.id,
deny: [
'VIEW_CHANNEL',
],
}, {
id: message.author,
allow: [
'VIEW_CHANNEL',
'SEND_MESSAGES',
],
}],
});
const reactionMessage = await channel.send(`Thank you for contacting support! ${message.author}`);
// message.author is important for later so make sure it stays in the message somehow.
try {
await reactionMessage.react("🔒");
await reactionMessage.react("⛔");
} catch (err) {
channel.send('Error sending emojis!');
throw err;
}
message.channel.send(`we will be right with you! ${channel}`).then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
}).catch((err) => {
throw err;
});
},
};
This section would go into your main bot.js file to catch the reaction add and it will auto remove reactions that are placed by members who are not admins
client.on('messageReactionAdd', async (messageReaction, user) => {
if (user.bot) return;
const message = await messageReaction.message.fetch(true);
const channel = message.channel;
const guild = client.guilds.cache.get(message.guildId);
const member = guild.members.cache.get(user.id);
if (channel.parent.id === '967965866035642408') {
const regex = /\d+/g;
const authorID = message.content.match(regex);
const originalAuthor = client.users.cache.get(authorID[0]);
if (!member.permissions.has("ADMINISTRATOR")) {
message.reactions.cache.find(reaction => reaction.emoji.name == messageReaction.emoji.name).users.remove(member.user);
return;
} else {
switch (messageReaction.emoji.name) {
case "🔒":
channel.permissionOverwrites.edit(originalAuthor, { SEND_MESSAGES: false });
break;
case "⛔":
channel.send('deleting this channel in 5 seconds');
setTimeout(() => channel.delete(), 5000);
break;
}
}
} else {
return;
}
});
I'm trying to write a discord bot, right now it's a command to get married.
Everything works as it should, except for one thing. In the awaitReactions function, I have a time of 10 seconds, and after this time I get this error:
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
[UnhandledPromiseRejection: This error originated either by throwing inside of a
n async function without a catch block, or by rejecting a promise which was not
handled with .catch(). The promise rejected with the reason "#".] {
code: 'ERR_UNHANDLED_REJECTION'
}
I can't understand why this is happening, I have .catch() at the end of the function and in theory everything should work as it should.
Why doesn't .catch() work in my case? What could be the problem?
const { Command } = require('discord.js-commando');
const db = require("quick.db");
module.exports = class MarryCommand extends Command {
constructor(client) {
super(client, {
name: 'marry',
memberName: 'marry',
group: 'test',
description: 'Marry the mentioned user',
guildOnly: true,
args: [
{
key: 'userToMarry',
prompt: 'Please select the member you wish to marry.',
type: 'member'
}
]
});
}
run(message, { userToMarry }) {
const exists = db.get(`${message.author.id}.user`);
const married = db.get(`${userToMarry.id}.user`);
if (!userToMarry) {
return message.channel.send('Please try again with a valid user.')}
if (exists == message.author.id) {
return message.channel.send('You are already married!')}
if (married == userToMarry.id) {
return message.channel.send('This user is already married!')}
if (userToMarry.id == message.author.id) {
return message.channel.send('You cannot marry yourself!');
}
if (exists != message.author.id && married != userToMarry.id) {
message.channel.send(`**Important announcement!**
${message.author} makes a marriage proposal ${userToMarry}
Are you ready to get married?`).then(message => {
message.react('👍').then(() => message.react('👎'));
message.awaitReactions((reaction, user) => user.id == userToMarry.id && (reaction.emoji.name == '👍' || reaction.emoji.name == '👎'),
{ max: 1, time: 10000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👎') {
return message.channel.send('I think **no**...')}
if (reaction.emoji.name === '👍') {
db.set(message.author.id, { user: message.author.id, partner: userToMarry.id });
db.set(userToMarry.id, { user: userToMarry.id, partner: message.author.id });
message.channel.send(`${message.author} and ${userToMarry} now married!!`)
.catch(() => {
message.reply('No reaction after 10 seconds, operation canceled');
});
}
});
});
}}};
The mistake here is that every then chain should have a catch block. You have missed two catch blocks. The solution is to either add the catch blocks to all the then chains or you can connect all then chains into one big chain and finally use one catch block
Method 1
const { Command } = require("discord.js-commando");
const db = require("quick.db");
module.exports = class MarryCommand extends Command {
constructor(client) {
super(client, {
name: "marry",
memberName: "marry",
group: "test",
description: "Marry the mentioned user",
guildOnly: true,
args: [
{
key: "userToMarry",
prompt: "Please select the member you wish to marry.",
type: "member",
},
],
});
}
run(message, { userToMarry }) {
const exists = db.get(`${message.author.id}.user`);
const married = db.get(`${userToMarry.id}.user`);
if (!userToMarry) {
return message.channel.send("Please try again with a valid user.");
}
if (exists == message.author.id) {
return message.channel.send("You are already married!");
}
if (married == userToMarry.id) {
return message.channel.send("This user is already married!");
}
if (userToMarry.id == message.author.id) {
return message.channel.send("You cannot marry yourself!");
}
if (exists != message.author.id && married != userToMarry.id) {
message.channel
.send(
`**Important announcement!**
${message.author} makes a marriage proposal ${userToMarry}
Are you ready to get married?`
)
.then((message) => {
message.react("👍")
.then(() => message.react("👎"))
.catch(()=>{
//code
});
message.awaitReactions((reaction, user) =>
user.id == userToMarry.id && (reaction.emoji.name == "👍" || reaction.emoji.name == "👎"),
{ max: 1, time: 10000, errors: ["time"] }
).then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === "👎") {
return message.channel.send("I think **no**...");
}
if (reaction.emoji.name === "👍") {
db.set(message.author.id, {
user: message.author.id,
partner: userToMarry.id,
});
db.set(userToMarry.id, {
user: userToMarry.id,
partner: message.author.id,
});
message.channel
.send(`${message.author} and ${userToMarry} now married!!`)
.catch(() => {
message.reply(
"No reaction after 10 seconds, operation canceled"
);
});
}
}).catch(()=>{
//code
});
}).catch(()=>{
//code
});
}
}
};
Method 2
const { Command } = require("discord.js-commando");
const db = require("quick.db");
module.exports = class MarryCommand extends Command {
constructor(client) {
super(client, {
name: "marry",
memberName: "marry",
group: "test",
description: "Marry the mentioned user",
guildOnly: true,
args: [
{
key: "userToMarry",
prompt: "Please select the member you wish to marry.",
type: "member",
},
],
});
}
run(message, { userToMarry }) {
const exists = db.get(`${message.author.id}.user`);
const married = db.get(`${userToMarry.id}.user`);
if (!userToMarry) {
return message.channel.send("Please try again with a valid user.");
}
if (exists == message.author.id) {
return message.channel.send("You are already married!");
}
if (married == userToMarry.id) {
return message.channel.send("This user is already married!");
}
if (userToMarry.id == message.author.id) {
return message.channel.send("You cannot marry yourself!");
}
if (exists != message.author.id && married != userToMarry.id) {
message.channel
.send(
`**Important announcement!**
${message.author} makes a marriage proposal ${userToMarry}
Are you ready to get married?`
)
.then((message) => {
message.react("👍")
.then(() => message.react("👎"))
.catch(()=>{
//code
});
return message.awaitReactions((reaction, user) =>
user.id == userToMarry.id && (reaction.emoji.name == "👍" || reaction.emoji.name == "👎"),
{ max: 1, time: 10000, errors: ["time"] }
)
})
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === "👎") {
return message.channel.send("I think **no**...");
}
if (reaction.emoji.name === "👍") {
db.set(message.author.id, {
user: message.author.id,
partner: userToMarry.id,
});
db.set(userToMarry.id, {
user: userToMarry.id,
partner: message.author.id,
});
return message.channel
.send(`${message.author} and ${userToMarry} now married!!`)
}
})
.catch(()=>{
message.reply(
"No reaction after 10 seconds, operation canceled"
);
});
}
}
};
So I want to add an emoji reaction to the bot's message. But idk what code to make it.
I only know the code to react to the command message.
else if(command === "guessage"){
message.channel.send({ embed: {
color: 16758465,
title: "Are you...",
description: Math.floor((Math.random() * 20) + 11) + " " + "years old?"
}
})
message.react('👍').then(() => message.react('👎'));
const filter = (reaction, user) => {
return ['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
message.reply('you reacted with a thumbs up.');
} else {
message.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
message.reply('you reacted with neither a thumbs up, nor a thumbs down.');
});
}
Handle the promise of each Message#reply()
Example Using Callbacks:
message.reply('you reacted with a thumbs up.').then(botsMessage => botsMessage.react('EMOJI-HERE'));
Example using Async/Await
(Recommend for maintaining reaction order):
// Inside an async function
const botsMessage = await message.reply('you reacted with a thumbs up.');
await botMessage.react('EMOJI-1');
await botMessage.react('EMOJI-2');
await botMessage.react('EMOJI-3');
Understanding Promises - Discord.JS
You need to await the sending of the message and use it's message object.
For example:
else if (command === "guessage") {
(async () => {
let bmsg = await message.channel.send({
embed: {
color: 16758465,
title: "Are you...",
description: Math.floor((Math.random() * 20) + 11) + " " + "years old?"
}
})
await bmsg.react('👍');
await bmsg.react('👎');
const filter = (reaction, user) => {
return ['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id;
};
bmsg.awaitReactions(filter, {
max: 1,
time: 60000,
errors: ['time']
})
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
message.reply('you reacted with a thumbs up.');
} else {
message.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
message.reply('you reacted with neither a thumbs up, nor a thumbs down.');
});
})();
}
I'm using an async IIFE to allow await to be used. There are other places where await should be used, but I'll leave that up to you.
someone can help?
5️⃣ = 5️⃣
var embed1 = new Discord.RichEmbed()
.setTitle("hjgsadgv")
message.channel.send(embed9)
.then(function (message) {
message.react("5️⃣")
.then(() => message.react("4️⃣"))
.then(() => message.react("3️⃣"))
.then(() => message.react("2️⃣"))
.then(() => message.react("1️⃣"))
const filter = (reaction, user) => {
return ['5️⃣', '4️⃣', '3️⃣', '2️⃣', '1️⃣'].includes(reaction.emoji.name) && user.id === message.author.id;
}
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '5️⃣') {
message.reply('123');
}
else {
message.reply('321');
}
var embed2 = new Discord.RichEmbed()
.setTitle("uysygadk")
message.channel.send(embed10)
})
})
Bot responds to its own reactions
You can ignore bots by changing your filter to this:
const filter = (reaction, user) => {
return ['5️⃣', '4️⃣', '3️⃣', '2️⃣', '1️⃣'].includes(reaction.emoji.name) && user.id === message.author.id && !user.bot;
}
It basically checks the bot property of user and if it's true then the filter blocks it.