clkhlum02
clkhlum02

Reputation: 57

Discord bot with multiple messages when detected a word

I have a discord bot that is triggered when a word is said, I originally had it to say only one thing (original post is here for reference:Discord bot unintentionally spamming messages after user response) but I now want it to have multiple sayings so I used a switch statement with a random number generated by a random number generator function and it gets called in the switch statement for the message output. For some reason my code doesn't work and Im not sure why.

                let Discord;
                let Database;
                if(typeof window !== "undefined"){
                    Discord = DiscordJS;
                    Database = EasyDatabase;
                } else {
                    Discord = require("discord.js");
                    Database = require("easy-json-database");
                }
                const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
                const s4d = {
                    Discord,
                    client: null,
                    tokenInvalid: false,
                    reply: null,
                    joiningMember: null,
                    database: new Database("./db.json"),
                    checkMessageExists() {
                        if (!s4d.client) throw new Error('You cannot perform message operations without a Discord.js client')
                        if (!s4d.client.readyTimestamp) throw new Error('You cannot perform message operations while the bot is not connected to the Discord API')
                    }
                };
                s4d.client = new s4d.Discord.Client({
                    fetchAllMembers: true
                });
                s4d.client.on('raw', async (packet) => {
                    if(['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)){
                        const guild = s4d.client.guilds.cache.get(packet.d.guild_id);
                        if(!guild) return;
                        const member = guild.members.cache.get(packet.d.user_id) || guild.members.fetch(d.user_id).catch(() => {});
                        if(!member) return;
                        const channel = s4d.client.channels.cache.get(packet.d.channel_id);
                        if(!channel) return;
                        const message = channel.messages.cache.get(packet.d.message_id) || await channel.messages.fetch(packet.d.message_id).catch(() => {});
                        if(!message) return;
                        s4d.client.emit(packet.t, guild, channel, message, member, packet.d.emoji.name);
                    }
                });
                s4d.client.login('TOKEN').catch((e) => { s4d.tokenInvalid = true; s4d.tokenError = e; });


function GetRandomInteger(a, b){

    if (a > b){
        small = b;
        large = a;
    }
    else{
        small = a;
        large = b;
    }


s4d.client.on('message', async (s4dmessage) => {
    if (s4dmessage.author.bot) return;
  if (s4dmessage.content.includes('apples')) {
    switch(GetRandomInteger(1,5)){
        case 1: s4dmessage.channel.send(String('yum I love apples!')); break;
        case 2: s4dmessage.channel.send(String('apples are the best')); break;
        case 3: s4dmessage.channel.send(String('did someone say apples?')); break;
        case 4: s4dmessage.channel.send(String('apples are great!')); break;
        case 5: s4dmessage.channel.send(String('yum yum!')); break;
    }


  }


});

s4d;
        

Upvotes: 0

Views: 197

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23161

As Fabio mentioned, there is a missing curly bracket after your GetRandomInteger() function, but that function won't return anything.

Instead of generating a random integer and struggling with switch statements, you could simply store the responses in an array and pick one of them randomly.

Something like this should work, and is a lot less code:

s4d.client.on('message', async (s4dmessage) => {
  if (s4dmessage.author.bot) return;
  let responses = [
    'yum I love apples!',
    'apples are the best',
    'did someone say apples?',
    'apples are great!',
    'yum yum!',
  ];

  if (s4dmessage.content.includes('apples')) {
    s4dmessage.channel.send(getRandom(responses));
  }
});

function getRandom(arr) {
  let index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

You could even go one step further and add your array of responses to different fruits in an object, where the keys are the fruit names, and the values are the responses. This way you could check if the message contains a key, and send a random response from the array where the key is the fruit name found.

If you want to add a new fruit, you can simply add it to your responses object, and if you want to add/remove/update a response, you can edit the corresponding array.

Check out the example below:

s4d.client.on('message', async (s4dmessage) => {
  if (s4dmessage.author.bot) return;
  let responses = {
    apples: [
      'yum I love apples!',
      'apples are the best',
      'did someone say apples?',
      'apples are great!',
      'yum yum!',
    ],
    kiwi: [
      '🥝🥝🥝 simply the best.. 🥝🥝🥝',
      'yummmy',
      'kiwi, kiwi, get in my belly',
      'am I the only one who loves kiwi?'
    ],
    oranges: [
      'yum I love oranges!',
      'I love eating oranges!',
      'did someone mention oranges?',
      '🍊🍊🍊 love them',
      'yummmm!',
    ],
  };

  // check if the message contains any of the keys of responses
  // returns the key if found, undefined otherwise
  let firstKeyword = Object.keys(responses).find((str) =>
    s4dmessage.content.includes(str),
  );

  if (firstKeyword) {
    s4dmessage.channel.send(getRandom(responses[firstKeyword]));
  } else {
    // message contains no apples, kiwi, or oranges
  }
});

function getRandom(arr) {
  let index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

enter image description here

Upvotes: 2

Related Questions