Cannot add a role, Discord.js - node.js

so i'm coding a discord bot, and there's a command, this command know when the user changes is custom status, and if the special status is "hello" the bot will send a message in a specific channel, and add a role to the user. But the code gives my an error
Here's the code :
bot.on('presenceUpdate', (oldMember, newMember) => {
console.log(newMember.activities[0].state)
let guildChannels = newMember.guild.channels;
var Cha = guildChannels.cache.find(channel => channel.name === "general")
if(newMember.activities[0].state === "hello") {
Cha.send('hello !')
.then(msg => {
let GradeUser = bot.users.cache.find(user => user.id == newMember.userID);
let role = msg.guild.roles.cache.find(r => r.id == "742423876004216883");
GradeUser.roles.add('742423876004216883')
})
.catch(console.error)
}
});
And here's the error :
TypeError: Cannot read property 'add' of undefined
at C:\Users\Nathan\Desktop\Dev\Effectivement Bot\index.js:320:29
at processTicksAndRejections (internal/process/task_queues.js:93:5)
I just want to solve the error with the role ( add the role )

You need to use a GuildMember object, not a user object.
From discord.js guide
What is the difference between a User and a GuildMember?
A lot of users get confused as to what the difference between Users and GuildMembers is. The simple answer is that a User represents a global Discord user and a GuildMember represents a Discord user on a specific server. That means only GuildMembers can have permissions, roles, and nicknames, for example, because all of these things are server-bound information that could be different on each server that user is in.
Replace bot.users.cache.find() with msg.guild.members.cache.find()

Related

How edit messages in Discord.js V12 using message ID

There is the way to edit a message on DiscordJS
To do this, we just need to pass it to the function, the client variable.
exports.myNewFunction = async function myNewTestFunction(client)
First, in order to edit a message using the Discord.JS API, we will need to find the server's GuildID.
const guild = client.guilds.cache.get(`Your Guild ID`);
Now, we're going to need to find the channel the message is on. For this, we will use the channel ID
const channel = guild.channels.cache.find(c => c.id === `Your message Channel` && c.type === 'text');
Finally, let's go to the editing part of the message. For this, we will only need to provide the ID of the message that you want to be edited.
channel.messages.fetch(`Your Message ID`).then(message => {
message.edit("New message Text");
}).catch(err => {
console.error(err);
});

Discord.js: Verify channel

