How to assign roles with a command - discord.js - javascript

I wanted to give my bot the functionality to assign roles with a command
For example, +mod #user would give #user the role of Mod.
Code in my main.js:
if(command == 'mod'){
client.commands.get('mod').execute(message, args);
}
Code in my mod.js file:
module.exports = {
name: 'mod',
description: "This command gives member the Mod role",
execute(message, args){
const member = message.mentions.users.first();
member.roles.add('role ID xxxx');
}
}
I get an error saying the member is empty. Am I doing something wrong?

I don't think it said member is empty. users don't have roles though, members have. So you will need to get the first mentioned member instead.
module.exports = {
name: 'mod',
description: 'This command gives member the Mod role',
async execute(message, args) {
const member = message.mentions.members.first();
if (!member) {
return message.reply('you need to mention someone');
}
try {
await member.roles.add('ROLE_ID');
message.reply(`${member} is now a mod 🎉`);
} catch (error) {
console.log(error);
message.reply('Oops, there was an error');
}
},
};

Related

Discord.js kick command permissions problem

So the last question I asked, I tried to use the sample code in MrMythical answer. This time, I encountered another problem:
if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)){
^
ReferenceError: Permissions is not defined
The code:
module.exports = new Command({
name: "kick",
description: "kick",
async run(message, args, client) {
if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)) {
if (message.mentions.members) {
try {
message.mentions.kick();
} catch {
message.reply("I don't have permission to ban " + message.mentions.members.first());
}
} else {
message.reply("You cannot ban " + message.member.mentions.first());
}
}
}
});
Let's say I deleted the if (message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS)), the message the returned when executing the command was I don't have permission to ban <insert_user_id>.
I'm kinda stuck here for a while, if you can help me, thank you so much.
Edit: I forgot to import the Permissions, so there's just "Don't have permissions to kick" now
You will need to import Permissions from discord.js. You can import it at the top of the page, like this:
const { Permissions } = require('discord.js');
Also, message.mentions returns an object and it includes the mentioned members, channels, and roles. It won't have a kick() method and if you try to call it, it will throw an error. As you don't log the error in your catch block, you will have no idea what the error is; it will just send a reply saying "You cannot ban undefined".
You will need to check if there are mentioned members by checking message.mentions.members. It returns a collection; you can grab the first member by using first().
You can kick the first mentioned member like this:
const { Permissions } = require('discord.js');
module.exports = new Command({
name: 'kick',
description: 'kick',
async run(message, args, client) {
if (!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS))
return message.reply('You have no permission to ban members');
if (!message.mentions.members)
return message.reply('You need to mention a member to ban');
let mentionedMember = message.mentions.members.first();
try {
mentionedMember.kick();
} catch (err) {
console.log(err);
message.reply(`Oops, there was an error banning ${mentionedMember}`);
}
},
});

How can I find who deleted the role on "roleDeltete" in discord.js

I'm on v13 of discord.js and when I run this
client.on('roleDelete', a => { console.log(a); }); it only logs deleted: true don't show who deleted. Can somebody help me about how can I find who deleted the role on "roleDelete" event ?
Use audit logs. The bot will need permissions though:
client.on("roleDelete", async role => {
let member;
try {
const log = await role.guild.fetchAuditLogs({
type: "ROLE_DELETE"
})
member = role.guild.members.resolve(log.entries.first().executor)
} catch (err) {
console.log(err) // simply for debugging
}
if (!member) member = null
})
And now when you access member, it will show null if it couldn't find the executor, but will show the GuildMember who deleted the role if they were found.

TypeError: message.author is not a function

For this piece of code, I aim for the author of the message that sent the ban command to be checked for whether they have the permissions necessary to ban the member, instead of instantly being allowed to, however I am unsure of what the const mod should be equivalent to to do so. Any help would be appreciated, thanks.
module.exports = {
name: 'ban',
description: "This command ban a member!",
execute(message, args) {
const target = message.mentions.users.first();
const mod = message.author();
if (mod.hasPermission('BAN_MEMBERS')) {
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.ban();
message.channel.send("User has been banned");
}
} else if (mod.hasPermission(!'BAN_MEMBERS')) {
message.channel.send(`You couldn't ban that member either because they don't exist or because you dont have the required roles!`);
}
}
}
As it says, Message.author is not a function. It is a property. You access it without the brackets
const mod = message.author
Another problem you may get is you can't get permissions. You will need Message.member for that
const mod = message.member

Delete the latest message of the bot in dms

I have a command where the bot sends a message to a specific user trough private messages. Now I want that I can delete the last message of the bot in DMs when there is like an error or something.
What I come up with is this:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
execute(message, args) {
const mentionedMember = message.mentions.members.first().id
const User = client.users.fetch(mentionedMember)
try {
if (!mentionedMember) {
return respond('', 'Bitte erwähne einen Nutzer.', message.channel)
}
User.dmChannel.messages.fetch( {limit: 1} )
.then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete()
});
} catch (error) {
console.error('an error has occured', error);
}
}
}
The error that I'm getting now is:
TypeError: Cannot read property 'messages' of undefined
And yes, I have direct messages with the bot.
Anyone knows what I did wrong?
There are a couple of errors. First, users.fetch and dmChannel.messages.fetch both return a promise, so you'll need for them to be resolved.
In your code above, User is a pending Promise that has no dmChannel property. As it has no dmChannel prop (i.e. it's undefined), you can't read its messages property and you will receive TypeError: Cannot read property 'messages' of undefined.
After you fixed these problems with fetch, there could be another error with the dmChannel. Sometimes (or most of the times?), user.dmChannel returns null. To avoid this, you can create a DM channel first using the createDM() method. It also returns a promise, so you will need to resolve it first :)
Check out the working code below:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
async execute(message, args) {
const mentionedUser = message.mentions.users.first();
if (!mentionedUser)
return respond('', 'Bitte erwähne einen Nutzer.', message.channel);
const user = await client.users.fetch(mentionedUser.id);
const dmChannel = user.dmChannel || (await user.createDM());
try {
const messages = await dmChannel.messages.fetch({ limit: 1 });
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete();
} catch (error) {
console.error('an error has occured', error);
}
},
};

recently i build discord bot, the main problem is, i dont know how to set the permission, so every member of my server can kick and ban others

module.exports = {
name: 'ban',
description: "This command bans a member!",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.members.cache.get(member.id)
memberTarget.ban();
message.channel.send("User has been banned");
}else{
message.channel.send('you couldnt ban that member');
}
}
}
module.exports = {
name: 'kick',
description: "This command kicks a member!",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.members.cache.get(member.id)
memberTarget.kick();
message.channel.send("User has been kicked");
}else{
message.channel.send('you couldnt kick that member');
}
}
}
We could simply check for a user's permission using the .hasPermission() function of the GuildMember object. We could simply integrate it with a simple if statement, that would include the permissions you want to check for:
if (!message.member.hasPermission('BAN_MEMBERS') return; // Would return if the message author does not have permission to Ban Members
if (!message.member.hasPermission('KICK_MEMBERS') return; // Same thing for the Kick Members permission.

Categories

Resources