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.