Bot reacting to emojis - javascript

So, I got my code and it works just as I want it to. the message pops up changes everything, it's perfect.
Now I want to add so the bot knows when I react to its message and then does something else. What I mean is: bot sends a message with reacts, and whenever some user clicks the reaction something happens, but I have no idea how to do that.
I've tried many things like if (reaction.emoji.name === ':bomb:'), but multiple errors popped out and I didn't know how to fix that. Here's the code:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
var lastbuffer;
lastbuffer = 0;
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if(message.content.startsWith(`${prefix}start`)){
message.delete()
setInterval(function(){
lastbuffer++;
const Buffer = new Discord.MessageEmbed()
.setColor('#8300FF')
.setTitle("**It's time to check buffers!**")
.setDescription("**It's been **" + "`" + lastbuffer + " Hour" + "`" + "** since last buffercheck, <#&675688526460878848>**." + " **Check now!**")
.setThumbnail('https://art.pixilart.com/88534e2f28b65a4.png')
.setFooter('WEEEEEWOOOOO')
.setTimestamp();
client.channels.cache.get("700296799482675230").send(Buffer).then(msg => {
msg.react('✅');
msg.react('💣');
msg.delete({timeout: 4000})
});
}, 5000)
}
});
client.login(token);

You are going to have to use a ReactionCollector using the createReactionCollector() method.
You can follow this guide to under ReactionCollectors better

You need to use a reaction collector.
client.channels.cache.get("700296799482675230").send(Buffer).then(async msg => {
// I'm using await here so the emojis react in the right order
await msg.react('✅');
await msg.react('💣');
msg.awaitReactions(
// Discord.js v12:
/* ({emoji}, user) => ['✅', '💣'].includes(emoji.name) && user.id === message.author.id,
{max: 1, time: 4000, errors: ['time']} */
// Discord.js v13:
{
// only collect the emojis from the message author
filter: ({emoji}, user) => ['✅', '💣'].includes(emoji.name) && user.id === message.author.id,
// stop collecting when 1 reaction has been collected or throw an error after 4 seconds
max: 1,
time: 4000,
errors: ['time']
}
)
.then(collected => {
const reaction = collected.first()
// do something
})
.catch(() => {
// I'm assuming you want to delete the message if the user didn't react in time
msg.delete()
})
What this code does:
Sends the embed (Buffer) to the channel with the id 700296799482675230
Reacts with the ✅ and then the 💣 emojis on the message with the embed
Waits for a ✅ or 💣 reaction from the author of the original message
If the user reacts within 4 seconds, runs the // do something part
If the user does not react within 4 seconds, deletes the message with the embed

Related

How can i get my discord.js v14 bot to stop saying "The application did not respond" if the slash command works?

i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.
Use interaction.reply instead of interaction.channel.send to reply.

How to make a discord bot do something after I react to an emoji in an image sent by itself

I'm making my first discord bot and I'm trying to make it send a message after I react to one of its emojis, problem is, when I click the thumbs up emoji, the bot simply does not send the message, it's been a few hours now and I can't find the problem, I'm sorry if this has been solved somewhere else, I couldn't find anything that works.
if (command === "ping") {
const attachment = new MessageAttachment('https://cdn.mcr.ea.com/3/images/ac394369-2801-4e09-87eb-82ca54e26254/1588018258-0x0-0-0.jpg');
const sentMessage = await message.channel.send({files: [attachment] })
sentMessage.react('👍');
//sentMessage.react('👎');
const filter = (reaction, user) => {
return reaction.emoji.name === '👍' && user.id === message.author.id;
};
const collector = sentMessage.createReactionCollector(filter, { time: 15000 });
collector.on('collect', (reaction, user) => {
message.channel.send(`Collected ${reaction.emoji.name} from ${user.tag}`);
});
collector.on('end', collected => {
message.channel.send(`Collected ${collected.size} items`);
console.log(`Collected ${collected.size} items`);
});
EDIT
I found that I was missing the "GUILD_MESSAGE_REACTIONS" intent, now i have these 3 "GUILDS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", still not working sadly!
Here's the full code:
https://pastebin.com/Q0eZ6VSz
Hi, this code is working except a small thing...
sentMessage.createReactionCollector(filter, { time: 15000 });
change this to:
sentMessage.createReactionCollector({filter, time: 15000 });
also I suggest you to add max: 1 option too.
so final code:
...
sentMessage.createReactionCollector({filter, max: 1, time: 15000 });
in this situation only gets first react by you.

DiscordJS reactionCollector does not work for other users when they react

My goal is to create a verification system and I want other users (ie. admins) to react to a message from the bot.
The bot sends a message embed to a certain channel and reacts to it with ✅ and ❌. Now all users in this channel should be able to react to this message.
But only the user who requested the verification can react to it (but they shouldn't be able to do this later on) and other users cannot react to it. Nothing happens and no errors. The reaction count just goes up for other users in the channel till the user who requested the verification can react, and then it works and the code continues.
adminChannel.messages.fetch({ limit: 1 }).then(async messages => {
const lastMessage = messages.first();
await lastMessage.react('✅');
await lastMessage.react('❌');
const filter = (reaction, user) => {
return ['✅', '❌'].includes(reaction.emoji.name) && !user.bot
}
const collector = lastMessage.createReactionCollector(filter, { max: 1 });
collector.on('collect', async (reaction, user) => {
if (reaction.emoji.name === '✅') {
//do something
} else {
//do something
}
The problem is the ReactionCollectorOptions parameter in lastMessage.createReactionCollector(filter, { max: 1 }) because max: 1 will make the bot stop awaiting reactions after the first reaction was added. You can just use lastMessage.createReactionCollector(filter) if you don't need this option.
If you still have doubts you can check here the documentation for ReactionCollectorOptions and here the documentation for createReactionCollector method.

Discord.JS How to wait for member reaction

I am making bot to manage my multiple Discord guilds. And I'd like to make confirmation system, like:
User does X thing,
Bot sends message in sufficient channel,
Bot waits for user to react with :thumbdsup: or :thumbsdown: up to 60 seconds
If thumbs up, do A, else - do B. If time is up, do C action
How can I build system like that, due to I have no idea.
Adding and Setting Up the Event Listener
First we start by defining discord.js & adding an event listener:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
});
Then you would need to tell the bot what it does after that:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
//what you want the bot to do after the message you are looking for has been sent
}
});
Now, if you want the bot to add the reaction to the message you will do the following:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
await message.react('👍'); //reacting to the message with a thumbs up emoji
await message.react('👎'); //reacting to the message with a thumbs down emoji
}
});
If you wanted the bot to reply to the message use:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
message.channel.send('The bots message here') //what you want the bot to reply with
}
});
Awaiting Reactions
Here it all depends on if you want to await reactions on the bot's message or the user's message.
If you would like to await reactions from the bot's message use:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
message = await message.channel.send('The bots message here') //waiting for the message to be sent
const filter = (reaction, user) => { //filtering the reactions from the user
return (
['👎', '👍'].includes(reaction.emoji.name) && user.id === message.author.id
);
}
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) //awaiting the reactions - remember the time is in milliseconds
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') { //if the reaction was a thumbs up
//A action
reaction.users.remove(message.author.id) //If you wanted to remove the reaction
} else { //if the reaction was a thumbs down
//B action
reaction.users.remove(message.author.id) //If you wanted to remove the reaction
}
}).catch((collected) => { //when time is up
//C action
});
}
});
If you wanted to await message from the user's message you would do the same thing except change:
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
message.channel.send('The bots message here') //sending the message but not awaiting reactions from it

