Search code examples
javascriptnode.jsdiscorddiscord.jsbots

How to have a Discord bot repeat message?


I am new to discord.js and making a bot, and I want to make a simple magic 8-ball style command where you ask the bot a question and it responds with a random answer.

const commands = [
new SlashCommandBuilder().setName('ask').setDescription('Ask MUDBot a yes or no question')

I have this in my deploy-commands.js and

client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;

if (commandName === 'ping') {
    await interaction.reply('Pong!');
} else if (commandName === 'ask') {
    switch (getRandomInt(10)) {
        case 0:
            //interaction.reply(client.message.content);
            //interaction.reply('You asked, I reply: ')
            
            await interaction.reply('It is certain!');
            break;
        case 1:
            //interaction.reply('You asked, I reply: ')
            await interaction.reply('Without a doubt.');
            break;

etc in my bot.js.

currently the output doesn't repeat the question you asked so if you say: /ask are you a good bot?

the output is just:

... used /ask

MUDbot: (response)

How can I have the question you ask with the slash command be repeated by the bot? Thank you.


Solution

  • I am not seeing a way the user can actually ask the question itself, so a way of doing that is to add an option.

    const commands = [
    new SlashCommandBuilder().setName('ask').setDescription('Ask MUDBot a yes or no question').addStringOption(option =>
        option.setName('question')
            .setDescription('The question that you want answered')
            .setRequired(true));
    

    Then once you have the option on the slash command, get that when the command is ran and make a response string for it.

    if (commandName === 'ask') {
        const question = interaction.options.getString('question');
        let response = `You asked "${question}", `;
        switch (getRandomInt(10)) {
            case 0:
                response += 'It is certain!';
                break;
            case 1:
                response += 'Without a doubt.';
                break;
        }
        // continue with other statements and then after switch reply
        interaction.reply(response);
    }