我有必须用理由踢用户的脚本。
语法:
$ kick @用户原因
但是当我键入:
$ kick sometext nexttext
我在控制台中出错:
TypeError:无法读取未定义的属性“踢”
和机器人停止...
如何编辑此脚本,以便在输入不正确的值后不会关闭机器人并弹出错误,并且机器人会将消息发送到通道。 “值不正确”?
脚本:
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');
答案 0 :(得分:1)
在javascript中执行可能会崩溃的代码,您可以使用语句
try {
//code to test
} catch(err) {
//code if it crash
}
答案 1 :(得分:0)
添加一个if (member)
来测试是否有提及。
在其他情况下,您可以发送“错误命令”消息
您还应该仅在消息以您的前缀开头的情况下触发漫游器
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');