Search code examples
javascriptdiscorddiscord.jsbots

How can I setup my discord bot to respond to an array of messages?


(This is my first time using JavaScript). My current code does not return a response from my Bot. I would like for the Bot to be able to respond to an array of user-sent messages, so I created an array of potential inputs. I am struggling on knowing how to format the "if" statement. The image is what I currently have: Code snapshot

I have tried changing 'includes' to 'indexof' and to change userMsg from 'const' to 'var,' though I haven't fully understood java syntax. Basically, what ends up happening is the Bot either responds to all messages or no messages...

Sorry if this was asked poorly. I have searched through some other questions and tried what I could but so far it has not worked.

Thank you for the help ♥


Solution

  • Discord.js API changes often enough so this may not be valid, but you can try this means of responding to certain inputs.

    const { Client, Intents } = require('discord.js');
    const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
    
    // Your array of messages to respond to
    const messagesToRespond = ['hello', 'hi', 'hey'];
    
    client.once('ready', () => {
      console.log('Bot is ready!');
    });
    
    client.on('messageCreate', message => {
      // Check if the message content matches any message in the array
      if (messagesToRespond.includes(message.content.toLowerCase())) {
        // Send a response
        message.channel.send('Hello! I am your friendly bot.');
      }
    });
    
    // Replace 'YOUR_BOT_TOKEN' with your actual bot token
    client.login('YOUR_BOT_TOKEN');