blour
blour

Reputation: 5

Discord Random Image Bot spamming

I prepared an sending random images discord bot. bot works smoothly but instead of just sending an image, it randomly sends all images in the folder. I need your help.(12 images available, prefix: !! ) codes;

const Discord = require('discord.js');
const client = new Discord.Client();
const settings = require('./settings.json');

var prefix = settings.prefix;

client.on('ready', () => {
console.log(`${client.user.tag} ready!`);
});

client.on('message', msg => {
  if (msg.content.toLowerCase() === prefix + 'xgif' )
      number = 12;
      imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
      msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
});

client.login(TOKEN HERE)

Upvotes: 0

Views: 1478

Answers (1)

Tarazed
Tarazed

Reputation: 2665

You have numerous problems leading to this. First, your if statement isn't scoped properly. Your code is the functional equivalent of:

if (msg.content.toLowerCase() === prefix + 'xgif' ) {
    number = 12;
}
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})

So what is happening is number is not always set to 12, and the last two lines execute with every single message, including messages that come from the bot itself. You need to: 1. scope your if statement correctly. 2. ignore all bot message.

client.on('message', msg => {
    if(msg.author.bot) return; // Ignore bots!
    if (msg.content.toLowerCase() === prefix + 'xgif' ) {
        number = 12;
        imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
        msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
    } // End of if scope
}

Unlike Python, for one example, JavaScript and all other C-style syntax languages do not use white space to indicate scope. An if statement with no brackets only includes the next single statement in it's scope.

Upvotes: 1

Related Questions