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

折月煮酒 提交于 2019-12-02 11:34:31

问题


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 say messages at random times. I Frankensteined 2 pieces of code from various tutorials together and currently have this:

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

The problem is occurring in this block:

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

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

Every time I attempt to command the bot in my discord chat (!on) I get the error "TypeError: Cannot read property 'startsWith' of undefined" in Node.js/command prompt. I've tried various things to fix it (removing "content" from both msg.content... statements - no complaints but absolutely nothing happens) but... I honestly have no idea what I'm doing. I've checked every post on the internet that deals with similar things and nothing has been able to answer this. I'm hoping it's a simple syntax thing/something not declared properly... If you have some time and pity for me, please help. I know I've gotten myself into a mess but I refuse to abandon it!

Let me know what other information I can provide to help.


回答1:


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



回答2:


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


});


来源:https://stackoverflow.com/questions/53330771/javascript-typeerror-cannot-read-property-startswith-of-undefined-discord-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!