How do I fix this to add a role mentioned in the command to the user? - javascript

I am coding a custom discord bot for my server and I ran into this issue. I want to add a role to a user that is not predefined. IE: I want to be able to &addrole #user anyrole and add that role to a user. Here is the code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
//!addrole #andrew anyrole
if(!message.member.hasPermission("MANAGE_MEMBERS")) return
message.reply("Sorry pal, you can't do that.");
let rMember = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if(!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("Specify a role!");
let gRole = message.guild.roles.find('name', any);
if(!gRole) return message.reply("Couldn't find that role.");
if(rMember.roles.has(gRole.id)) return message.reply("They already have
that role.");
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Congrats, you have been given the role
${gRole.name}`)
}catch(e){
message.channel.send(`Congrats to <#${rMember.id}>, they have been given
the role ${gRole.name}. We tried to DM them, but their DMs are locked.`)
}
}
module.exports.help = {
name: "addrole"
}

Related

Discord.js Dev detector

I am making a discord bot and I have a few dev only commands. However, the system I use to detect if someone is a bot developer doesn't work.
My code:
const { MessageEmbed } = require("discord.js");
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return message.channel.send("Slow down, poke. This is devs only, poke?"); // return if author isn't bot owner
let user = message.mentions.users.first();
if (!user) return message.channel.send("Send money to who?");
let amount = args[1];
if (!amount || isNaN(amount)) return message.reply("That isn't a valid amount.");
let data = client.eco.addMoney(user.id, parseInt(amount));
const embed = new MessageEmbed()
.setTitle(`You'll be rich! The money has been added.`)
.addField(`User`, `<#${data.user}>`)
.addField(`Balance Given`, `${data.amount} 💸`)
.addField(`Total Amount`, data.after)
.setColor("#f54242")
.setThumbnail(user.displayAvatarURL)
.setTimestamp();
return message.channel.send(embed);
}
exports.help = {
name: "addmoney",
aliases: ["addbal"],
usage: `addmoney #user <amount>`
}
I shouldn't have received the devs only message, but when I tested in discord, I did.
Thought I'd just make this an answer than a comment, as I've had time to test.
This works, but it may be related to how you store your IDs in the admin array.
.includes() is type sensitive, so a string wont match a number. Discord IDs are a string, so your array has to match it.
Example:
const admins = [96876194712018944];
console.log(admins.includes("96876194712018944")); // false

discord.js the bot crash when there's no mention in my unmute command

so i made a mute and unmute command, the mute one works pretty well and i just gotta add some things, the unmute one also works well but when there's no mentioned person (for example q!unmute and not q!unmute [user]) the bot crashes, i tried catch and that stuff but i really don't understand how they work, i'm pretty new to js, this is the string that should send the "you have to mention a user" error:
if (!member) return message.channel.send("You have to mention a valid member");
this is the rest of the code:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
if (!member) return message.channel.send("You have to mention a valid member");
}
}
}
i hope you can help
In your code you're checking if the user mentioned is null, but it is at the end of the function. I think that putting the if just after you get the value should work:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
if (!member) return message.channel.send("You have to mention a valid member");
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
}
}
}
Move
if (!member) return message.channel.send("You have to mention a valid member");
Below where you define member.
const member = message.mentions.members.first();

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

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

How Do I Add Roles via Discord.js?

I'm currently creating a bot through Discord.js, and I want someone to be able to state a command in order to gain a role. However, I can't figure this out for the life of me.
In my bot folder, I've created an addrole.js file with the following chunk of code:
const Discord = require("discord.js");
const roles = message.guild.roles.cache.map((role) => role);
const member = message.mentions.members.first();
const role = message.mentions.roles.first();
const colours = require("../colours.json");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, frog lover! :disappointed: :broken_heart: You don't have permission to perform this command!"
);
let rMember =
message.mentions.members.first ||
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role =
message.guild.roles.cache.find((r) => r.name == args[1]) ||
message.guild.roles.cache.find((r) => r.id == args[1]) ||
message.mentions.roles.first();
if (!role)
return message.channel.send(
"Which role do I give to this user, frog lover? :point_right: :point_left:"
);
if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, friend :broken_heart: :shrug: I don't have permission to perform this command!"
);
if (rMember.roles.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e.message));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
let embed = new Discord.RichEmbed()
.setColor(colours.redlight)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL)
.addField("Moderation:", "Addrole")
.addField("Mutee:", rMember.user.username)
.addField("Reason:", reason)
.addField("Date:", message.createdAt.toLocaleString());
letsChannel = message.guild.channels.cache.find(
(c) => c.name === "beans-the-frog"
);
sChannel.send(embedVariable);
};
module.exports.config = {
name: "addrole",
description: "Adds a role to a member of the guild!",
usage: "beans addrole",
accessableby: "Moderators",
aliases: ["ar", "roleadd"],
};
I followed THIS tutorial to get here: https://www.youtube.com/watch?v=GCSbZ2UbriU
I've given my bot the Manage_Roles permission and have attempted to state both "beans addrole (role) (user)" and "beans addrole (user) (role)". I'm expecting him to even specify error messages, or even better yet, add the role. However, he isn't even spitting out error messages, and neither is my console. Everything else works fine, it's just that this particular function won't work. Any input/feedback would help a LOT.
I found a lot of typos inside of your code, and also, it has some problem because you mixed discord.js^11.x with discord.js^12.x. I fixed your code below, but make sure your bot has the ADMINISTRATOR permission as well required by your command.
const Discord = require("discord.js");
// You defined the 3 lines here twice, which requires `message` to be defined.
const colours = require("../colours.json");
module.exports.run = async (bot, message, args) => {
// `Member.hasPermissions()` is deprecated
if (!message.member.permissions.has(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, frog lover! :disappointed: :broken_heart: You don't have permission to perform this command!"
);
let rMember =
message.mentions.members.first() || // `.first()` is a function.
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role =
message.guild.roles.cache.find((r) => r.name == args[1]) ||
message.guild.roles.cache.find((r) => r.id == args[1]) ||
message.mentions.roles.first();
if (!role)
return message.channel.send(
"Which role do I give to this user, frog lover? :point_right: :point_left:"
);
if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, friend :broken_heart: :shrug: I don't have permission to perform this command!"
);
if (rMember.roles.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
let embed = new Discord.MessageEmbed()
.setColor(colours.redlight)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("Moderation:", "Addrole")
.addField("Mute:", rMember.user.username)
.addField("Reason:", reason)
.addField("Date:", message.createdAt); // `.toLocaleString()` isn't required, discord automatically coonverts it to string.
let sChannel = message.guild.channels.cache.find(
(c) => c.name === "beans-the-frog"
);
sChannel.send(embedVariable);
};
module.exports.config = {
name: "addrole",
description: "Adds a role to a member of the guild!",
usage: "beans addrole",
accessableby: "Moderators",
aliases: ["ar", "roleadd"],
};
To learn more, try visiting the links below:
Discordjs.guide - Guide - Updating from v11 to v12
Discordjs.guide - Guide - Permissions
Discordjs.guide - Guide - Handling Commands
if (rMember.roles.cache.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
I used this snippet to get my bot to add roles. Thanks to user above. I had to add cache though. in first line.
Your problem mainly appears from these lines:-
const roles = message.guild.roles.cache.map((role) => role);
const member = message.mentions.members.first();
const role = message.mentions.roles.first();
The problem happens because message is not defined until you define a function. Try moving the code inside the run function.

Categories

Resources