Discord.js not sending random responces

Viewed 49

I've been working on a discord js bot. For some reason when my bot uses random responses like this, the application does not and does respond randomly.

I even tried having an array for responses but discord js gave me a hassle about that as well.

On top of this, for whatever reason, when I tried removing the catches next to the replies (the promise version) it would not work, and when it does the catch always fires.

8ball file:

const { SlashCommandBuilder } = require('discord.js');
const { logging } = require('../index')

module.exports = {
    data: new SlashCommandBuilder()
        .setName('8ball')
        .setDescription('Ask me a question')
        .addStringOption(opt => opt.setName('question').setDescription('question you have for meh').setRequired(true)),
    
    async execute(interaction) {
        logging.info(`Log:8ball command was called printing a random message`);
        let randomnumber = Math.floor(Math.random() * 4);
        if(interaction.options.getString('question').includes('?') === true) {
            await interaction.reply({ content:'Sorry, but this command does not support question marks', ephemeral:true })
                .catch(logging.error(`Log:A error occurred while trying to send error message in 8ball`))
        
            return;
        }
        if (randomnumber === 1) {
            log.info(`Log:A response 0 was selected, printing response 0`);
            try {
                await interaction.reply('Q: ' + interaction.options.getString('question') + '\nA: yes, i suppose');

            }
            catch {
                await interaction.followUp('An error occurred while attempting to send the reply, please try again')
                    .catch(logging.error(`Log:A error occurred while trying to send error message `))
                    .then(logging.error( 'A error occurred while sending response 1, returning'))
                return;
            }
        }
        else if (randomnumber === 2) {
            log.info(`Log:A response 2 was selected, printing response 2`);

            try {
                await interaction.reply('Q: ' + interaction.options.getString('question') + '\nA: maybe, unsure how should I know.');
            }
            catch {
                await interaction.followUp('An error occurred while attempting to send the reply, please try again')
                    .catch(logging.error(`Log:A error occurred while trying to send error message `))
                    .then(logging.error( 'A error occurred while sending response 2, returning'))
                return;
            }
        }
        else if (randomnumber === 3) {
            log.info(`Log:A response 3 was selected, printing response 3`);

            try {
                await interaction.reply('Q: ' + interaction.options.getString('question') + '\nA: definitely not, I am not sure why you would even ask');
            }
            catch {
                await interaction.followUp('An error occurred while attempting to send the reply, please try again')
                    .catch(logging.error(`Log:A error occurred while trying to send error message `))
                    .then(logging.error( 'A error occurred while sending response 3, returning'))
                return;
            }
        }
    },
}

The other part is a function that prints responses if production mode is off:

const logging = {
    info: function(msg) {
        if(process.env.NODE_ENV === "production") {
            return 0;
        }
        else {      
            log.info(msg);
        }
        return 0;
    },

    error: function(msg) {
        if(process.env.NODE_ENV === "production") {
            return 0;
        }
        else {
            log.error(msg);
        }
        return 0;
    }
}

I'm using nodeJS v16.17.0 discord.js v14 and Winston for logging

Edit:

I apologize for being very vague and for the large volume of code, the expected output of this function is supposed to do the following

  • loads the question from the getString() function
  • logs to a file (debug.log) that the command /8ball was called
  • generates a random number
  • replies with a response that changes based of the value of randomnumber
  • logs if an error occurred with replying to the user
  • logs that ccb replied successfully
  • returns

but what the files do is this (in worse cases)

  • logs that 8ball has been called
  • sends deferReply()
  • halts, does not write anything to debug.log, no error message, no success message, nothing, and stays on "CCB is thinking"

also: I am aware that there is no handler for randomnumber being 0, the reason for that is when I first created /8ball, the randomnumber variable never seemed to respond with 0 so I emitted it for performance

also keep in mind that each time production mode has not been on

thanks again in advance

3 Answers

Instead of using

let randomnumber = Math.floor(Math.random() * 4);

