JavaScript TypeError: Cannot read property 'startsWith' of undefined - discord bot

后端 未结 2 1737
鱼传尺愫
鱼传尺愫 2021-01-27 00:18

I must start this question by saying that I have very little knowledge of javascript (I\'m practiced in Java) and just wanted to make a (somewhat) simple Discord bot that would

相关标签:
2条回答
  • 2021-01-27 00:36

    Your issue is, that you mix discord.js with discord.io

    discord.js is object oriented where discord.io is not, so in discord.io your message is already a string!

    Example discord.io message event.

    bot.on('message', function(user, userID, channelID, message, event) {
        if (message === "ping") {
            bot.sendMessage({
                to: channelID,
                message: "pong"
            });
        }
    });
    
    0 讨论(0)
  • 2021-01-27 00:49

    Maybe jam something like if(!msg || !msg.content) return; in there to bail out if the msg object or its content property is undefined.

    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.");
            }
      }
    
    
    });

    0 讨论(0)
提交回复
热议问题