Why messageReactionAdd do nothing discord.js - javascript

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()

Related

My discord bot won't respond to my command

So I'm pretty new to javascript, trying to get a bot to work. I get no errors, but when I try to use the bot in the server it is added in, it won't respond. I tried putting a console input in between the client.on and the if statement to see if I got input into my console, but no luck.
This tells me the issue is there, but after hours of editing and searching the web I didn't find anything. Thanks for the help!
const Discord = require("discord.js")
const fetch = require("node-fetch")
const client = new Discord.Client({ intents: [8] })
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", Message => {
if (msg.content === "Test") msg.reply("Success")
})
client.login(process.env['TOKEN'])
See this Image
Where did you define "msg". You have taken the argument as Message and then you are trying to use "msg" to get the content of it. You can replace "Message" to be msg then It may work
#2)
If this isn't working, you can check if you have other instances of the BOT running. This happened to me also!
The reason your bot is not responding to your messages is first of all, likely caused by incorrect intents provided.
The intents [8] resolves to a single intent (GUILD_EMOJIS_AND_STICKERS), which is why the message event is not executing. Do not confuse intents with permissions. You need to subscribe to the right intents:
const client = new Discord.Client({
intents: [
"GUILD_MESSAGES"
]
});
Secondly, your message listener takes a Message parameter, but the body of it is using a msg variable. Ensure you use the correct variables in your code:
// "message" is deprecated, "messageCreate" is preferred
client.on("messageCreate", (msg) => {
if (msg.content === "Test") {
msg.reply("Success");
}
})
Already found the issue, Discord.js v13 does NOT support content anymore. This was supported up to V12.

Event messageCreate not firing/emitting when I send a DM to my bot (discord.js v13)

I made this code for logging the DMs that are sent to my bot:
client.on('messageCreate', async message => {
if (message.author.bot) return;
const attachment = message.attachments.first()
if (message.channel.type === 'DM') {
console.log(message.content)
const dmLogEmbed = new MessageEmbed()
.setColor("RANDOM")
.setTitle(`${message.author.tag} dmed the bot and said: `)
.setDescription(message.content)
.setFooter(`User's id: ${message.author.id}`)
if (message.attachments.size !== 0) {
dmLogEmbed.setImage(attachment.url)
}
client.channels.fetch("852220016249798756").then((channel) => {
channel.send({ embeds: [dmLogEmbed] })
})
}
});
But when updating to discord.js v13 it didn't work anymore, for what I understood the only change is that the 'dm' channel type isn't 'dm' anymore but 'DM', so I changed it in my code, but it is still not working and I don't really know why.
Make sure you have DIRECT_MESSAGES in your client's intents.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"] });
There is a breaking change in the Discord API v8. For reference see here.
On Discord API v8 and later, DM Channels do not emit the CHANNEL_CREATE event, which means discord.js is unable to cache them automatically. In order for your bot to receive DMs, the CHANNEL partial must be enabled.
So we need to enable the partial CHANNEL as well. Keep in mind that when dealing with partial data, you often want to fetch the data, because it is not complete. However this doesn't seem to be your case, if you are using the messageCreate event. The message received is not partial nor message.channel. To check if something is partial, you can use the .partial property. For example Message.partial or Channel.partial.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"], partials: ["CHANNEL"] });
Now it should work as good old discord.js v12.

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

Discord.JS Reactions

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("⛔");
});

How to fix "Problem with Reactions (Restart bot)"

I've a problem with a reaction reply System.
I want that when a user adds a reaction, that replies to a message, except that when the bot reboots it is no longer detected by the bot.
Do you know how to fix this problem?
Here is my current code :
bot.on("messageReactionAdd", function(messageReaction, user){
if(messageReaction.message.content === "Message"){
if(user.bot){return}
messageReaction.message.reply("It works.")
}
})
bot.on("message", function(message){
if(message.content.startsWith(prefix + "test")){
message.delete()
message.member.createDM().then(m => m.send("Message").then(m => m.react("✅")))
}
}
on the latest version of discord.js, you can use the Partial Events to accomplish this.
According to the doc (https://discord.js.org/#/docs/main/master/topics/partials):
Partials allow you to receive events that contain uncached instances, providing structures that contain very minimal data. For example, if you were to receive a messageDelete event with an uncached message, normally Discord.js would discard the event. With partials, you're able to receive the event, with a Message object that contains just an ID.
What you need to do is
const Discord = require('discord.js');
// add "partials" in the bot options to enable partial events
const client = new Discord.Client({"partials": ['CHANNEL', 'MESSAGE']});
[...]
client.on("messageReactionAdd", async function(messageReaction, user){
// fetch message data if we got a partial event
if (messageReaction.message.partial) await messageReaction.message.fetch();
if(messageReaction.message.content === "Message"){
if(user.bot){return}
messageReaction.message.reply("It works.")
}
})
Doing this, you must be careful on your client.on("message", ...) calls, to avoid accessing data or method that are not available.
there is a boolean message.partial that you can use to discard partial message when you don't need them.

Categories