I am Coding my own discord bot for my server, I have a issue that the bot says no role doesn't exit even if I mentions the role. Here is the code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on("message", message => {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
if (command === "add") {
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ")
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.has(roleAdd.id)){
return message.channel.send("User already has role")
}
if (member) {
member.addRole(roleAdd).catch((error) =>{
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
}
})
client.login(config.token)
What did I made a mistake? Thanks.
First make sure you are using discord.js v12. Type npm i discord.js#latest in your terminal. Here you can see all changes in discord.js v12.
If you are using discord.js v12 now, this code should work for you:
if (!message.member.hasPermission("MANAGE_ROLES"))
return message.channel.send("Insufficient permissions")
const member = message.mentions.members.first()
if (!member)
return message.channel.send("No user mentioned")
const add = args.slice(1).join(" ");
if (!add)
return message.channel.send("No role said")
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
if (!roleAdd)
return message.channel.send("Role does not exist")
if (member.roles.cache.has(roleAdd.id)) {
return message.channel.send("User already has role")
}
if (member) {
member.roles.add(roleAdd).catch((error) => {
message.channel.send("I cant add...")
}).then((member) => {
message.channel.send(`:thumbsup: ${roleAdd} added to ${member.displayName}`)
})
}
Mention the role you want to add won't work because here
const roleAdd = message.guild.roles.cache.find(role => role.name === add);
you just find the role by its name. To fix that you can change that line into:
const roleAdd = message.guild.roles.cache.find(role => role.name === add) || message.mentions.roles.first();
This will allow a user to mention the role as well.
Related
const Discord = require('discord.js');
const config = require('../config.json');
const { Permissions } = require('discord.js');
module.exports.run = async (client, message, args) => {
if(!message.member.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('You can\'t use that!')
if(!message.guild.me.permissions.has(Permissions.FLAGS.BAN_MEMBERS, true)) return message.channel.send('I don\'t have the permissions.')
const member = message.mentions.members.first();
if(!args[0]) return message.channel.send('Please specify a user');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
message.guild.members.unban(`${member}`, `${reason}`)
.catch(err => {
if(err) return message.channel.send('Something went wrong')
})
let banembed = new Discord.MessageEmbed()
.setTitle('Member Unbanned')
.addField('User Unbanned', member)
.addField('Unbanned by', message.author)
.addField('Reason', reason)
.setFooter('Time Unbanned', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
You're using a message.mentions.members.first() which is referring to a pinged person. To use their ID's you can use .fetch or cache.get
const member = await message.guild.members.fetch(args[0])
const member = await message.guild.members.cache.get(args[0])
also you can use them on the same line using or ||
const member = message.mentions.members.first() || await message.guild.members.fetch(args[0]) || await message.guild.members.cache.get(args[0])
I only don't know if its going to work with unban because the bot and the user should on the same server
So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel
So I've made a bot that can mute and umute user. The main problem is, after getting mute and give unmute, the roles not back again
Here's what I've tried
const mainRole = [`791144820810842163` , `794825576602533898` , `791144908240060426` , `791144966474563624` , `791145298072305685` , `791145926344966185` , `791146191336505414` , `791146355552682034` , `792565793568587796` , `795357387794939904` , `795358283623432213` , `798804993468530699` , `791146747367653387`];
module.exports = {
name: `unjail`,
description: "this is unjail command!",
execute(message, args){
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You cant unjail person because you are not staff/co owner/owner");
let mainRole = message.guild.roles.cache.find(role => role.name === 'Peasant');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Jailed');
let = message.guild.members.cache.get(target.id);
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unjailed`);
} else {
message.channel.send('Cant find that member!');
}
}
}
I guess the code logic fine and it should work as intended. So let's describe it and try to solve the problem.
//extract mentioned user, by this command
const target = message.mentions.users.first();
if (target) {
//target mentioned user from discord server members
const memberTarget = message.guild.members.cache.get(target.id);
//check permissions for user that using the command
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You cant unjail person because you are not staff/co owner/owner");
//find roles Peasant in server cache that should be returned and role Jailed
let mainRole = message.guild.roles.cache.find(role => role.name === 'Peasant');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Jailed');
//?????? What have been here?
let = message.guild.members.cache.get(target.id);
//return roles
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unjailed`);
} else {
message.channel.send('Cant find that member!');
}
How actually should work this code, by the correct logic:
No const mainRole = ['791144820810842163',...] predefining before the module.exports.
The following code will return only one role (Peasant in this case) to the unjailed person. But it could return even more roles, if you could store all the roles from the user, at the moment of muting. So you'll need some kind of storage for that and don't forget to add the following logic, to the command that actually muting users.
Writing to JSON file via fs module or any DBaaS for free-for-dev should help you with that.
If you have a huge Discord server with thousands of users, I highly recommend Mongo Atlas for that.
module.exports = {
name: `unjail`,
description: "this is unjail command!",
execute(message, args){
//return exeption for lack of permission
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You cant unjail person because you are not staff/co owner/owner");
const target = message.mentions.users.first();
if (!target) return message.channel.send(`Can't find mentioned user!`);
const memberTarget = message.guild.members.cache.get(target.id);
if (!memberTarget) return message.channel.send(`Can't find mentioned user!`);
/**
* At this point, we should return from the store the original roles for a user to restore
* But since we don't have any storage, let's just return the only available role, Peasant, and remove the role Jailed
*/
let mainRole = message.guild.roles.cache.find(role => role.name === 'Peasant');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Jailed');
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unjailed`);
}
}
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', (oldMessage, newMessage, role, args, guild) => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === '.') {
if (message.guild.channel === 'dot-wars') {
message.guild.members.forEach(member => {
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
member.removeRole(role);
})
}
var role = message.guild.roles.find(role => role.name === 'Dot Master!');
message.member.addRole(role);
}
});
okay so what i want to do is when someone sends a '.' the bot will remove the 'Dot Master!' role from everyone in the server and then add the 'Dot Master!' role to the person that sent it, but only if it is in the 'dot-wars' channel.
A text channel has a name property for reading its name. However, make sure you're checking the channel the message was sent in, not the guild (Message#channel).
if (message.channel.name === 'dot-wars') {
...
}
I was working on a discord bot and for a verification channel. I want users to type only the /verify command: every message or command except /verify they type should get deleted automatically. How can I do this?
Current code:
if (command === "verify") {
if (message.channel.id !== "ChannelID") return;
let role = message.guild.roles.find(rol => rol.name === 'Member')
const reactmessage = await message.channel.send('React with 👌 to verify yourself!');
await reactmessage.react('👌');
const filter = (reaction, user) => reaction.emoji.name === '👌' && !user.bot;
const collector = reactmessage.createReactionCollector(filter, {
time: 15000
});
collector.on('collect', async reaction => {
const user = reaction.users.last();
const guild = reaction.message.guild;
const member = guild.member(user) || await guild.fetchMember(user);
member.addRole(role);
message.channel.send(`Verification Complete.. ${member.displayName}. You have got access to server. `)
});
message.delete();
}
You can add a check at the top of your client.on('message') listener:
client.on('message', message => {
let verified = !!message.member.roles.find(role => role.name == 'Member');
// ... command parsing ect...
if (!verified && command == 'verify') {...}
else if (verified) {
// other commands...
}
});