Reputation: 23
I have script which have to kick user with reason.
Syntax:
$kick @user Reason
but when I type:
$kick sometext nexttext
I got error in console:
TypeError: Cannot read property 'kick' of undefined
and bot stop...
How can I edit this script so that after entering an incorrect value, an error will not pop up turning off the bot and bot will send message to channel eg. "Incorrect value"?
Script:
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "kick") {
let member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
member.kick(reason);
message.delete();
client.channels.cache.get('737341022782357566').send("User <@" + member.id + "> with id " + member.id + " has been kicked by <@" + message.author.id + "> with reason " + reason)
}})
client.login('token');
Upvotes: 1
Views: 3112
Reputation: 133
in javascript to execute a code that have chances to chrash, you can use the statment
try {
//code to test
} catch(err) {
//code if it crash
}
Upvotes: 1
Reputation: 1867
add a if (member)
to test if there was a mention.
In the else, you can send your "bad command" message
you should also only trigger the bot if the message starts with your prefix
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
if (!message.content.startsWith(prefix)) { return }
//this line prevents the bot to execute every message
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "kick") {
let member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (member) { // add this
member.kick(reason);
client.channels.cache.get('737341022782357566').send(`User ${member.user} with id: ${member.id} has been kicked by ${message.author} with reason: ${reason}`);
} else {
message.reply("invalid parameters for $kick")
}
message.delete();
}
})
client.login('token');
Upvotes: 0