So I have this inside my main index.js to check for any blacklisted users to prevent them from joining if they tried to join back again.
bot.on("guildMemberAdd", member => {
if(member.user.bot)
if (!db.get("blacklist_users").find({ user_id: member.id }).value()) {
return;
} else {
member.ban();
member.send("**You are blacklisted.**")
}
})
bot.on('message', message => {
let member = message.author;
if(!db.get("blacklist_users").find({ user_id: member.id }).value()) {
return;
}else {
member.ban();
member.send("**You are blacklisted.**")
}
})
Always be sure to check the API documentation for types. In this case, message.author returns a User object, not a GuildMember object. User does not have a ban function because it isn't associated with a guild. If you need the member object you will need to retrieve it from the member property.
let member = message.member;
Just be wary that this may be undefined if the message did not originate in a guild (i.e. Direct Message) or the member has left the guild before it is executed.
So i got it solved now by moving the code to my event instead of leaving it in the main file. And of course i had to define some other stuff in order to read where the blacklisted user is.
if (!db.get("blacklist_users").find({ user_id: member.id }).value()) {
return;
} else {
member.ban()
console.log(`User "${member.user.username}" has joined tried to join "${member.guild.name} and is probably blacklisted` )
}
i hope this will help you guys
Related
Explain
I am developing a user verification bot.
Within the requirements I need to remove the user reactions on a specific message, but removing the reactions discord.js triggers the messageReactionRemove event and causes another function to be executed that sets the roles to a user.
Problem/Error
The problem happens when a user leaves the server, discord.js removes the reactions but in turn triggers another event messageReactionRemove and my bot blows up with an error called "Uknow Member"
Codes
Listener when an user leaves the server:
// All this code works fine :)
client.on("guildMemberRemove", async (member) => {
warn(`El usuario ${member.user.username} abandono el servidor`);
try {
const channel = await client.channels.fetch(CHANNELS.VERIFICATION_CHANNEL);
const message = await channel.messages.fetch(
MESSAGES.BOT_VERIFICATION_MESSAGE_ID
);
message.reactions.cache.map((reaction) => {
// After removing the reaction, discord.js fires the event "messageReactionRemove"
reaction.users.remove(member.user.id);
});
} catch (err) {
console.error(err);
}
});
Listener when an user remove a reaction from a message:
if (!user.bot) {
try {
const channelId = reaction.message.channelId;
const messageId = reaction.message.id;
const emojiName = reaction.emoji.name;
const userExists = await getMember(user.id); // <-- This explodes in an error
if (!userExists) {
warn(`El usuario ${user.username} no existe en el servidor`);
return;
}
if (
channelId === CHANNELS.VERIFICATION_CHANNEL &&
messageId === MESSAGES.BOT_VERIFICATION_MESSAGE_ID &&
emojiName === EMOJIS.VERIFICATION_EMOJI
) {
addTownLoyalRoleToNewUsers(reaction, user);
}
// other messages validations ...
} catch (err) {
error(err.message, err);
}
}
Code for add the verification role:
const addTownLoyalRoleToNewUsers = async (reaction, user) => {
const member = await reaction.message.guild.members.fetch(user.id); // <-- This also blows up in an error
const townRoyalUsersLength = await getUsersLengthByRole(
ROLES.TOW_LOYAL_ROLE_ID
);
if (townRoyalUsersLength <= MAX_LENGTH_TOW_LOYAL_USERS) {
member.roles.add(ROLES.TOW_LOYAL_ROLE_ID);
} else {
member.roles.add(ROLES.VERIFIED_ROLE_ID);
}
const otherRoles = ROLES.AFTER_VERIFICATION();
if (otherRoles.length) member.roles.add(otherRoles);
};
Error images
Error when an user leaves a server
Interestingly when the user leaves, the guildMemberRemove event still owns the nonexistent user
If you want to only remove the member who is leaving, then this line of code should do the trick, add it to your guildMemberRemove event
client.channels.cache.get('ChannelIdWithMessage').messages.fetch('MessageIdToRemoveReactionsFrom').then((message) => {
message.reactions.cache.filter(reaction => reaction.users.remove(member.user.id))
})
There are 2 parts to discord.js you should know, there is the Discord API, which is where those errors come from, and then there are the objects, which make interacting with the Discord API easier.
I'm assuming that your getMember() function tries to fetch the member from the API by ID (guild.members.fetch(id)). Note the user is not "non-existent", it's the GuildMember. The object is simply data from the event, but you can't interact with it in the API. You seem to expect the getMember() function to return a falsy value, like null or undefined, if the member is not found. Instead, it gets a 404 and rejects.
Instead, use a .catch() like this:
const userExists = await getMember(user.id).catch(() => null); // null if rejected
I want to make a discord bot program. when someone new goes to the server they have to type !daftar to be able to enjoy the server. and when they type !daftar message list will appear on #welcome channel. but I get an error that is in the title. here is my code
const { GuildMember } = require("discord.js");
module.exports = {
name: 'daftar',
description: "This is for add roles to a member",
execute(message, args) {
let role = message.guild.roles.cache.find(r => r.name === "Members")
if (message.member.roles.cache.some(r => r.name === "Members")) {
message.channel.send('Kamu sudah menjadi MEMBER Di grup ini');
} else {
message.member.roles.add('817360044622217276');
message.member.roles.remove('817965925122048010');
message.channel.send('Baiklah silahkan menikmati Server');
GuildMember.guild.channels.cache.get('817957997312737290').send(`Selamat Datang <#${GuildMember.user.id}>`)
}
}
}
GuildMember is not exactly defined. Yes, you are destructuring it as the property of discord.js, but it's not exactly defined as who the member actually is. Right now it's just an empty object that belongs to no one, meaning that it also has no properties itself as it does not know what it refers to.
Assuming that you're wanting to give the role to the member who typed this command, you'd have to make the GuildMember object the property of the Message object that is defined as message in your parameters. We can get this object using the member property of message => message.member.
Now, assuming that the channel you're looking to send the message to is found in the same guild as the message object, there is no sense behind using a GuildMember object to find a certain channel, when we can instead use the Message object, as seen below:
Final Code
module.exports = {
name: 'daftar',
description: "This is for add roles to a member",
execute(message, args) {
let role = message.guild.roles.cache.find(r => r.name === "Members")
if (message.member.roles.cache.some(r => r.name === "Members")) {
message.channel.send('Kamu sudah menjadi MEMBER Di grup ini');
} else {
message.member.roles.add('817360044622217276');
message.member.roles.remove('817965925122048010');
message.channel.send('Baiklah silahkan menikmati Server');
message.guild.channels.cache.get('817957997312737290').send(`Selamat Datang <#${GuildMember.user.id}>`)
}
}
}
I have a problem adding a custom role to a user. The command should look like this: ${prefix}addrole #user <role name>. The user should receive a custom role and the bot should send a confirmation message. This is my code:
client.on('message', (message) => {
if (message.content.startsWith(`${prefix}addrole`)) {
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermissions('MANAGE_MEMBERS'))
return message.reply("You don't have acces!");
const rMember =
message.guild.member(message.mentions.user.first()) ||
message.guild.members.get(args[0]);
if (!rMember) return message.reply("I couldn't find that user!");
const role = args.join(' ').slice(22);
if (!role) return message.reply('Please type a role!');
const gRole = message.guild.roles.find(`name`, role);
if (!gRole) return message.reply("I couldn't find that role!");
if (nMember.roles.has(gRole.id));
await nMember.addRole(gRole.id);
try {
nMember.send(`You received ${gRole.name}`);
} catch (e) {
message.channel.send(
`The user <#${rMember.id}>, received the role ${gRole.name}. We tried to dm him but he disabled them.`
);
}
};
module.exports.help = {
name: 'addrole',
};
}
});
The first problem I found comes from these two lines:
if(nMember.roles.has(gRole.id));
await(nMember.addRole(gRole.id));
First of all:
await is not a function, and thus you don't need parentheses. If you do put parentheses, you will get an error. Instead, just use:
await nMember.addRole(gRole.id)
Second of all:
GuildMember.roles.has is deprecated. discord.js v12+ uses Managers, so you will have to add the cache property. Write:
if (nMember.roles.cache.has(gRole.id))
This also applies to a line further up in the code:
let gRole=message.guild.roles.find(`name`, role);
Replace that with
let gRole = message.guild.roles.cache.find(r => r.name = role)
Third of all:
This issue is also seen in the second line of code I quoted:
await nMember.addRole(gRole.id)
addRole() is also deprecated, instead use:
await nMember.roles.cache.add(gRole.id)
Fourth of all, and I barely caught this:
MANAGE_MEMBERS is no longer a permission flag. Instead, use MANAGE_ROLES.
Overall the code could be cleaned up a bit, but I think that's all the errors I found.
I am trying to use the discord API to make a bot that its going to create a role and add a person to it. I'm not sure why my code isn't working.
async function role(message){
try {
let guild = client.guild.get(236824834066219009);
guild.roles.create({
data:{
name:"asd",
color:"grey",
},
reason:"asd",
})
let role = message.guild.roles.find(r => r.name === "asd");
let user = 236824834066219009;
await user.addrole(role).catch(console.error);
} catch (error) {
console.log(error);
}
}
The reason why your code is not working is because since discord.js v12 there have been a lot of changes.
You can't use .find() on roles anymore you have to access their cache first so you need to replace let role = message.guild.roles.find(r => r.name === "asd"); with let role = message.guild.roles.cache.find(r => r.name === "asd");
You also can't add roles using addrole(), you need to use roles.add() so you need to replace user.addrole(role) with user.roles.add(role)
You can also make your code more efficient by not having to find the role, you can just use .then() to add the role to the user, which you can also pass through as a parameter in your function along with the guild, like so:
async function role(message, user, guild){
try {
guild.roles.create({
data:{
name:"asd",
color:"grey",
},
reason:"asd",
}).then((role) => user.roles.add(role)).catch(console.error);
} catch (error) {
console.log(error);
}
}
When a user joins the server, the bot sends a welcome message, i want to take that welcome message's ID and make the bot delete it if the users leaves after he joins. I tried to save the message's id in a variable and make the bot delete the message when the user leaves but without success. I already took a look at the docs, but I really can't understand how to make it.
Define an object to hold the welcome messages by guild and user. You may want to use a JSON file or database (I'd highly recommend the latter) to store them more reliably.
When a user joins a guild...
Send your welcome message.
Pair the the message's ID with the user within the guild inside of the object.
When a member leaves the guild...
Fetch their welcome message.
Delete the message from Discord and the object.
Example setup:
const welcomeMessages = {};
client.on('guildMemberAdd', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.send(`Welcome, ${member}.`);
if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
welcomeMessages[member.guild.id][member.id] = message.id;
} catch(err) {
console.error('Error while sending welcome message...\n', err);
}
});
client.on('guildMemberRemove', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
if (!message) return;
await message.delete();
delete welcomeMessages[member.guild.id][member.id];
} catch(err) {
console.error('Error while deleting existing welcome message...\n', err);
}
});
To do this you would have to store the id of the welcome message and the user that it is tied to (ideally put this in an object). And when the user leaves you would use those values to delete that message.
Example code:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];
client.on('message', (message) => {
if(message.channel.name === 'welcome') {
const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
welcomes.push(welcomeObj);
}
});
client.on('guildMemberRemove', (member) => {
welcomes.forEach(welcome, () => {
if(welcome.user === member.user.username) {
welcomeChannel.fetchMessage(welcome.id).delete();
}
});
});
This only works if the welcome message includes a mention to the user so make sure that's in the welcome message.
Also I can't test this code myself at the moment so let me know if you encounter any problems.