Check if the user adding a reaction has a role - node.js

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

Related

DISCORD.JS How to get the name of the person who invited the new member?

I'm currently trying to add the name of the user who invited the new member to my welcome message!
could you help me? I'll leave my code below and thank you if you can help me with this!
client.on("guildMemberAdd", async (member) => {
let guild = await client.guilds.cache.get("SERVER ID"); // SERVER ID
let channel = await client.channels.cache.get("CHANNEL ID"); // CHANNEL ID
let emoji = await member.guild.emojis.cache.find(emoji => emoji.name === "eba"); // NOME DO EMOJI
if (guild != member.guild) {
return console.log("Sem boas-vindas pra você! Sai daqui saco pela."); // MENSAGEM EXIBIDA NO CONSOLE
} else {
let embed = await new Discord.MessageEmbed()
.setColor("#fcfcfc")
.setAuthor(member.user.tag, member.user.displayAvatarURL())
.setTitle(`:boom: Boas-vindas :boom:`)
.setImage("https://media.tenor.com/images/c001d9d78724152f00eca4d8ed2e2b9c/tenor.gif")
.setDescription(`**Olá ${member.user}!**\nBem-vindo(a) ao servidor **${guild.name}**!\nVocê é o membro **#${member.guild.memberCount}\n**Compartilhe nosso servidor! :heart:`)
.setFooter("Servidor Espalha Lixo") // Set footer
.setTimestamp();
channel.send(embed);
}
});
There's no official way to find out who invited someone through Discord's API. What people do is store a list of existing invites, and when someone joins, compare the stored list to the current list to find out which invite had its number of uses increased.
It isn't perfect, and can possibly break in large servers with a lot of people joining.
There's a great guide about this topic on the An Idiot's Guide website: https://anidiots.guide/coding-guides/tracking-used-invites
This is working; check out this code
client.on('guildMemberAdd', member => { //guildMemberAdd event
member.guild.fetchInvites().then(guildInvites => {
// This is the *existing* invites for the guild.
const ei = invites[member.guild.id];
// Update the cached invites for the guild.
invites[member.guild.id] = guildInvites;
// Look through the invites, find the one for which the uses went up.
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
// This is just to simplify the message being sent below (inviter doesn't have a tag property)
const inviter = client.users.get(invite.inviter.id);
channel.send(`${member.user.tag} joined using invite code - ${invite.code} from ${inviter.tag}. Invite was used ${invite.uses} times since its creation.`);
})
});
You can find more at discordjs-bot-guide from github.
The answer - inviter.tag from code

Cannot add a role, Discord.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()

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.

Discord.js Backdoor command

I've seen my bot join many more servers, but it seems like some are abusing it.
I want the bot to make a one time use invite to a server that I am not on, but my bot is. Once I am on the server I can just remove it. It would be like so:
^backdoor "guild id". I am very new to coding. Thanks!
There are 2 possible ways of doing this, but both are reliant on the permissions that the bot has in that guild.
guildid has to be replaced with an ID or an variable equivilant to the ID
Way 1:
let guild = client.guilds.get(guildid):
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
guild.fetchInvites()
.then(invites => message.channel.send('Found Invites:\n' + invites.map(invite => invite.code).join('\n')))
.catch(console.error);
Way 2:
let guild = client.guilds.get(guildid):
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
let invitechannels = guild.channels.filter(c=> c.permissionsFor(guild.me).has('CREATE_INSTANT_INVITE'))
if(!invitechannels) return message.channel.send('No Channels found with permissions to create Invite in!')
invitechannels.random().createInvite()
.then(invite=> message.channel.send('Found Invite:\n' + invite.code))
There would also be the way of filtering the channels for SEND_MESSAGE and you could send a message to the server.
Instead of entering the guild and then removing it, it would be simpler to just make the bot leave the guild, using Guild.leave()
// ASSUMPTIONS:
// guild_id is the argument from the command
// message is the message that triggered the command
// place this inside your command check
let guild = client.guilds.get(guild_id);
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
guild.owner.send("The bot has been removed from your guild by the owner.").then(() => {
guild.leave();
});

Resources