Discord.JS Reactions - javascript

I'm working on a ticket bot and I would like it so that you react to a message to create a ticket. I can make the message but when I use bot.on('messageReactionAdd') if my bot restarts it won't detect that a reaction has been added unless you make a new message and react to a message that has been created since the bot has been online. This is a problem for me and I know it's fixable. I've tried google searches and couldn't fix the problem. Can anyone here help me?

Starting from Discord.js v12, you can enable partials on the bot that allow it to send events for unfetched messages, with the tradeoff that you have to fetch the message yourself at the start of the handler:
const Discord = require('discord.js');
// Make sure you instantiate the client with the correct settings
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.on('messageReactionAdd', async (reaction, user) => {
// When we receive a reaction we check if the reaction is partial or not
if (reaction.partial) {
// If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message: ', error);
// Return as `reaction.message.author` may be undefined/null
return;
}
}
// Now the message has been cached and is fully available
console.log(`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`);
// The reaction is now also fully available and the properties will be reflected accurately:
console.log(`${reaction.count} user(s) have given the same reaction to this message!`);
});

You can use this however you want, but here is an example for you:
message.channel.send("React test!").then(messageReaction => {
messageReaction.react("✅");
messageReaction.react("⛔");
});

Related

How do I fix DiscordAPIError: Unknown Message?

I made a bot that deletes text messages in an image channel, but when I use it it's logs this error.
client.on("message", async message => {
if (message.author.bot) return;
const users = ['853248522563485717'];
if (message.channel.id === '841260660960395287') {
if (users.includes(message.author.id)) return;
if (message.attachments.size !== 0) return;
message.member.send("You can't send text in 'images' channel")
await message.delete();
} else return;
});
(this is different from the other questions with the same topic)
how do I fix it?
The most likely problem is that you are running multiple instances of the Discord bot. Check if you have multiple command lines open, if so, check if they are running the bot. Apart from that, if users spam, Discord API tends to get confused about which messages to delete, making it try to delete the same message more than 1 time. You can try adding an if statement checking if the message is undefined.
client.on("message", async (message) => {
if (!message) return; // ADDED THIS LINE OF CODE
if (message.author.bot) return;
const users = ["853248522563485717"];
if (message.channel.id === "841260660960395287") {
if (users.includes(message.author.id)) return;
if (message.attachments.size !== 0) return;
message.member.send("You can't send text in 'images' channel");
await message.delete();
} else {
return;
}
});
From your error above, you are seemingly using a message event listener for every command or function you want your bot to perform. The maximum for this is 11 (of the same type). This is not the correct way to do this.
What is an event listener?
//the 'client.on' function is called every time a 'message' is sent
client.on("message", async (message) => {
//do code
});
How to fix this:
Instead of using 1 event listener per command, use 1 for the whole client. You could solve this a multitude of ways, with command handlers or such, however I will keep it simple.
This is the basic setup you should see in your index.js or main.js file:
// require the discord.js module
const Discord = require('discord.js');
// create a new Discord client
const client = new Discord.Client();
// on message, run this
client.on('message', (message) => {
if (!message) return;
console.log(`message sent in ${message.channel.name}. message content: ${message.content}`);
//this event will fire every time a message is sent, for example.
});
// login to Discord with your app's token
client.login('your-token-goes-here');
So what do you do if you want to do multiple functions with your bot? (for example deleting text in an images only channel and logging messages to console)
Command handling. It is the only way. I linked an official Discord.js guide above, read through it and see what you can do. I would highly recommend trying this with an entirely different bot and clean index file, as it would be easier than trying to fit in code you dont understand between your already problematic code.

How do i make reactions working after restart?

