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'] });
Related
Dear all hope you are well,
I have created a discord bot with which I register some commands as well as interact with the user's messages, The first bot is working fine but when I tried to make a second one (with the same configurations as the first one) it is returning the error below:
{
rawError: {
message: 'You are not authorized to perform this action on this application',
code: 20012
}
}
I made a link with application.commands permission as well as even administrative privileges but it is still not working.
Below you can find my code:
const path = require("path");
require("dotenv").config({ path: path.resolve(__dirname, ".env") });
// Discord Bot Configuration/Setup
const Discord, { ButtonStyle } = require("discord.js");
const commands = [];
const command = require("./commands/ping");
commands.push(command.data.toJSON());
const rest = new Discord.REST({ version: "10" }).setToken(
process.env.DISCORD_BOT_TOKEN
);
(async () => {
try {
const data = await rest.put(
Discord.Routes.applicationCommands("{APPLICATION_ID}"),
{ body: commands }
);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
const client = new Discord.Client({
partials: [Discord.Partials.Channel, Discord.Partials.Message],
intents: [
Discord.GatewayIntentBits.DirectMessages,
Discord.GatewayIntentBits.DirectMessageTyping,
Discord.GatewayIntentBits.Guilds,
Discord.GatewayIntentBits.GuildMessages,
Discord.GatewayIntentBits.MessageContent,
Discord.GatewayIntentBits.GuildMembers,
],
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("interactionCreate", async (interaction) => {
// my interaction logics. This part is not relevant to the issue
});
client.on("messageCreate", async (message) => {
// my interaction logics. This part is not relevant to the issue
});
try {
client.login(process.env.DISCORD_BOT_TOKEN);
} catch (err) {
console.log(err);
}
The same code is working with my former bot which makes me more puzzled
Update Notes
The code has been updated and I tried to clarify the problem a bit better, if it is still unclear, please comment on it.
While I was writing this bug I figured the problem out, the primary issue was that I used my old application id instead of the new one:
const data = await rest.put(
Discord.Routes.applicationCommands("{APPLICATION_ID}"), // <==== Causing issue
{ body: commands }
);
So I extracted it to an environment variable and then used the the right value like below:
const data = await rest.put(
Discord.Routes.applicationCommands(process.env.APPLICATION_ID),
{ body: commands }
);
while I was using the token of the new one therefore it was giving unauthorized as it was trying to add slashing commands to the already active bot. the interactions were also returning undefined as there were no interactions existing due to the same issue. You can find the correct application id on the General Information tab of your application on discord developer portal
I hope these insights become useful to another person who is also struggling with the new updates of discord.js and that they can save some time :)
Update Notes
I have updated the answer and added some codes to it. If the answer for any reason is still unclear, please let me know in the comments
Sorry if this is poorly formatted, I've never written a question on here before.
First of all, this is my first time writing anything in JavaScript, so this might be some dumb mistake I'm making that's causing my problem.
What I want to do is send a message when a member joins the server, and send a different message when a member leaves. When someone joins the server, the join message is sent and everything works perfectly fine, but when a member leaves, absolutely nothing happens. I put in some console.logs in the joinMessage and leaveMessage functions, and I get an output for joinMessage but nothing for remove. I have enabled Presence Intent and Server Members Intent on the Discord developer portal.
The join and leave message functions are down at the bottom, but I went ahead and added the entire thing so people could help me better. The bot token and channel IDs have been removed, and they are correct in my version of the code.
console.log('Starting');
const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const commandHandler = require("./commands");
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
client.login('token');
var server = client.guilds.cache.get('server');
client.on('ready', ready);
function ready()
{
console.log('Authenticated');
server = client.guilds.cache.get('server');
}
client.on('messageCreate', receivedMessage);
function receivedMessage(msg)
{
commandHandler(msg);
}
client.on('guildMemberAdd', joinMessage);
function joinMessage(member)
{
let channelWelcome = server.channels.cache.get('welcome');
let channelIntro = server.channels.cache.get('intro');
channelWelcome.send(`Welcome to the server, ${member}! Head over to ${channelIntro} and introduce yourself!`);
}
client.on('guildMemberRemove', leaveMessage);
function leaveMessage(member)
{
let channelWelcome = server.channels.cache.get('welcome');
channelWelcome.send(`${member} has left the server.`);
}
I've been trying to figure this out for about an hour, so I'd really appreciate it if someone could help me solve this. Thanks!
You need to include following intent: GUILD_PRESENCES
So your code needs to look like this:
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
Now your bot will detect if a member leaves the guild.
Try calling the function directly in the event parameters. There might be some sort of confliction when extracting the function
client.on("guildMemberAdd", (member) => {
let channelWelcome = server.channels.cache.get('welcome');
let channelIntro = server.channels.cache.get('intro');
channelWelcome.send(`Welcome to the server, ${member}! Head over to ${channelIntro} and introduce yourself!`);
}
client.on("guildMemberRemove", (member) => {
let channelWelcome = server.channels.cache.get('welcome');
channelWelcome.send(`${member} has left the server.`);
}
Also make sure you have set the right intents (if you are running V13), and gave the bot the correct privileged intents in the developer portal
This question/answer is rather old, but I found that the selected answer here is not fully correct, at least in the current version.
You do not in fact need the Presences Intent to receive guildMemberRemove event. The event is actually not firing in cases when the member data is not cached and will therefore not emit the event.
In order to resolve this, you will need to enable Partials on the client, specifically Partials.GuildMember. This will enable the event to emit on un-cached data.
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.
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
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("⛔");
});