Why is my reactioncollector working only for me - node.js

I am currently trying to create a bot that adds a verification system that adds a specific role to the user upon reacting. This works, but when another user tries it does not work. Even removing the reaction upon reacting only works for me. Bear in mind, I have only just got back into the discord bot game so I am a little rusty. Below is the snippet of code, it just does not work for other users, but does for me. This is written in NodeJS - discord.js
if (message.content.startsWith(config.prefix + 'verify')) {
message.delete()
const embed = new MessageEmbed()
.setColor(config.embedcolor)
.setTitle('✅ Verification Board ✅')
.setFooter('Copyright © 2020 History GFX', 'https://i.imgur.com/1HkdOVY.png')
.setDescription('')
message.channel.send(embed).then(async message => {
await message.react('✅');
const collector = message.createReactionCollector((reaction, user) => user !== client.user)
collector.on("collect", (reactionCollect, user) => {
if(reactionCollect.emoji.name === "✅"){
let verify = message.guild.roles.cache.find(r => r.name === "🍃 Client");
message.guild.member(user).roles.add(verify);
reactionCollect.users.remove(user);
}
});
})
};
Thank you for your time!

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

Send DM when a user joins a VC using Discord.JS

Stack Overflow (I apologize if this question has already been asked, I don't believe it has, but in advance, just in case):
I'm making a discord bot using Discord.JS and Node.JS. I want to make a bot to detect when a user joins a VC, and then sends said user a DM. I have the detection code figured out:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login("token");
bot.once('ready', () =>{
console.log(`Bot ready, logged in as ${bot.user.tag}!`);
})
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.channelID;
let oldUserChannel = oldMember.channelID;
if(newUserChannel === "channel id")
{
// User Joins a voice channel
console.log("User joined vc with id "+newUserChannel)
}
else{
// User leaves a voice channel
console.log("Left vc");
}
});
But I'm having trouble sending the user (who i assume is represented by newMember) a DM. Can someone kindly provide some assistance? Thanks!
You can use the .member property of the VoiceState instance you get to get the user who has joined the voice channel. Then simply call the .send() method on the voice channel user to send them a DM. Take a look at the example code below:
bot.on('voiceStateUpdate', (oldState, newState) => {
const newChannelID = newState.channelID;
if (newChannelID === "channel id") {
console.log("User has joined voice channel with id " + newChannelID);
const member = newState.member;
member.send('Hi there! Welcome to the voice channel!');
} else {
console.log("User left or didn't join the channel matching the given ID");
}
});
Give it a try and see how it goes

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

Is there a way to get invites from ALL the guilds my bot is in?

Any ideas on how to get invites from a discord you aren't in but my bot is in?
I guess you want to get invited to every guild your bot is in
client.guilds.cache.forEach(guild => {
guild.channels.cache.filter(x => x.type != "category").random().createInvite()
.then(inv => console.log(`${guild.name} | ${inv.url}`));
});
Rez's answer is a common one but not a secure one, the random channel you get could be a channel you don't have permission to create an invite in.
This approach is safer, (might be a bit slower since async/await):
(This needs to be in an async function)
const invites = [];
//cant use async inside of forEach
//https://www.coreycleary.me/why-does-async-await-in-a-foreach-not-actually-await/
for (const [guildID, guild] of client.guilds.cache) {
//if no invite was able to be created or fetched default to string
let invite = "No invite";
//fetch already made invites first
const fetch = await guild.fetchInvites().catch(() => undefined);
//if fetch worked and there is atleast one invite
if (fetch && fetch.size) {
invite = fetch.first().url;
invites.push({ name: guild.name, invite });
continue;
}
for (const [channelID, channel] of guild.channels.cache) {
//only execute if we don't already have invite and if the channel is not a category
if (!invite && channel.createInvite) {
const attempt = await channel.createInvite().catch(() => undefined);
if (attempt) {
invite = attempt.url;
}
}
}
invites.push({ name: guild.name, invite });
}
console.log(invites)

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.

Resources