So i am trying to make an ticket bot, using discord.js . By clicking on an reaction, users will be added to an ticket channel, where they can get help. The ticket system itself works perfectly fine, exactly like i want it to work. But the problem is, after i restart the bot, nothing happens anymore when you click on the reaction. Here is the relevant code:
let helpdeskmessageEmbed = await message.channel.send(helpdeskticketEmbed)
helpdeskmessageEmbed.react("1️⃣")
helpdeskmessageEmbed.react("2️⃣")
helpdeskmessageEmbed.react("3️⃣")
client.on('messageReactionAdd', async (reaction, user) => {
const categoryID = "820920950114615318"
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.partial) await reaction.fetch()
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel ) {
if(reaction.emoji.name === "1️⃣") {
reaction.users.remove(user)
message.guild.channels.create(`report-${user.username}`).then(
The rest of the code isn't relevant to my question. Could anyone tell me how to fix this.
Note: I am using an command handler, if that is relevant
I've had this exact issue some time ago. Long story short, you need to use partials.
Be aware, that:
"Partials do not have all the information necessary to make them fully functional discord.js structures, so it would not be a good idea to enable the functionality by default. Users should know how to handle them before opting into this feature."
I see that you have tried to use them, but you need to add the ability to handle partials in your code. Change const client = new Discord.Client(); into:
const client = new Discord.Client({
partials: [`MESSAGE`, `CHANNEL`, `REACTION`], //unsure if message and channel are needed, feel free to test it out
});
This basically allows handling all messages, even those posted before your bot started. Without the change above, your code will not detect partials.
client.on("messageReactionAdd", async (reaction, user) => {
let msg = reaction.message;
if (msg.partial) {
await msg.fetch().catch(() => {});
}
//your code goes here
});
Answering your comment:
I have read your replit code and it looks fine, I can only suggest to change this:
const Discord = require ('discord.js');
const client = new Discord.Client({ partials: [`MESSAGE`, `CHANNEL`, `REACTION` ]});
into this:
const { Discord } = require('discord.js');
const client = new Discord({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });

Reaction event discord.js

I'm trying to make a starboard code with my bot, and everything else is working good. But I'm trying to make it to where the bot ignores reactions from the author of the actual message.
This is my current code:
client.on('messageReactionAdd', (reaction_orig, message, user) => {
if (message.author.id === reaction_orig.users.id) return
manageBoard(reaction_orig)
})
It returns the following error:
if (message.author.id === reaction_orig.users.id) return;
^
TypeError: Cannot read property 'id' of undefined
The problem is that messageReactionAdd takes two parameters; the message reaction as the first one, and the user that applied the emoji as the second one. When you write reaction_orig, message, user, reaction_orig is the reaction (which is correct), but message is the user who reacted as it's the second parameter. The user variable will be undefined.
Another issue is that reaction_orig.users returns a ReactionUserManager that doesn't have an id property. Luckily, the user is already passed down to your callback so you can use its ID.
Also, reaction_orig has a message property, the original message that this reaction refers to so you can get its authors' ID from it.
You can change your code to this to work:
client.on('messageReactionAdd', (reaction_orig, user) => {
if (reaction_orig.message.author.id === user.id) {
// the reaction is coming from the same user who posted the message
return;
}
manageBoard(reaction_orig);
});
However, the code above only works on cached messages, ones posted after the bot is connected. Reacting on older messages won't fire the messageReactionAdd event. If you also want to listen to reactions on old messages you need to enable partial structures for MESSAGE, CHANNEL and REACTION when instantiating your client, like this:
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
You can check if the message is cached by e.g. checking if its author property is not null. If it's null, you can fetch the message. Now, you have both the message author and the user who reacted, so you can compare their IDs:
// make sure it's an async function
client.on('messageReactionAdd', async (reaction_orig, user) => {
// fetch the message if it's not cached
const message = !reaction_orig.message.author
? await reaction_orig.message.fetch()
: reaction_orig.message;
if (message.author.id === user.id) {
// the reaction is coming from the same user who posted the message
return;
}
// the reaction is coming from a different user
manageBoard(reaction_orig);
});
Try doing this :
client.on('messageReactionAdd', (reaction, user) => {
if (!reaction.message.author.id === user.id){
//Do whatever you like with it
console.log(reaction.name)
}
});
Note: The message must be cached. For that you'll need to do this
Client.channels.cache.get("ChannelID").messages.fetch("MessageID");
I'm guessing you're using discord.js v12

How to make Discord.js Bot responds with local picture when we mentions(#) the bot?

I am a newbie to JavaScript. I want to make my discord server's bot responding with local picture on my computer while anybody mentions(#) it. I have tried multiple methods,
this is the one I follow the documentation:
client.on('message', (message) => {
if (message.mentions.has("My Bot's ID")) {
const attachment = new MessageAttachment('./images/image1.png');
return message.channel.send(`Hi ${message.author},`, attachment);
}
});
This one failed, as well as a few older version methods I tried. Some of them not even operate, so I deleted them.
Also, I can't find any other materials besides the documentation for the version(12.3.1).
MessageMentions is an object. You are looking for the MessageMentions.users Collection.
client.on('message', (message) => {
if (message.mentions.users.has("My Bot's ID")) {
// message.mentions.users
const attachment = new MessageAttachment('./images/image1.png');
return message.channel.send(`Hi ${message.author},`, attachment);
}
});

Why messageReactionAdd do nothing discord.js

I'am trying to code a discord bot with node.js, but i have a problem with messageReactionAdd I don't now why the bot does nothing when i react with an emoji.
My code :
bot.on('messageReactionRemove', (reaction, user) => {
console.log("that work 1");
if(reaction.emoji.name === "white_check_mark") {
console.log("that work 2");
}})
Events messageReactionAdd and messageReactionRemove working only for cached messages. You need add raw event to your code for trigger any message.
https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/raw-events.md
Update 2022. You may need to add intents for GUILD_MESSAGES and GUILD_MESSAGE_REACTIONS with cache messages to make it work.
Reference: https://discordjs.guide/popular-topics/reactions.html#listening-for-reactions-on-old-messages
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
The message must be cached before it will work. Any messages that come in while your bot is open will automatically get cached, but if it's for a specific older message, you can use:
client.channels.get(CHANNELID).fetchMessage(MESSAGEID);
to cache it. After doing this (each time your script is run) you will receive reaction events for that message.
You are doing reaction remove and you need to use Unicode emojis - you can find these online and copy them
You should listen to the messageReactionAdd event.
Keep also in mind that ReactionEmoji.name is the Unicode for that emoji: you can get the Unicode symbol by writing a backslash before the emoji, like \:joy:. The Unicode for :white_check_mark: is ✅.
This should be your code:
bot.on('messageReactionAdd', (reaction, user) => {
console.log("first check");
if (reaction.emoji.name === "✅") {
console.log("second check");
}
});
This will work on every cached message, if you want it to work only on a specific message, try using Message.awaitReactions() or Message.createReactionCollector()

Categories