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
Related
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.
This is the code, I want it to write user's name and then auction word (p.s I am new to this)
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageEmbed } = require('discord.js');
const channel = client.channels.cache.get('889459156782833714');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
var message = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle() // want user's name + "Auction"
.addField('Golden Poliwag', 'Very Pog', true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction')
if (msg.content === "d.test") {
msg.reply(message)
}
})
You can access the user's username by using msg.author.tag. So. the way to use the user's tag in an embed would be:
const { MessageEmbed, Client } = require("discord.js");
const client = new Client();
const channel = client.channels.cache.get("889459156782833714");
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
var message = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`${msg.author.tag} Auction`)
.addField("Golden Poliwag", "Very Pog", true)
.setImage("https://graphics.tppcrpg.net/xy/golden/060M.gif")
.setFooter("Poliwag Auction");
if (msg.content === "d.test") {
msg.reply(message);
}
});
I suggest you to read the discord.js documentation, almost all you need to interact with Discord API is from there.
You can't control the bot if you don't login to it. Get the bot's token from Developer Portal and login to your bot by adding client.login('<Your token goes here>') in your project.
You can't get the channel if it's not cached in the client. You need to fetch it by using fetch() method from client's channels manager:
const channel = await client.channels.fetch('Channel ID goes here');
P/s: await is only available in async function
message event is deprecated if you are using discord.js v13. Please use messageCreate event instead.
You are able to access user who sent the message through msg object: msg.author. If you want their tag, you can get the tag property from user: msg.author.tag, or username: msg.author.username or even user ID: msg.author.id. For more information about discord message class read here.
The reply options for message is not a message. You are trying to reply the message of the author with another message which is wrong. Please replace the reply options with an object that includes embeds:
msg.reply({
embeds: [
// Your array of embeds goes here
]
});
From all of that, we now have the final code:
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
client.on("ready", () => {console.log(`Logged in as ${client.user.tag}!`)});
client.on("messageCreate", async (msg) => {
const channel = await client.channels.fetch('889459156782833714');
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle(`${msg.author.tag} Auction`)
.addField('Golden Poliwag','Very Pog',true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction');
if (msg.content === "d.test") {
msg.reply({
embeds: [ embed ],
});
}
});
client.login('Your bot token goes here');
Now your bot can reply to command user with an rich embed.
I'm trying to code a discord bot that send a message to all users in a list. I am having problems using the client.users.fetch(); method on discord.js. The error message says something about DiscordAPIError: Unknown user, Unhandled promise rejection, and DiscordAPIError: Cannot send messages to this user, even though I am in the same guild as the bot.
Here is the code I have so far:
const Discord = require('discord.js');
const client = new Discord.Client();
const ownerId = 'YOUR-ID'
const users = ['YOUR-ID']
client.on('ready', () => {
console.log('Bot is online!');
});
client.on('message', async message => {
if (message.content.includes("test")) {
if (message.author.id == ownerId) {
message.channel.send("ok!")
var userID
var user
for (let i = 0; i < users.length; i++) {
userID = users[i];
user = client.users.fetch(userID.toString(), true);
client.user.send('works');
}
}
}
});
client.login('YOUR-TOKEN');
There are several issues in your code.
Firstly, client.users.fetch(...) is an asynchronous function therefore it requires an await.
Secondly, client.user.send(...) will actually send a message to the bot which is impossible. So you'll want to replace it with either message.channel.send(...) which will send the message in the same channel the message was received in or message.author.send(...) which will send a message to the author of the message.
Below is an example fix:
const Discord = require('discord.js'); // Define Discord
const client = new Discord.Client(); // Define client
const ownerId = 'your-discord-user-id';
const users = [] // Array of user ID's
client.on('ready', () => { // Ready event listener
console.log('Bot is online!'); // Log that the bot is online
});
client.on('message', async message => { // Message event listener
if (message.content.includes("test")) { // If the message includes "test"
if (message.author.id == ownerId) { // If the author of the message is the bot owner
message.channel.send("ok!"); // Send a message
// Define variables
let userID;
let user;
for (let i = 0; i < users.length; i++) { // Loop through the users array
userID = users[i]; // Get the user ID from the array
user = await client.users.fetch(userID.toString()); // Await for the user to be fetched
message.channel.send('works'); // Send a message to tell the message author the command worked
}
}
}
});
client.login('YOUR-TOKEN'); // Login your bot
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
I have a function that send messages, but it doesn't work because it's not inside
client.on('message', msg => {
How can I do?
You can send messages from outside client.on('message'..., All you need is channel ID and then you can simply do:
const myChannel = client.channels.get('CHANNEL_ID');
myChannel.send(`your message here!`);
EDIT
You can use this inside a function by passing it as a parameter:
const myChannel = client.channels.get('CHANNEL_ID');
function myFunc(channel) {
channel.send('MESSAGE');
}
Now you can call your function using myChannel:
myFunc(myChannel);
client.on("message") is an event that will trigger each time a new message is sent in a channel the bot can see. (DMs included.)
To send a message to a channel id, first you have to find the channel using the client.channels collection.
const Discord = require("discord.js");
const Client = new Discord.Client(); // Creating a new Discord Client.
Client.on("ready", () => {
const Channel = Client.channels.get("your channel id"); // Searching the channel in the collection channels.
if (!Channel) {
return console.error("No channel found!"); // If the channels does not exist or the bot cannot see it, it will return an error.
} else {
return Channel.send("Your message to send here!"); // We found the channel. Sending a message to it.
};
}); // Making sure the client is ready before sending anything.
Client.login("your bot token here"); // Logging into Discord with the bot's token.