【问题标题】:Discord.js printing out ReferenceError: command is not definedDiscord.js 打印出 ReferenceError: command is not defined
【发布时间】:2020-02-16 04:17:01
【问题描述】:

我对编程很陌生,我想我会搞砸并尝试使用 discord.js 编写一个不和谐机器人来搞乱我的朋友。 不幸的是,虽然我遇到了一些错误,但完整的日志附在下面(UnhandledPromiseRejectionWarning: ReferenceError: command is not defined)

这里是完整的代码:

const BotName = "name"; // Name
const Token = "token"; // Token
const SpamMessage = "hello"; // Message
const YourDiscordID = 398561449078685717; // My discord ID 

// Actual bot code

const Discord = require("discord.js");
const prefix = "-";

const bot = new Discord.Client({disableEveryone: true});

bot.on("ready", async () => {
 bot.user.setActivity("Getting Things Ready", "https://twitch.tv/")

 console.log(`${BotName} Loaded!`);

 try {
     let link = await bot.generateInvite(["ADMINISTRATOR"]);
     console.log(link);
 } catch(e) {
     console.log(e);
 };
});

bot.on("message", async message => {
 if(message.author.bot) return;

 if(!command.startsWith(prefix)) return;

     if(command === `${prefix}spam`) {
         if(!message.author.id === YourDiscordID) return;
         let Ping = message.mentions.users.first();
         setInterval(function(){
             Ping.send(SpamMessage)
         },
             1200
         );
     };
});

bot.login(Token);

我希望收到“Ready!”在让机器人加入我的服务器后在控制台中,而不是它卡在带有登录 URL 的消息上,如果我在不和谐上键入命令 (-spam),我会收到下面列出的错误。

Full console log

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    当您的机器人收到消息类型的事件时,它会调用您的回调,并且在您的回调中您只会收到message,所以command 当然是未定义的。通过一些例子,我认为应该是这样的:

    const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();
    

    Here 是完整的例子,我建议检查一下。

    【讨论】:

    • 虽然这确实解决了问题,但不幸的是,它带来了一个新问题。我将您建议的代码 sn-p 粘贴在我的其他常量下(将消息更改为 spamMessage)。我现在收到的错误是:const args = SpamMessage.content.slice(config.prefix.length).trim().split(/ +/g); ^ TypeError: Cannot read property 'slice' of undefined at Object.<anonymous>
    • 这个错误意味着你的SpamMessage.content返回undefined,调试它看看它返回什么。在进行切片并尝试一次完成所有操作之前,尝试接收任何消息,然后尝试发送随机消息,然后从那里继续,一步一步地进行,而不是在第一次游泳时跳到深水区,希望对您有所帮助!
    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 2020-08-30
    • 2014-03-03
    • 2021-03-29
    • 2018-12-26
    • 2020-06-14
    • 2019-02-08
    • 2015-11-19
    相关资源
    最近更新 更多