Search code examples
javascriptnode.jsdiscorddiscord.js

Bot sends the same response always | Discord.js


I am trying to make a bot that responds randomly when somebody uses the command !say but I want to send some info the first time that somebody uses this command (and then, after the first time, send random messages).

For example:

  1. (first time) !say, response: info
  2. (second time) !say, response: random response
  3. (nth time) !say, response: random response

I tried to use new Map() so it can keep the ids that executed that command once and then if the map has the id of the message author then send random response.

But the problem is that the bot always responses with "info" and never with random response.

Here is my code

if (!mention) {
            message.channel.send("You need to tag someone")
        } else {

            if (map.has(message.author.id)) {
                if (mention.id == message.author.id) {
                    message.channel.send(random2)
                    //map.set(message.author.id)
                } else if (message.mentions.users.first().bot) {
                    message.channel.send(random3)
                    //map.set(message.author.id)
                } else {
                    message.channel.send(random)
                    //map.set(message.author.id)
                }
            } else {
                message.channel.send("info")
                map.set(message.author.id, Date.now())
                console.log(map)
            }

Solution

  • You need to define your map variable outside of the event handler so you don't need to create a new one on every incoming message. Please note though that it will still reset when you restart your bot.

    const map = new Map();
    
    client.on('message', async (message) => {
      if (message.author.bot) return;
    
      if (map.has(message.author.id)) {
        message.reply('you have already sent a message');
      } else {
        message.reply('you have not sent a message yet');
        map.set(message.author.id, Date.now());
      }
    });
    

    You could also simplify your if-else statements:

    const map = new Map();
    
    client.on('message', async (message) => {
      // ...
      // ...
      // ...
      if (!mention) {
        return message.channel.send('You need to tag someone');
      }
    
      if (!map.has(message.author.id)) {
        map.set(message.author.id, Date.now());
        return message.channel.send('info');
      }
    
      if (mention.id == message.author.id) {
        return message.channel.send(random2);
      }
    
      if (message.mentions.users.first().bot) {
        return message.channel.send(random3);
      }
    
      return message.channel.send(random);
    });