messagereactionadd dont get triggered - javascript

I have a problem with the messageReactionAdd event, it only works after a message is sent inside the discord.
I also tried to put a console.log at the beginning of the event but not even that is triggered.
This is my code:
module.exports = async (client, reaction, user) => {
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(reaction.message.channel.id === '837981337658589204') {
reaction.users.remove(user);
if(reaction.emoji.name === '🐬') {
//code...
}
}
partials:
const client = new discord.Client({ partials: ['MESSAGE', 'REACTION']});
i have tried all the methods found on this site but it still doesn't work.
Edit: The solution to all of this was to activate Privileged Gateway Intents on the bot page, like that. Thanks to #Toasty

I think you don't need to check if the message is partial, but if the reactionis partial. Try this:
try {
if(reaction.partial) await reaction.fetch();
if(user.partial) await user.fetch();
} catch(err) {
console.log('Error: ' + err);
}
In the official guide it is checked if the message is partial, but this example is not about the messageReactionAdd event
Edit / Update:
After looking through the guide again, I remembered one thing:
Try enabling Privileged Intents in the Discord Developer Portal under "Privileged Gateway Intents" in the "Bot" section.
If you don't know what I mean, look at this screenshot. Just enable these and it may work now.

Related

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'] });

Trying to send message to specific channel, but can't define my client

I have a command that clears a set amount of messages that works fine right now, but I'm trying to have the bot send a message to a log channel that tells the mods and admin, how many messages were deleted and who deleted them.
This is all the code right now from the clear file:
module.exports = {
name: 'clear',
description: "clears messages",
async execute(message, args){
if(message.member.roles.cache.has('802911784892760074')){//If mod
if(!args[0]) return message.reply('Enter amount');
if(isNaN(args[0])) return message.reply('Enter amount');
if(args[0] > 100) return message.reply('To high');
if(args[0] < 1) return message.reply('To low');
await message.channel.messages.fetch({limit: args[0]}).then(messages =>{
message.channel.bulkDelete(messages);
client.channels.cache.get('799292569825443860').send(`${message.author} has cleared ${args} messages!`)
});
}
}
This is the line of code that does not seem to be working:
client.channels.cache.get('799292569825443860').send(`${message.author} has cleared ${args} messages!`)
The command prompt says that the client is not defined, but I have the clientdefined in the main js file.
const client = new Discord.Client();
I'm still pretty new to this, and I may just be missing something very basic. (and I'm sorry if this question comes off as stupid to those who understand) any help would be awesome, as I seem to be at a roadblock here.
That client won't just magically appear in your command's file. You need to pass the client as an argument:
async execute(message, args, client){
// ...
And in main.js:
commands.get('clear').execute(message, args, client)
You need to pass your client object to the function, so for example you could do this:
client.commands.get('clear').execute(message, args, client); (or however you execute commands), and then have your function definition like this: async execute(message, args, client){

Discord.js; why does this not add the role?

I'm quite new to Stack Overflow, so excuse me if I do something wrong.
I've been working on Discord bots lately, and for my server I want to make a verification bot. I've got a large piece of the code all done and dusted, but now the important part doesn't work, and I don't know why.
My code:
const Discord = require("discord.js");
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION"]});
const prefix = "v!";
client.on("ready", async () => {
console.log(`Logged in as ${client.user.tag}`);
client.user.setActivity("v!verify | Verify in #πŸ”β”ƒverify-here", {type: "LISTENING"});
});
client.on("message", async(msg) => {
const args = msg.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if(command === 'svm') { // svm = send verification message
if (msg.member.id !== '434239200607600651') return;
const sEmbed = new Discord.MessageEmbed()
.setTitle("Welcome to **aSpiv's Network**!")
.setDescription("aSpiv's Network is a place to hang out, talk and have fun with friends, family and strangers. Our goal is to make this community as friendly and welcoming as possible. Please, remember the human.")
.addField("πŸŽ— Community Guidelines", "TL;DR Use common sense. If you think you'll get a warning for it, don't do it!\n\nTreat everyone with respect. This is the #1 rule of this server. Absolutely no harassment, witch hunting, sexism, racism, or hate speech will be tolerated.\n\nNo spam or self-promotion (server invites, advertisements, etc) without permission from a staff member. This includes DMing fellow members.\n\nNo NSFW or obscene content. This includes text, images, or links featuring nudity, sex, hard violence, or other graphically disturbing content. (Except for the places where it's allowed; see at own risk!)\n\nTalk English. We want to make sure everyone can participate in all conversations, so no one feels left out.\n\nDon't earrape in the voice chats. It's annoying for people who actually want to talk.\n\nNo voice changers. If you don't want people to hear your voice, then don't talk at all.\n\nIf you see something against the rules or something that makes you feel unsafe, let staff know. We want this server to be a welcoming place!")
.addField("πŸ” Getting Verified", "To agree to the rules and receive permission to view all of our channels and send messages, go to <#792391986799837224> and send \`v!verify\`. You are responsible for reading the contents of this channel before agreeing. By being in this server, you agree to all our rules. These rules are subject to change.\n\naSpiv's Network or aSpiv Staff can not and will not be held responsible for any damages or losses that result from the use of our server. We will help you out the best we can, but we are only humans, too.")
.setColor(Math.floor(Math.random()*16777215))
msg.channel.send(sEmbed)
msg.delete();
}
if(command === 'verify') {
let sEmbed = new Discord.MessageEmbed()
.setTitle("Get Verified")
.setDescription("Click on the emoji below to get verified! Make sure you've read the embed in <#791281485276905492>!")
.setColor(Math.floor(Math.random()*16777215))
let m = await msg.channel.send(sEmbed)
m.react('βœ…')
}
return;
});
client.on("messageReactionAdd", async(reaction, user) => {
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.client) return;
if(!reaction.message.guild) return;
if(reaction.emoji.name === 'βœ…') {
await reaction.message.guild.members.cache.get(user.id).roles.add(r => r.id === "792395200676495371")
}
})
client.login("n0t.4-r3al_t0k3n")
Does anyone see the mistake here? It should send a message, react to that message with βœ… (That part works), but when I react with the message too, it should give me a role, but it doesn't.
Thanks in advance for your help!
The Problem
The issue is in your messageReactionAdd event handler, which I assume you must already know given the only part of your code that isn't working is the code's response to your reaction. In that part of your code, you are doing if (user.client) return;. This line is incorrect, and will always return (because user.client is always true).
I'm guessing you want to return if the user that reacted is a bot. But user.client doesn't return whether or not the user is a bot; it returns the Client that created the user variable. Essentially, it returns your client variable. And since the User object stored in the user variable is always created by your client, that if statement will always return and prevent your actual role-adding code from occurring (just like what if (true) return; would do).
The Solution
Here's how to fix it, such that it actually checks if the user is a bot or not instead of trying to check if the client exists or not:
client.on("messageReactionAdd", async(reaction, user) => {
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.emoji.name === 'βœ…') {
await reaction.message.guild.members.cache.get(user.id).roles.add(r => r.id === "792395200676495371")
}
})
Simply changing user.client to user.bot will solve your issue, or will at the very least allow your role-adding code to actually run and allow you to see if there are any additional errors.
Relevant Resources
https://discord.js.org/#/docs/main/stable/class/User?scrollTo=bot
https://discord.js.org/#/docs/main/stable/class/User?scrollTo=client

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("β›”");
});

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