不和谐机器人踢
Posted
技术标签:
【中文标题】不和谐机器人踢【英文标题】:Discord bot kick 【发布时间】:2020-09-23 07:07:48 【问题描述】:我开始构建一个 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(`$prefixkick`))
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:无法读取未定义的属性“踢”。我可以做些什么来使它充分发挥作用?
【问题讨论】:
【参考方案1】:您需要检查该用户是否存在。 试试是这样的:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"]))
if (message.content.startsWith(`$prefixkick`))
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(`$prefixkick`))
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');
【讨论】:
【参考方案2】:在踢成员之前检查用户是否提到了另一个用户:
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(`$prefixkick`))
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
。
【讨论】:
以上是关于不和谐机器人踢的主要内容,如果未能解决你的问题,请参考以下文章