so I am trying to make a command like $roletested #user which should give the user mentioned the specific role. I get an error called:_ "Cannot read property 'roles' of undefined... Help me out please, here's my code :D
if (message.content.startsWith(prefix + "roletested")) {
let testedUser = message.mentions.members.first()
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'));
if(!testedUser) return message.channel.send("You have to mention the person you want to assign the role to!").then((declineMsg) => { message.react('❌');
declineMsg.delete({timeout: 5000});
let testedRole = message.guild.roles.cache.find(role => role.id === "724676382776492113");
testedUser.roles.add(testedRole);
message.channel.send("Added the role `TESTED` to user.")
})}})
Your code but fixed
if (message.content.startsWith(prefix + "roletested")) {
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))
let testedRole = message.guild.roles.cache.get('724676382776492113');
let testedUser = message.mentions.members.first();
if(!testedUser) return message.channel.send("You have to mention the person you want to assign the role to!").then((declineMsg) => { message.react('❌')
declineMsg.delete({timeout: 5000});
});
testedUser.roles.add(testedRole);
message.channel.send("Added the role `TESTED` to user.")
}
I fixed your code :
I put in order something (the code is the same, I only changed something)
You can't use message.guild.roles.cache.find(...) so I changed it to message.guild.role.cache.get('Role ID')
Source : Link
Code :
if (message.content.startsWith(prefix + 'roletested')) {
const testedUser = message.mentions.members.first();
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'));
if (!testedUser) {
message.channel.send('You have to mention the person you want to assign the role to!').then(declineMsg => {
message.react('❌');
declineMsg.delete({ timeout: 5000 });
return;
});
}
const testedRole = message.guild.roles.cache.get('395671618912780289');
testedUser.roles.add(testedRole);
message.channel.send('Added the role `TESTED` to user.');
}
I tested this code on my bot and it worked as expected.
Related
So i am trying to make a command that mute a member. I want my bot to check if there is role name Muted and if there is not, to create a role for Muted members.
This is the code:
module.exports = {
name: 'mute',
description: 'mutes a member',
execute(message, args, Discord, bot) {
let mutedRole = message.guild.roles.cache.find(r => r.name === 'Muted')
if(!mutedRole) {
Guild.roles.create({
data: {
name: 'Muted',
color: 'BLACK'
}
})
}
}
}
and the error is this:
C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\mute.js:10
Guild.roles.create({
^
TypeError: Cannot read property 'create' of undefined
I don't think you should create a role via code. I think you should create a role in your Discord server (like actually just making one without code). Download the ms package. (npm i ms) Then, paste this code in:
const ms = require('ms');
module.exports = {
name: "mute",
description: "Mutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
if (!args[1]){
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted.`);
return;
}
if (isNaN(args[1]) || !args[1] === ' '){
message.channel.send("Please enter a real number! (If you have a space after the username and you don\'t want to set a time limit, delete the space. YOU HAVE TO.)");
return;
}
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);
setTimeout(function(){
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
}, ms(args[1]));
} else {
message.channel.send("Can't find that member!");
}
}
}
Thanks to CodeLyon for this code. Hope this works for you! It even includes a time limit.
format 1: !mute #User
format 2: !mute #User 1000 (1000 can be changed, just make sure it's in milliseconds)
module.exports = {
name: "unmute",
description: "Unmutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = 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 unmuted.`);
} else {
message.channel.send("Can't find that member!");
}
}
}
format: !unmute #User
Remember, this code only works if you have a role Member and a role Muted. So, in your server, add the role Member to everybody and add a role Muted (not to everybody).
Hope this works! If there's any need for clarification, please tell me in the comments.
at the moment I am trying to make a role command for my bot. For example: t!role add #person <name of role>. But I can't figure out how to get the role as people have usernames with different lengths so I cannot use .slice which I have been able to use for creating a role
Currently my bot says that it can't find that role
My code:
const config = require("../../config.json");
module.exports = {
name: "role",
description: "Creates/removes roles from server and adds/removes roles from members",
category: "utility",
run: async (client, message, args) => {
const mentionedMember = message.mentions.members.first();
let messageRole = message.content.slice(config.prefix.length + 12).trim();
const findRole = message.guild.roles.cache.find(r => r.name === messageRole);
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("You do not have permission to use this command");
if (args[0].toLowerCase() == "create") {
let roleName = message.content.slice(config.prefix.length + 12);
if (!roleName) return message.channel.send("You need to specify a name for the role");
let newRole = await message.guild.roles.create({ data: { name: roleName, permissions: false } });
message.channel.send(`**${roleName}** has been created`);
} else if (args[0].toLowerCase() === "delete") {
if (!findRole) return message.channel.send("You need to specify a role to be deleted\n\n" + messageRole);
findRole.delete();
message.channel.send(`${findRole.name} has been deleted`);
} else if (args[0].toLowerCase() === "add") {
if (!args[1]) return message.channel.send("You need to mention the member you want to give the role to");
if (!mentionedMember) return message.channel.send("I can't find that member");
if (!args[2]) return message.channel.send("You need to specify a role I have to give");
if (!findRole) return message.channel.send("I can't find that role");
if (mentionedMember.roles.cache.has(findRole)) return message.channel.send(`${mentionedMember.name} already has that role`);
mentionedMember.addRole(findRole);
message.channel.send(`${mentionedMember.name} has been given the role ${findRole.name}`)
return undefined
} else if (args[0].toLowerCase() === "remove") {
if (!args[1]) return message.channel.send("You need to mention the member you want to remove the role from");
if (!mentionedMember) return message.channel.send("I can't find that member");
if (!args[2]) return message.channel.send("You need to specify a role I have to remove");
if (!mentionedRole) return message.channel.send("I can't find that role");
if (!mentionedMember.roles.cache.has(mentionedRole.id)) return message.channel.send(`${mentionedMember} doesnt have that role`);
mentionedMember.roles.remove(mentionedRole.id);
message.channel.send(`**${mentionedRole.name}** has been removed from ${mentionedMember}`);
return undefined
}
}
}
Slice the amount of args. If you slice an array, it will remove one entire value from it.
[1, 2, 3].slice(2)
// result: [3]
Since args is an array, all you have to do is args.slice(2), assuming args does not include the command message.
I'm trying to find if any member having a particular role id is present in a particular voice channel. If even 1 member having the particular role id is present in that particular voice channel, then only those members can use the commands of music bot.
From my research, I have came to know that voiceStateUpdate may help but the problem is I don't know how to use it in my codes(cause I am new to JavaScript). Here is the link to the documentation:
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-voiceStateUpdate .
Here is a part of my code:
client.on('voiceStateUpdate', (oldMember, newMember) => {
});
client.on('message', async message => {
if (message.author.bot) return
if (!message.content.startsWith(prefix)) return
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
const args = message.content.substring(prefix.length).split(' ');
const searchString = args.slice(1).join(' ')
const url = args[1] ? args[1].replace(/<(._)>/g, '$1') : ''
const serverQueue = queue.get(message.guild.id)
if() { //the conditional statement I am trying to put here but I don't know how to do it properly
if (message.content.startsWith(`${prefix}play`)) {
const voiceChannel = message.member.voice.channel
if (!voiceChannel) return message.channel.send("You need to be in a voice channel to play music")
.......
So the main thing is that I don't know what to write their exactly in the if statement that would make my code work properly.
client.on("message", async message => {
// Checking if the message author is a bot.
if (message.author.bot) return false;
// Checking if the message was sent in a DM channel.
if (!message.guild) return false;
// The role that can use the command.
const Role = message.guild.roles.cache.get("RoleID");
// The voice channel in which the command can be used.
const VoiceChannel = message.guild.channels.cache.get("VoiceChannelID");
if (message.content.toLowerCase() == "test") {
// Checking if the GuildMember is in a VoiceChannel.
if (!message.member.voice.channel) return message.reply("You need to be in a voice channel.");
// Checking if the GuildMember is in the required VoiceChannel.
if (message.member.voice.channelID !== VoiceChannel.id) return message.reply("You are in the wrong VoiceChannel.");
// Checking if the GuildMember has the required Role.
if (!message.member.roles.cache.has(Role.id)) return message.reply("You are not allowed to execute this command.");
// Execute your command.
return message.reply("Command executed");
};
});
So from what I can understand, you want the command to only execute when a user with the role 'Example Role' is in the channel 'Example Channel'
For this you will need the role id and the channel id.
client.on("message", async message => {
if (message.author.bot) return;
if (!(message.guild)) return;
var roleID = 'RoleID';
var vc = message.guild.channels.cache.get("VoiceChannelID");
if (message.content.toLowerCase() == "test") {
canUse = false;
vc.members.forEach((member) => {
if (member.roles.has(roleID)) {
canUse = True;
}
})
if (!(canUse)) { // nobody in the voice channel has the role specified.
return;
}
console.log("A member of the voice channel has the role specified")
}
});
i was wondering if someone can share a code with me or message me on discord to help me --> Maniac#3833
i tried this code below.. and it failed.
if (msg.startsWith(prefix + 'unbanall')) {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.channel.send('You don\'t have permissions to use this command')
message.guild.fetchBans().then(bans => {
bans.forEach(member => {
message.guild.members.unban(member);
message.channel.send(`Unbanned **${bans.size}** users`)
})
})
}
The fetchBans() method returns a collection of BanInfo. So you need to do it this way:
if (msg.startsWith(prefix + 'unbanall')) {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.channel.send('You don\'t have permissions to use this command')
message.guild.fetchBans().then(bans => {
bans.forEach(banInfo => {
message.guild.members.unban(banInfo.user);
});
message.channel.send(`Unbanned **${bans.size}** users`)
})
}
Also, the message.channel.send() won't wait the forEach, so it will send it before all the members are banned.
Well, I followed "The Source Code" "discord.js" tutorial, (even copy-pasted his code from GitHub) but the ban and kick commands he's shown don't work, I assume they got broken by a recent update. It sends the embed to the incidents channel but doesn't actually ban the player. Also, if you have any suggestions for me to change things, please suggest!
if (cmd === `${prefix}ban`) {
let bUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!bUser) return message.channel.send("Can't find user!");
let bReason = args.join(" ").slice(22);
if (!message.member.hasPermission("MANAGE_MEMBERS")) return message.channel.send("No can do pal!");
if (bUser.hasPermission("MANAGE_MESSAGES")) return message.channel.send("That person can't be banned!");
let banEmbed = new Discord.RichEmbed()
.setDescription("Ban Management")
.setColor("#bc0000")
.addField("Banned User", `${bUser} with ID ${bUser.id}`)
.addField("Banned By", `<#${message.author.id}> with ID ${message.author.id}`)
.addField("Banned In", message.channel)
.addField("Time", message.createdAt)
.addField("Reason", bReason);
let incidentchannel = message.guild.channels.find(`name`, "incidents");
if (!incidentchannel) return message.channel.send("Can't find incidents channel.");
message.guild.member(bUser).ban(bReason);
message.delete().catch(O_o => {});
incidentchannel.send(banEmbed);
return;
}
message.guild.member(bUser).ban(bReason);
This will not ban the member. The message has a member property so you don't need to use message.guild.member you can just easily use message.member.
So it should look like this:
if (cmd === `${prefix}ban`) {
let bUser = message.guild.member(message.mentions.members.first() || message.guild.members.get(args[0]));
if (!bUser) return message.channel.send("Can't find user!");
let bReason = args.join(" ").slice(22);
if (!message.member.hasPermission("MANAGE_MEMBERS")) return message.channel.send("No can do pal!");
if (bUser.hasPermission("MANAGE_MESSAGES")) return message.channel.send("That person can't be banned!");
let banEmbed = new Discord.RichEmbed()
.setDescription("Ban Management")
.setColor("#bc0000")
.addField("Banned User", `${bUser.user.tag} with ID ${bUser.id}`)
.addField("Banned By", `<#${message.author.id}> with ID ${message.author.id}`)
.addField("Banned In", message.channel.name)
.addField("Time", message.createdAt)
.addField("Reason", bReason);
let incidentchannel = message.guild.channels.find(`name`, "incidents");
if (!incidentchannel) return message.channel.send("Can't find incidents channel.");
message.guild.member(bUser).ban({
reason: bReason
});
message.delete();
incidentchannel.send({
embed: banEmbed
});
return;
}
I changed a lot because a lot was outdated and could not work. It could be that I haven't seen one or the other mistake.
Let me know if it worked! :)
Best regards,
Monkeyyy11
This seems awfully complicated, I hope my command can make things a bit easier!
bot.on('message', message => {
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const commandName = arguments.shift().toLowerCase();
if (message.content.startsWith(prefix) && commandName == "kick") {
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("Permissions invalid");
const userKick = message.mentions.users.first();
if (userKick) {
var member = message.guild.member(userKick);
if (member) {
member.kick({
reason: `This person was kicked using a bot's moderation system. We are so sorry if this caused problems.`
}).then(() => {
message.reply(`A user been kicked.`)
})
} else {
message.reply(`User not found`);
}
} else {
message.reply(`Please enter a name`)
}}})
bot.on('message', message => {
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const commandName = arguments.shift().toLowerCase();
if (message.content.startsWith(prefix) && commandName == "ban") {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Permissions invalid");
const userBan = message.mentions.users.first();
if (userBan) {
var member = message.guild.member(userBan);
if (member) {
member.ban({
reason: `This person was banned using a bot's moderation system. We are so sorry if this caused problems.`
}).then(() => {
message.reply(`a user has been banned!`)
})
} else {
message.reply(`User not found`);
}
} else {
message.reply(`Please enter a name`)
}}})
If you use discord.js v12 or higher, then RichEmbed is now deprecated. Instead, use MessageEmbed