【问题标题】:Discord.js - command line issueDiscord.js - 命令行问题
【发布时间】:2020-12-29 07:19:41
【问题描述】:
client.on("message", (message) => {
    if(message.content.startsWith("!Bonk")){
        let userToMention = message.mentions.users.first();
        message.channel.send("bonks "+userToMention.toString() + "  https://tenor.com/view/bonk-meme-dog-doge-gif-14889944");
    }

});

当您运行命令!bonk @devildog 时,机器人会显示gif + @devildog。 但是当你单独运行命令!bonk 时,机器人会随机崩溃。有什么办法可以用if else 解决这个问题?

错误:

message.channel.send("bonks "+userToMention.toString() + "https://tenor.com/view/bonk-meme-dog-doge-gif-14889944");
                                                    ^

TypeError: Cannot read property 'toString' of undefined

【问题讨论】:

  • 我怀疑如果消息中包含 0 次提及,message.mentions.users 为空,因此userToMention 为空,您无法调用toString()

标签: javascript discord.js


【解决方案1】:

由于在您的示例中,调用命令不包含任何提及,因此对 message.mentions.users.first(); 的调用将导致崩溃。当没有提到用户时(如您的示例中),first() 方法将无法在users 中找到第一个用户,因为根本没有提到用户!因此,在 null/undefined 对象上调用 toString() 将导致异常。

在您的初始if 语句中检查用户以防止这种行为:

client.on("message", (message) => {
    if(message.content.startsWith("!Bonk") && message.mentions.users.array.length > 0){
        let userToMention = message.mentions.users.first();
        message.channel.send("bonks "+userToMention.toString() + "  https://tenor.com/view/bonk-meme-dog-doge-gif-14889944");
    }

});

【讨论】:

  • 好的,崩溃问题解决了,但是现在bot停止响应命令了
  • 您应该使用标准的 JavaScript 调试概念来确定 message.mentions.users.array.length 表达式会阻止脚本的主要部分运行的原因。
【解决方案2】:

你好@Blissy89!

是的,您可以通过以下方式修复它:

if(!userToMention) return message.say('Mention a user to run this command!')

放在上面 message.channel.send

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 2020-08-24
    • 2020-06-16
    • 2020-01-14
    • 2021-10-06
    • 1970-01-01
    • 2018-07-14
    • 2020-06-09
    相关资源
    最近更新 更多