The problem that I have is with the case “ban”. When I go “+ban” and then mention the user, it works. The user is banned and the message is sent but then it exits with a message error about the Discord API and permission, even though I have admin permission for the bot.
And when I don’t mention anyone, it does what it’s supposed to do and just gives out the “There is no one to ban.” message but it then exits with an error (Error [BAN_RESOLVE_ID]: Couldn't resolve the user ID to ban.
). I need to rerun the code to get the bot started again.
Do you know how to to keep the bot running with no issues?
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = "+";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
const { content } = msg;
let latency = Date.now() - msg.createdTimestamp;
let latencyOfAPI = Math.round(client.ws.ping);
const user = msg.mentions.users.first();
let banMember = msg.guild.members.ban(user);
if (!content.startsWith(prefix)) return;
const args = content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
switch(command) {
case "ping" : {
msg.reply("This is the latency between the message and the response: " + latency + "." + "nThis is the API latency: " + latencyOfAPI + ".");
break;
}
case "pong" : {
msg.reply("ping");
break
}
case "ban" : {
if (user) {
banMember;
msg.reply("The user " + user + " has been banned.")
} else {
return msg.reply("There is no one to ban.")
}
break
}
}
});
client.login( ..)
Advertisement
Answer
The first problem is that you try to ban someone even if there is no member mentioned or if there was no ban command. You try to define a banMember
variable using let banMember = msg.guild.members.ban(user)
but it calls the ban()
method before you check if the command is “ban”. You need to move this ban()
method inside the switch statement.
Second, you try to ban a User
. msg.mentions.users.first()
returns a User
if there’s someone mentioned. User
s don’t have a ban()
method, only GuildMember
s have.
Instead of msg.mentions.users
you should use msg.mentions.members
.
Your code should look something like this:
client.on('message', (msg) => {
const { content } = msg;
if (!content.startsWith(prefix)) return;
const args = content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'ping': {
let latency = Date.now() - msg.createdTimestamp;
let latencyOfAPI = Math.round(client.ws.ping);
msg.reply(
`This is the latency between the message and the response: ${latency}.nThis is the API latency: ${latencyOfAPI}.`,
);
break;
}
case 'pong': {
msg.reply('ping');
break;
}
case 'ban': {
const member = msg.mentions.members.first();
if (!member) return msg.reply('There is no one to ban.');
msg.guild.members
.ban(member)
.then(() => msg.reply(`The member ${member} has been banned.`))
.catch(console.error);
break;
}
}
});