Discord.js add custom role to a mentioned user - javascript

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.

Related

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

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

discord.js Cant use command with user ID

I'm making a command that rickrolls the mentioned user by sending them a dm and when i try to use it by mentioning someone using their ID it dosent work and sends the error message i added saying: The mentioned user is not in the server
const { DiscordAPIError } = require('discord.js');
const Discord = require('discord.js');
const BaseCommand = require('../../utils/structures/BaseCommand');
module.exports = class RickrollCommand extends BaseCommand {
constructor() {
super('rickroll', 'fun', []);
}
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You really thought i was boutta rickroll myself? AINT NO WAY CHEIF');
const rickrollEmbed = new Discord.MessageEmbed()
.setTitle("You've Been Rickrolled!")
.setThumbnail('https://i1.wp.com/my-thai.org/wp-content/uploads/rick-astley.png?resize=984%2C675&ssl=1')
.setDescription('Rick astley sends his regards')
.setColor('#FFA500');
await mentionedMember.send('https://tenor.com/view/dance-moves-dancing-singer-groovy-gif-17029825')
await mentionedMember.send(rickrollEmbed)
.then(() => {
message.channel.send("Successfully rickrolled the user.");
})
.catch(err => {
message.channel.send('I was unable to rickroll the user.');
});
}
}
The wierd part is it only works with my ID and not any other user's ID.
I think the problem is, that you are using the cache and not the guilds member manager. Therefore, when no other user is cached it will only work with your ID since you are the one sending the message => getting loaded into the cache.
Try this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}
I don't know for sure, but it might also be a bit more optimized if you still prefer the cache, but just use the member manager as an additional backup, like this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first()
|| message.guild.members.cache.get(args[0])
|| await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}

How to log into the ban section of discord using discord.js v12?

I'm working on my ban command and it's fully functional, but I was wondering, how I would log the ban reason into the ban section of discord (example in the attachment)? My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
module.exports = {
name: 'ban',
description: "Mentioned user will be banned",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.members.first()) || message.guild.members.cache.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Invalid Permissions a")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban
console.log(`Ban reason = ${banReason}`)
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
Any help? Thanks :)
It's actually quite easy, just add ({reason: banReason}) after the User.ban part, making it:
User.ban({reason: banReason})
That should log it there properly :)
You can use the reason property of the options parameter in the GuildMember.ban() method:
User.ban({ reason: 'real life danger' })
.then(member => console.log(`${member.name} was banned.`))
.catch(console.error)
Also, in your code, there's no reason for using the Guild.member() method when defining User. Guild.member(user) is used to turn a User object into a GuildMember object.
However, MessageMentions.members.first() already returns a GuildMember object, making it obsolete.

Creating a Role with discord.js

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

Categories

Resources