【问题标题】:JavaScript TypeError: Cannot read property 'startsWith' of undefined - discord botJavaScript TypeError:无法读取未定义的属性“startsWith” - 不和谐机器人
【发布时间】:2019-04-19 05:22:20
【问题描述】:

我必须首先说我对 javascript 知之甚少(我在 Java 中练习过),只是想制作一个(有点)简单的 Discord 机器人,它会在随机时间说出消息。我将来自各种教程的 2 段代码弗兰肯斯坦放在一起,目前有这个:

var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
//random bot code
var randomMessage;
var randOn = false;
var responseArray = [ //add more messages here
  "Ayy, lmao!",
  "Say what?",
  "roflmaotntpmp"
];

var prefix = "!";
var timer = [5,10]; //set min and max in seconds for random messages


// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
    colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
   token: auth.token,
   autorun: true
});
bot.on('ready', function (evt) {
    logger.info('Connected');
    logger.info('Logged in as: ');
    logger.info(bot.username + ' - (' + bot.id + ')');
});


bot.on('message', (msg) => {

  if (msg.content.startsWith(prefix + "on")) {
        if (randOn) {
            msg.channel.sendMessage("Already running.");
        }
        else {
            msg.channel.sendMessage("Random message started.")
        randomMessage = setTimeout(function() {
                randMsg(msg.channel);
            }, 1000*timer[0]);
        }
  }
  else if (msg.content.startsWith(prefix + "off")) {
        if (randOn) {
            clearTimeout(randomMessage);
            msg.channel.sendMessage("Random message disabled.");
        }
        else {
            msg.channel.sendMessage("Not running.");
        }
  }


});



function randomIntFromInterval(min, max) {
  return Math.floor(Math.random()*(max-min+1)+min);
}

function randMsg(msgChan) {
    console.log("callback");
    var interval = 1000*randomIntFromInterval(timer[0],timer[1]);
  var rand = randomIntFromInterval(0,responseArray.length-1);
  if(responseArray[rand]) {
    msgChan.sendMessage(responseArray[rand]);
  }
    randomMessage = setTimeout(function() {
        randMsg(msgChan);
    }, interval);
}

此块出现问题:

 bot.on('message', (msg) => {

      if (msg.content.startsWith(prefix + "on")) {
            if (randOn) {
                msg.channel.sendMessage("Already running.");
            }

每次我尝试在我的不和谐聊天 (!on) 中命令机器人时,我都会在 Node.js/命令提示符中收到错误“TypeError: Cannot read property 'startsWith' of undefined”。我已经尝试了各种方法来修复它(从两个 msg.content... 语句中删除“内容” - 没有抱怨,但绝对没有任何反应)但是......老实说,我不知道我在做什么。我已经检查了互联网上所有涉及类似事情的帖子,但没有人能够回答这个问题。我希望这是一个简单的语法东西/没有正确声明的东西......如果你有时间同情我,请帮忙。我知道我把自己弄得一团糟,但我拒绝放弃它!

让我知道我可以提供哪些其他信息来提供帮助。

【问题讨论】:

  • 调用处理程序时msg的值是多少?你能console.log(msg)它并分享输出吗?
  • 不确定我是否做对了,但我放置了“console.log(msg);”就在包含 msg.content...等的 if 语句开始之前。当我运行机器人(node bot.js)并尝试在不和谐中使用命令时,它只是在抛出错误@shkaper之前在命令提示符中打印了我的不和谐名称
  • 放入一个console.dir(msg) 这将为您提供对象的爆炸转储,包括所有成员和方法。在行后插入: bot.on('message', (msg) => {

标签: javascript node.js bots discord.io


【解决方案1】:

您的问题是,您将discord.jsdiscord.io 混合在一起

discord.js 是面向对象的,而discord.io 不是,所以在discord.io 中,您的消息已经是一个字符串!

discord.io 消息事件示例。

bot.on('message', function(user, userID, channelID, message, event) {
    if (message === "ping") {
        bot.sendMessage({
            to: channelID,
            message: "pong"
        });
    }
});

【讨论】:

    【解决方案2】:

    如果msg 对象或其content 属性未定义,则可能会在其中插入if(!msg || !msg.content) return; 之类的东西以摆脱困境。

    bot.on('message', (msg) => {
    
      if(!msg || !msg.content) return;
    
      if (msg.content.startsWith(prefix + "on")) {
            if (randOn) {
                msg.channel.sendMessage("Already running.");
            }
            else {
                msg.channel.sendMessage("Random message started.")
            randomMessage = setTimeout(function() {
                    randMsg(msg.channel);
                }, 1000*timer[0]);
            }
      }
      else if (msg.content.startsWith(prefix + "off")) {
            if (randOn) {
                clearTimeout(randomMessage);
                msg.channel.sendMessage("Random message disabled.");
            }
            else {
                msg.channel.sendMessage("Not running.");
            }
      }
    
    
    });

    【讨论】:

    • 所以我这样做了,它停在“if(!msg || !msg.content) return;”处线。然后我将其中的每一个隔离开来看看哪个是问题(“如果(!msg)返回”,然后我做了msg.content),我的发现是msg.content似乎是问题,因为它只停在“如果(!msg.content) 返回”。理论上,我认为内容应该是不和谐用户的输入。从这里去哪里.....@Will
    • 好的,所以我打印了 msg.content,它确实显示为“未定义”。
    • 我试图查看Discord.Client 的文档,看起来您的代码遵循他们的示例。我不确定为什么在该事件触发时您得到的对象缺少 content 属性,但如果它丢失了,您可以忽略该事件。
    猜你喜欢
    • 2021-05-25
    • 2020-07-31
    • 2019-01-27
    • 1970-01-01
    • 2020-08-30
    • 2022-12-04
    • 2020-11-03
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多