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