【问题标题】:"Cannot read property 'toLowerCase' of undefined" when coding a Discord bot编码 Discord 机器人时,“无法读取未定义的属性 'toLowerCase'”
【发布时间】:2020-07-20 14:39:11
【问题描述】:

我最近试图制作一个不和谐的机器人(使用节点),但我一直遇到“无法读取未定义的属性 'toLowerCase'”。我尝试将“toLowerCase”更改为“toUpperCase”,但没有解决问题。

client.on('ready', () => {
    console.log("The bot is online!");
    client.user.setActivity('Servers', { type: 'WATCHING' });


}); 

const isCommand = (message, cmdName) => message.content.toLowerCase().startsWith(PREFIX + cmdName);
const rollDice = () => Math.floor(Math.random() * 6) + 1;
client.on('message', function (message){
    if(message.author.bot) return;
     if(isCommand(message + "hello")) 
        message.reply(" Hi! I didn't want to make you feel lonely so I wanted to say hi.");
        if(isCommand(message , "rolldice")) {
            message.reply("You rolled a "+ rollDice());
   }




});

【问题讨论】:

  • 这个if(isCommand(message + "hello"))不应该是if(isCommand(message ,"hello"))

标签: javascript node.js discord.js


【解决方案1】:

您收到该错误是因为 message.content 未定义,undefined 上没有属性 toLowerCase。您需要检查 message 包含的内容,以及其中是否包含 content 属性。

正如@Aafaq 所说,它应该是if(isCommand(message ,"hello")) 否则你只是传递一个参数。

即便如此,您也需要在回调中 console.log 您的消息对象并查看它正在接收什么,然后访问适当的属性。

【讨论】:

  • 错误是因为if(isCommand(message + "hello"))这一行,因为这将连接消息对象中的“hello”字符串,即使message.content存在,message.content也会变得未定义。
【解决方案2】:

startcode 上面的一切都很好,可以通过以下方式修改:

//startcode
client.on('message', function (message){
const isCommand = (message, cmdName) => message.content.toLowerCase().startsWith(PREFIX + cmdName);
const rollDice = () => Math.floor(Math.random() * 6) + 1;
    if(message.author.bot) return;
     if(isCommand(message + "hello")) 
        message.reply(" Hi! I didn't want to make you feel lonely so I wanted to say hi.");
        if(isCommand(message , "rolldice")) {
            message.reply("You rolled a "+ rollDice());
   }

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 2021-11-28
    • 1970-01-01
    • 2020-07-23
    • 2020-06-24
    • 2018-10-23
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多