Why not use an array?

let randomNumber = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
let randomPercent = Math.floor(Math.random() * randomNumber.length);
let getRandomNumber = randomNumber[randomPercent];

Look at the snippet to know if this is you need.

let randomNumber = ["1", "2", "3", "4", "5", "6", "7", "8"];
let randomPercent = Math.floor(Math.random() * randomNumber.length);
let getRandomNumber = randomNumber[randomPercent];
console.log(getRandomNumber);

EDIT:

You're using if (randomnumber === 1) which is when you get a random number then the bot will response a random log. What'd you expect?

Don't use if else if else so many times! Use variables instead!

Try this code in the 'execute:'

async execute(interaction) {
    logging.info(`Log:8ball command was called printing a random message`);
    let responses = ['yes, i suppose', 'maybe, unsure how should I know.', 'definitely not, I am not sure why you would even ask']; // All responses are here
    let randomnumber = Math.floor(Math.random() * responses.length); // Outputs an array between 0 and responses.length -1
    let randomresponse = responses[randomnumber]; // Get the random response

    if (interaction.options.getString('question').includes('?') === true) {
        await interaction.reply({ content: 'Sorry, but this command does not support question marks', ephemeral: true })
            .catch(logging.error(`Log:A error occurred while trying to send error message in 8ball`))

        return;
    }

    log.info(`Log:A response ${randomnumber} was selected, printing response ${randomnumber}`);
    try {
        await interaction.reply('Q: ' + interaction.options.getString('question') + `\nA: ${randomresponse}`);

    }
    catch {
        await interaction.followUp('An error occurred while attempting to send the reply, please try again')
            .catch(logging.error(`Log:A error occurred while trying to send error message `))
            .then(logging.error(`A error occurred while sending response ${randomnumber}, returning`))
        return;
    }
}

Hope this helps ^-^

[+] : You can add infinite responses in the responses Array!

i appreciate all of your time even when now the fix seems so obvious

@Tachanks and @Kodeur_Kubic were correct,

I found the fix was to use arrays as @Kodeur_Kubic answered, and as @Tachanks suggested I forgot the handler for 0

so for others future reference here's the resulting code that was fixed

const { SlashCommandBuilder } = require('discord.js');
const { logging } = require('../index')

module.exports = {
    data: new SlashCommandBuilder()
        .setName('8ball')
        .setDescription('Ask me a question')
        .addStringOption(opt => 
            opt.setName('question')
            .setDescription('question you have for meh')
            .setRequired(true)),
    
    async execute(interaction) {

        //defines the invoker
        const invokerRaw = interaction.user.tag;

        //defines the invoker as a string
        const invoker = invokerRaw.toString();

        //defines the question as questionRaw
        const question = interaction.options.getString('question');

        //creates a array for responces
        const responce = ['yes, i suppose', 'maybe, idk how should i know?', 'defininately not, im not sure why you would even ask', 'ask me later, im busy!'];
        
        //logs to debug.log that the 8ball commands was called and to genorate a random message
        logging.info(`8ball command was called printing a random message`);

        //random number object
        let randomNumber = Math.floor(Math.random() * 4);

        //try to see if the question has a ? in it
        if(question.includes('?') === true) {

            //prints to the user that the question contained a question mark
            await interaction.reply({ content:'Sorry, but this command does not support question marks', ephemeral:true })
                .catch((err) => {

                    //logs the error to debug.log
                    logging.error(err);
                })
                .then(() => {

                    //logs to debug.log that we sent the error message
                    logging.info('Error message sent to ' + invoker);
                })

            //returns
            return 1;
        }

        await interaction.reply(`Q: ${question}\nA: ${responce[randomNumber]}`)
            .catch((err) => {

                //logs the error to debug.log
                logging.error(err.name);
            })
            .then(() => {

                //logs to debug.log that we sent the reply
                logging.info('sent reply successfully')
            })
    },
}
Related