How to get the last message of a specific channel discordjs

I'm trying to get the last message of a specific channel but I've couldn't do that, I want that if i write a command in another channel (Channel 1) that command gives me the last message of another channel (channel 2).
My code is:
client.on('message', (message)=>{
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')){
message.channel.fetchMessages({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
console.log(lastMessage.content);
})
.catch(console.error);
}
}
});
I cleaned up you code a bit, and added some comments explaining what is happening.
If you have more questions, i would recommend visiting the official Discord.js Discord server.
https://discord.gg/bRCvFy9
client.on('message', message => {
// Check if the message was sent in the channel with the specified id.
// NOTE, this defines the message variable that is going to be used later.
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')) {
// Becuase the message varibable still refers to the command message,
// this method will fetch the last message sent in the same channel as the command message.
message.channel.fetchMessages({ limit: 1 }).then(messages => {
const lastMessage = messages.first()
console.log(lastMessage.content)
}).catch(err => {
console.error(err)
})
}
}
})
If you want to get a message from another channel, you can do something like this.
And use the command start #channel
client.on('message', message => {
// Check if the message was sent in the channel with the specified id.
if(message.channel.id === '613553889433747477'){
if(message.content.startsWith('start')) {
// Get the channel to fetch the message from.
const channelToCheck = message.mentions.channels.first()
// Fetch the last message from the mentioned channel.
channelToCheck.fetchMessages({ limit: 1 }).then(messages => {
const lastMessage = messages.first()
console.log(lastMessage.content)
}).catch(err => {
console.error(err)
})
}
}
})
More about mentioning channels in messages can be found here.
https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=mentions

Categories

Resources