我开始构建Discord机器人,我做的第一个功能是踢成员。这是代码
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
如果有人未经踢球和禁令许可而尝试,则不会发生任何事情,因此此部分正在运行。如果管理员输入例如:kick @someone然后有人会被踢。但是,如果管理员输入:kick(没有用户名),则会收到错误消息,并且该漫游器会停止工作,直到我手动将其重新启动为止。这是错误:TypeError:无法读取未定义的属性“踢”。我该怎么做才能使其完全正常工作?
答案 0 :(得分:2)
您需要检查该用户是否存在。 试试是这样的:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
如果您想处理更多可能的错误,则需要使用try-catch块:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
try {
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
} catch (error) {
console.log(error);
message.channel.send('An error has occured');
}
}
}
答案 1 :(得分:1)
在踢出该成员之前,检查用户是否提到了另一个用户:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if (!member)
return;
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
你不能踢undefined
。