Discord.js how to add roles - discord.js

Now I believe this is a bit of an older version of discord.js but I'm not sure. I'm attempting to add a "Muted" role when you say a certain word, which in this case is "Heck". In the console I'm getting and error saying "TypeError: Cannot read property 'add' of undefined" and I'm not sure what to do here. Here is my code:
client.on('message', (message) => {
if(message.content.includes('Heck')) {
message.reply('Not allowed');
let role = message.guild.roles.cache.find(role => role.name === "Muted");
console.log('works')
let member = message.mentions.members.first();
console.log('works')
member.roles.add(role)
console.log('works')
}
});

Bot can't find Muted role in guild or there is no member mention to add role
client.on('message', (message) => {
if(message.content.includes('Heck')) {
message.reply('Not allowed');
let role = message.guild.roles.cache.find(role => role.name === "Muted");
if (!role) return console.log("no role found");
console.log('works')
let member = message.mentions.members.first();
if (!member) return console.log("no member mentioned");
console.log('works')
member.roles.add(role)
console.log('works')
}
});
This will log no role found if Muted role not found in guild and if role exists & no member mention then it will log no member mentioned in console

Here's a solution without having a mute role
client.on('message', (message) => {
if(message.content.includes('Heck')) {
let member = message.member;
for (var [snowflake, channel] of msg.guild.channels.cache) {
channel.overwritePermissions(member, { SEND_MESSAGES: false })
.then()
.catch(console.error);
}
}
}

Related

I would like my bot to send a dm to the person who and ban

I made my bot etc but I would like to make it so that the bot sends a dm when it ban a person I do not find it has been 3 hours that I search but without success
exports.run = (client, message, args) => {
if (message.member.hasPermission('BAN_MEMBERS')) {
const user = message.mentions.users.first();
let reason = args.slice(1).join(' ');
if (!reason) reason = "No reason provided";
if (user) {
const member = message.guild.member(user);
user.send("You we're banned from **__" + message.guild.name + "__** for **__" + reason + "__**")
.catch(() => message.reply("Unable to send message to user"))
.then(() => member.ban({
reason: "BANNED!"
}))
.catch(err => {
message.reply('I was unable to ban the member');
console.error(err);
});
if (member) {
member
.ban({})
.then(() => {
message.reply(`Successfully banned **__${user.tag}__** for **__${reason}__**`);
})
.catch(err => {
message.reply('I was unable to ban the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to ban!");
}
} else {
message.reply('you don\'t have permission to ban members!')
}
}
There's a few flaws here.
Firstly, message.guild.member() is not a method. You should instead use message.mentions.members.first(); instead of message.mentions.users.first(), then access the User object via GuildMember.user (in your case, user.user, unless you rename the variable) if you need to. You could use guild.members.fetch() but this is much easier.
Secondly, you try to message, if you can't you don't bother banning. Which means if a user blocks your bot, they can prevent getting banned by it. So to fix this, with your current code, just do
user.send("message")
.catch(err => {
message.reply("User could not be messaged");
});
user.ban( {reason: "BANNED!"} )
.catch(err => {
message.reply("User could not be banned");
});
If it continues to error after this, please respond with the error your receive.

How do we make a kick command with userid?

So how do we detect the userID with the kick command below?
So below is my kick command and whenever I kick a person I need to mention them (?kick #test) I want to kick a user by their user id (?kick 354353) and their mentions.
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
client.login('TOKEN');
I recommend setting up Arguments if you plan to make more commands that take user input.
However if you're not interested in fully setting up arguments, you can just slice the message and grab the id. You will then need to fetch the member object, make sure to make your function is async for this, or use Promise#then if you prefer.
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const memberId = message.content.slice(' ')[1];
if (memberId) {
const memberToKick = await message.guild.members.cache.fetch(userId);
memberToKick.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
}
}

Cannot read property 'roles' of undefined discord.js v12

I want that the bot gives the reacter a role. But it doesnt work. Does anyone know where the problem is? Im coding in discord.js v12
if (user.bot) return;
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.guild.id !== "753289194738024632") return;
if (reaction.message.channel.id === "753290581412937832") {
const cs = bot.emojis.cache.find(emoji => emoji.name === "csgo");
const vl = bot.emojis.cache.find(emoji => emoji.name === "valorant");
const fn = bot.emojis.cache.find(emoji => emoji.name === "fortnite");
let role = reaction.guild.roles.cache.find(role => role.id === '753290549548679229');
member.roles.add(role.id);
Try changing reaction to message
let role = message.guild.roles.cache.find(role => role.id === '753290549548679229');
I think reaction.guild isn't a valid function
I would change it to this:
if(message.channel.type === 'dm') return message.reply('This command does not work in DMs') //checks if the command wasnt executed in DMs
let role = message.guild.roles.cache.find(role => role.id === '753290549548679229');

Giving roles on discord

I'm making a discord murder mystery bot.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("now done");
}
});
client.login('my token');
What would I add to the code so after the person who was tagged got there role changed from alive to dead?
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.members.cache.get(mention.id);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
/*
client.on("message", async (message) => {
// ...
try {
await Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.error);
The Promise.all means that the promises for adding and removing the roles are started at the same time. A promise is an object that can resolve to a value or reject with an error, so the .catch(console.error) logs all errors. I recommend that you handle errors for message.delete(), mention.send('you are dead'), and message.channel.send("now done") as well.
For more information on member.roles.remove() and member.roles.add(), see the documentation for GuildMemberRoleManager.

Reference error: guild is not defined. Discord.js bot role kick command error

I'm working on a command for my discord bot to kick everyone in a certain role.
I think what i have should work but i keep on getting a reference error saying guild is not defined
client.on('message', message => {
if (message.content.startsWith('-rolekick')) {
console.log('rolekick')
guild.members.forEach(member => {
if (member.roles.has("OutLaw")){
member.kick()
}
})
}
});
Just as the error says, you haven't defined the variable guild anywhere within your code. To get the guild the message was sent in, use Message.guild.
client.on('message', message => {
if (message.content.startsWith('-rolekick') && message.guild) {
console.log('rolekick');
message.guild.members.forEach(member => {
if (member.roles.find(role => role.name === 'OutLaw')) member.kick()
.catch(console.error);
});
}
});

Resources