A versatile Discord bot programmed to trigger various messages upon detecting specific keywords

I've been working on a Discord bot that triggers a response when a specific word is mentioned. Originally, I had it set up to say only one thing (you can check out the original post here), but now I want the bot to have multiple responses. To achieve this, I implemented a switch statement with a random number generator function that generates a number used in the switch statement for selecting the message output. However, my code doesn't seem to be working, and I'm unsure 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;
        

Answer β„–1

As mentioned previously by Fabio, there seems to be a missing curly bracket after the GetRandomInteger() function and that function does not return any value.

Rather than generating a random integer and dealing with switch statements, you could simplify the process by storing responses in an array and randomly selecting one of them.

The following code snippet should suffice and is much more concise:

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 can take it a step further by organizing your array of responses for different fruits within an object, where the keys represent the fruit names and the values correspond to the responses. This approach allows you to check for specific fruit names in the message content and send a randomized response linked to that fruit.

If you wish to introduce a new fruit, simply add it to your responses object. Additionally, you can edit the corresponding arrays to add, remove, or modify responses as needed.

Refer to 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!',
    ],
  };

  let firstKeyword = Object.keys(responses).find((str) =>
    s4dmessage.content.includes(str),
  );

  if (firstKeyword) {
    s4dmessage.channel.send(getRandom(responses[firstKeyword]));
  } else {
    // message contains no recognized fruits
  }
});

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

https://i.sstatic.net/nExTE.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scanner (IE5) impact on page load speeds

I have developed an MVC project which is designed as a single-page application (SPA) utilizing knockoutjs and sammy frameworks. The following script is placed in the head section of the page: <script> var startTime = (new Date()).getTime(); </ ...

Avoid retrieving data during the fetching process

I have been working on an application that utilizes Redux for state management. Furthermore, I have been using the native fetch method to fetch data. return fetch("https://dog.ceo/api/breeds/image/random").then(res => res.json()); Within my React co ...

Executing Array.prototype.filter() results in an empty array being returned

I have a list of jQuery elements that I collected using the .siblings() method, and now I am trying to filter them. Here is the HTML code: <div> <div> <label for="username">Username</label> <input class="form ...

The debounce function seems to be malfunctioning as I attempt to refine search results by typing in the input field

Currently, I am attempting to implement a filter for my search results using debounce lodash. Although the filtering functionality is working, the debounce feature seems to be malfunctioning. Whenever I input text into the search bar, an API call is trigge ...

What is the best way to convert a circular JSON object to a string

Is there a way to stringify a complex JSON object without encountering the "Converting circular structure to JSON" error? I also need its parser. I am facing issues every time I try to use JSON.stringify and encounter the "Converting circular structure to ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

The node.js fs module reports that the object does not support the appendFile method

I am currently developing a node js application for educational purposes, where each operation is being logged into a file named log.txt The logging module contains the following code: var fs = require('fs'); function write(data, filename) { ...

When using JavaScript's async await, a promise is being returned instead of the expected result

Can anyone help me understand why I am receiving Promise { <state>: "pending" } when I call GetProfile("username")? Any suggestions on what steps I should take? Here is the function I am referring to: const GetProfile = async ( ...

Font-awesome integration in Vue.js causing extremely slow hot reloading

Recently, I decided to embark on a fun project using Vue.js because working with this framework seemed enjoyable. To enhance my project, I chose to incorporate the https://github.com/FortAwesome/vue-fontawesome component. However, upon using it in one of m ...

The script I added is malfunctioning when I utilize laravel/ui

Recently, I started using a template from node js during a course. While reading various posts, I learned that bootstrap utilizes jquery. It dawned on me that the script placed in the head section was causing issues when inserting scripts in other views. ...

Storing intricate information in MongoDB

I've been exploring the JSON-BSON structures of MongoDB, but I'm struggling to understand how to insert documents into other documents and query them. Here's what I'm curious about - let's say someone wants to store an array of do ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

jQuery AJAX is seamlessly handling cross domain requests in Chrome and other browsers, however, it seems to be struggling in IE10 as it is not properly transmitting data. Additionally, in Internet

My web application requires sending data to an API hosted on a different domain. The API processes the received data and jQuery AJAX handles the response. This process works smoothly on Chrome and Firefox, but encounters issues on Internet Explorer. While ...

techniques for utilizing dynamic variables with the limitTo filter in AngularJS

<div class="container"> <div class="row" ng-repeat="cmts in courCmt.argument" ng-init="getUserInfo(cmts)"> <div class="col-sm-1 col-xs-2"> <div class="thumbnail"> &l ...

What is the best way to transform this string into a Luxon Datetime object using Typescript?

Here is a snippet of Javascript/Typescript code that I have for converting a string into a Luxon DateTime: import { DateTime } from 'luxon'; const x = '2023-10-27T01:00:57.830+00:00' const y = DateTime.fromFormat(x, 'yyyy-MM-dd ...

Unravel a Base64 encoded string with the power of CryptoJS

I am in the process of developing a basic webpage where the objective is to send an encrypted message to the server, which will then create a file with that content. Subsequently, a link is generated for the recipient to access the encrypted value by provi ...

Emphasize the importance of paying attention to read-only

Currently, I have a form containing three inputs. The last input has the property of being β€˜readonly’, as the user is supposed to fill it by clicking buttons (such as a virtual keyboard) rather than typing manually. Everything functions correctly in th ...

Navigating with Nokia Here maps: plotting a path using GPS coordinates

I am currently developing a GPS tracking system and my goal is to visually represent the device's locations as a route. The challenge I'm facing is that there is a REST API available for this purpose, but my client-side application relies on soc ...

What is the significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

Transmitting boolean values from a Python API request

Is it possible that the error in my script is due to the boolean value I am trying to send in an API put call using Requests in Python? Here is how my script looks: import requests data = { 'name': 'John', 'lastname': ...