I'm trying to make my own bot for my server, for now i'm focusing on the verify. By acting to the check mark emoji it'll add the verified role, and then it should remove only the user reaction, but instead it'll remove every reaction right away
client.on('messageReactionAdd', async (reactionReaction, user) => {
const message = reactionReaction.message;
const verifyChannel = message.guild.channels.cache.find(c => c.name === 'approvazione');
const member = message.guild.members.cache.get(user.id);
if (member.user.bot) return;
const verify = message.guild.roles.cache.get('728000975046180988');
if (reactionReaction.emoji.name === '✅' && message.channel.id === verifyChannel.id) {
member.roles.add(verify).catch(console.error);
await reactionReaction.remove(member).catch(console.error);
}
here is the message sent by the bot with it's own reaction
and here is the same message after i reacted, and both mine and the bot reaction are removed, i just want my reaction to be removed
If you look at the docs it takes no parameter for the user:
https://discord.js.org/#/docs/main/stable/class/MessageReaction?scrollTo=remove
This was changed in v12, the method now is to use .users.remove:
reactionReaction.users.remove(member);

I need to fix the code for communicating people leaving the server and tracking their inviters Node js Discord

I do code for New members on Discord server and it works.But i do some errors in code for leavers.What commands i need to write to do working code.
//this is for new members
client.on('guildMemberAdd', member => {
member.guild.fetchInvites()
.then(invites => {
const ib = inviterses[member.guild.id];
inviterses[member.guild.id] = invites;
const logs = invites.find(i => ib.get(i.code).uses < i.uses);
const joinchannel = member.guild.channels.find(channel => channel.name === "joiners");
joinchannel.send(`${member} **join**. Inviter- **${logs.inviter.tag}** (**${logs.uses}** invites)`)
console.log(`${member} **join**. Inviter- **${logs.inviter.tag}** inviter(**${logs.uses}** invites)`)
});
})
// this code for leavers,it not working
client.on('guildMemberRemove', (member) => {
targetUser = member.id
member.guild.fetchInvites()
.then(invites => {
const userInvites = invites.array().filter(o => o.inviter.id === targetUser.id);
inviterses[userInvites.id].has[targetUser.id]
inviterses.delete(targetUser.id)
const leavchannel = member.guild.channels.find(channel => channel.name === "leavers");
leavchannel.send(`${targetUser.user.username} left;Invited by ${userInvites.inviter.tag}`)
})
})
Discord doesn't provide an efficient way to know who invite a member. The way you use in your case is not simple to understand for beginners.
You fetch all the server invites (with their use count) and store them in a local variable
When a member joins, you check which invite has its use count increased
You update your local variable with new data
It means that if the invitation was created after the fetch in your local variable, you won't be able to know who invite the member. Click here for more information.
To know who invited a member you need to store in a local variable (or in a database, it's better) who invited him in the guildMemberAdd event because you won't be able to know that in the guildMemberRemove event.
So tracking user invites is very complicated and difficult.

Check if the user adding a reaction has a role

I want to check if the user reacting to a message has a role or not, so that if the user dont have a rank the bot will ignore the rest of the command, but I dont know how.
example: if a user with the admin rank reacted with :eggsa: emoji, the bot would continue with the command, but if i only had member rank the bot would ignore me.
client.on('messageReactionAdd', reaction => {
const eggsa = client.emojis.find(emoji => emoji.name === "eggsa");
if (reaction.emoji.name === 'eggsa') {
const message = reaction.message;
const kanal = reaction.message.guild.channels.find('name', 'sitater');
var embed = new Discord.RichEmbed()
.setAuthor(reaction.message.content)
.setTimestamp()
.setFooter(reaction.message.author.username, reaction.message.author.avatarURL)
kanal.send({embed});
}
});
the code works in this stage, only everyone can use it
I would be really grateful if someone could help me >:)
If you look at the messageReactionAdd docs you can see that along with the reaction, you can also get the user which added the reaction. So instead of
client.on('messageReactionAdd', reaction => {
You'd have
client.on('messageReactionAdd', (reaction, user) => {
So then you have the user and which is of type User. Because the user isn't of type GuildMember you first need to fetch the correct Guild member before you can check his/her role.
The easiest way to do this is by getting the Message to which the reaction was added with const msg = reaction.message;. Then you can get the guild from the message with const guild = msg.guild;. Now you can access the guild members with const guildMembers = guild.members;. Lastly you'd need to find the correct member with const guildMember = guildMembers.get(user.id);.
Now that you have your Guild Member you can access his/her Roles and thus check whether he/she has or does not have a certain role

discord.js how to return all members from a current role

i am currently working on some updates for my discord bot, I am using discord.js
and trying to get all the usersnames from a current role via dm,
For example, if 3 users have the role Admin,
then the 3 usernames will be returned via message,
so far i have this
bot.on('message', msg => {
if(msg.channel instanceof Discord.DMChannel)
{
if(msg.content == prefix + "des"){
let RoleName = "Admin";
let guildid = "idwashere";
let memberWithRole =
bot.guilds.get(guildid).roles.get("name",
RoleName).members;
console.log(memberWithRole);
msg.reply("Feature coming soon");
}
}
});
i get a error
let memberWithRole =
bot.guilds.get(guildid).roles.get("name",
RoleName).members;
^
TypeError: Cannot read property 'members' of
undefined
i feel i'm close but yet not sure what im doing wrong :)
Managed to fix it
i changed memberswithrole to
let memberWithRole = bot.guilds.get(guildid).roles.find("name", RoleName).members.map(m=>m.user.username);
this then returns the username
If anyone has any better way or imrpovents please let me know.

Resources