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.
Related
My bot is not responding to any commands except for the .purge command.
Here is my code.
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
const { prefix, token } = require('./config.json');
client.on('ready', () => {
client.user.setStatus('invisible');
console.log('Bot ready!');
client.user.setActivity('Bot is in WIP Do not expect stuff to work', {
type: 'STREAMING',
url: "https://www.twitch.tv/jonkps4"
});
console.log('Changed status!');
});
client.on('message', message => {
if (message.content.startsWith(".") || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message === 'apply') {
message.reply("The Small Developers Application form link is:")
message.reply("https://forms.gle/nb6QwNySjC63wSMUA")
}
if (message === 'kick') {
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the guild
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member \n Maybe due to I having missing permissions or My role is not the higher than the role the person to kick has');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
if (command === 'purge') {
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('Not a valid number');
} else if (amount > 100) {
return message.reply('Too many messages to clear. \n In order to clear the whole channel or clear more please either ```1. Right click on the channel and click Clone Channel``` or ```2. Execute this command again but more times and a number less than 100.```');
} else if (amount <= 1) {
return message.reply('Amount of messages to clear **MUST** not be less than 1 or more than 100.')
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('**There was an error trying to prune messages in this channel!**');
});
}
});
client.login(token);
I need a specific command to work which is the .apply command
and i would like to know why my embeds do not work.
I tried this embed example It didn't work.
const embed = new MessageEmbed()
// Set the title of the field
.setTitle('A slick little embed')
// Set the color of the embed
.setColor(0xff0000)
// Set the main content of the embed
.setDescription('Hello, this is a slick embed!');
.setThumbnail('https://tr.rbxcdn.com/23e104f6348dd71d597c3246990b9d84/420/420/Decal/Png')
// Send the embed to the same channel as the message
message.channel.send(embed);
What did I do wrong? I am quite new to Discord.JS Any help would be needed.
You used the message parameter instead of command. Instead of message === 'xxx' put command === 'xxx'. Simple mistake, I think that was what you meant anyways. Of course the purge command worked because you put command === 'purge' there
Im quite new to coding and ive come across an issue which I'm not really sure what the issue is.
Ive been making my discord bot kick/ban command and its giving me the error "Declaration or statement expected. ts(1128) (11, 1)"
Here is my code helps appreciated.
CODE:
member.kick().then((member) => {
message.channel.send(`:wave: ${member.displayName} has been kicked`);
}).catch(() => {
if (!message.member.hasPermission(['KICK_MEMBERS', 'ADMINISTRATOR'])) {
message.reply("You cannot kick members");
} else if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS', 'ADMINISTRATOR'])) {
message.reply("You cannont kick this member");
}
})
}
if (message.content.startsWith(`${prefix}ban`)) {
let member = message.mentions.members.first();
member.ban().then((member) => {
message.channel.send(`:wave: ${member.displayName} has been kicked`);
}).catch(() => {
if (!message.member.hasPermission(['BAN_MEMBERS', 'ADMINISTRATOR'])) {
message.reply("You cannot ban members");
} else if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS', 'ADMINISTRATOR'])) {
message.reply("You cannont ban this member");
}
})
}
The reason why the code is throwing an error is because you can't check for permissions in a .catch block because catch blocks handle errors thrown by code. Instead, you should check for permissions before the command is executed. Additionally, you are checking that the user has all three permissions. You can use the JavaScript OR (||) to check that they have any of the permissions and the Administrator permission has ALL PERMISSIONS, eliminating the need to add it to the list. I've rewritten the code below
// You never need to check for ADMINISTRATOR, because it has all permissions
if (!message.member.hasPermission('KICK_MEMBERS')) {
message.reply("you cannot kick members");
} else if (member.hasPermission('KICK_MEMBERS' || 'BAN_MEMBERS')) {
message.reply("you cannot kick this member");
}
member.kick()
.then(member => message.channel.send(`:wave: ${member.displayName} has been kicked`))
.catch(e => console.log(e));
}
if (message.content.startsWith(`${prefix}ban`)) {
let member = message.mentions.members.first();
if (!message.member.hasPermission('BAN_MEMBERS')) {
message.reply("You cannot ban members")
} else if (member.hasPermission('KICK_MEMBERS' || 'BAN_MEMBERS')) {
message.reply("You cannont ban this member")
}
member.ban()
.then(member => message.channel.send(`:wave: ${member.displayName} has been banned`)
.catch(e => console.log(e));
}
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")
}
});
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.