Need Discord bot to respond with random messages upon command

Hey, that’s a very good question and it is very possible! The below example I created would take each reply from a text-file named replies.txt and put them into an array named replies.

// Include the file-system module
const fs = require("fs");

// Read the text file that contains all replies
let reply_data = fs.readFileSync("./replies.txt").toString();

// Take each reply in the text file and put them into an array
let replies = reply_data.split("\n");

// As an example, we will print each reply separately
replies.forEach((reply) => console.log(reply));

Hope this works for you!

Just a simple question. Would this code work with discord.js?

1 Like

@owenb8 Hey, welcome to the GitHub Support Community! This code was written for usage with discord.js so you should have no problems implementing it in your project!

use this command, it worked well for me

command(client, ‘command’, (message) => {

let replies = [“reply 1”, “reply 2”, “reply 3”];
let random = Math.floor(Math.random() * 3);

message.channel.send(replies[random])

});

I know someone already replied, but there’s a different way that may work better for you:

[all your const stuff]
const errorReplies = require(./randomMessages.json)
const randomError = errorReplies[Math.floor(Math.random() * errorReplies.length)];

...

    try {
         command.execute(message, args);
    } catch (error {
         console.error(error);
         message.channel.send(randomError);
}});

In randomMessages.json:

{"errorReplies": ["reply 1", "reply 2", "So on and so forth"]}

This example would be if you wanted to randomise error messages for a bot using dynamic commands, but it could be implemented in other scenarios.

Hey! I’m having a little trouble on this, when I put it into my commands folder, I get the error,

“ERROR: ENOENT: no such file or directory, open ‘./factsreplies.txt’”

But when I put the text into my node_modules folder (where my main.js is), it shows all the text in my console log (command prompt) and when I do activate the command, it works, but it just shows everything in it instead of one line at a time.

Question: how would I get it to only display certain lines, because I have in factsreplies.txt:

1 (line of facts)
2
3 (line of facts)
4
5 (line of facts)
6
7 (line of facts)

facts.js (command handler)

const Discord = require("discord.js");
const fs = require('fs');

let reply_data = fs.readFileSync("./factsreplies.txt").toString();
let replies = reply_data.split("\n");


module.exports = {
    name: 'facts',
    description: "Tells you facts about chickens!",
    execute(message, args){
            message.channel.send(replies);
            replies.forEach((reply) => console.log(reply));
    }
}

I just started coding around 3 weeks ago so i’m not the smartest when it comes to command handlers lol

1 Like

Hey, welcome to the GitHub Support Community. First off, I do not recommend leaving your main.js file in your node_modules folder; it is best to only leave it in your main project folder. The reason you’re receiving an error only when factsreplies.txt isn’t in your node_modules folder is because main.js is trying to include factsreplies.txt in the same folder it is in. For less issues, leave both main.js and factsreplies.txt in your main project folder for now.

The reason everything is showing at once instead of just a random line is because you’re logging each Array value in a forEach() loop instead of just one line. When you use the split() function in your code, it takes each piece of your factsreplies.txt file and adds it to an Array, each having their own index value to identify it later in code. To print out a single random fact from that list, use this:

const Discord = require("discord.js");
const fs = require('fs');

let reply_data = fs.readFileSync("./factsreplies.txt").toString();
let replies = reply_data.split("\n");


module.exports = {
    name: 'facts',
    description: "Tells you facts about chickens!",
    execute(message, args){
            let random = Math.floor(Math.random() * replies.length);
            message.channel.send(replies[random]);
    }
}

^ this should get a random index value between 0 the length of your Array and then use that index value to pick a fact from the list and send it as a message.

Hope this helps fix your issue! Please reply back if it doesn’t work as intended.

1 Like

Yep that fixed it. Thanks for your help!

Another quick question: is there a way to put it on a timer, so like it will change lines every 24 hours since I also have another command similar to that one and since it’s going to be on a 24/7 VPN soon and the command won’t work like before.

1 Like

May you go more in depth of what you want to achieve? Once I know more information I can come up with a solution.

Yeah, so far here’s the code for the command:

const Discord = require("discord.js");

let replies = ["Try to search the internet for the worlds smallest egg!", "Always love that chicken!", "Try going outside and finding at least 1 chicken. I know you can do this!"];
let random = Math.floor(Math.random() * 3);

module.exports = {
    name: 'Word of the Day',
    description: "Tells you a daily quote about chickens!",
    execute(message, args){
            message.channel.send(replies[random])
    }
}

Basically it will switch between differently lines of text randomly each day (24hr), but beforehand the bot would run on my PC, so I would usually turn it on and off manually, making it so everytime I boot up the bot, it will change replies automatically. I hope that didn’t go off track lol

Sorry about before, the code I pasted beforehand was from an older version of that command, but I just fixed it lol.

I am having problems with this code, it doesn’t want to randomize the replies, it just posts one reply, specifically the 2. one.

const Discord = require('discord.js');

const client = new Discord.Client();

const prefix = '-';

let replies = ["Catch-22: A soldier who wants to be declared insane to avoid combat is deemed not insane for that very reason and will therefore not be declared insane.", "Drinker paradox: In any pub there is a customer such that if that customer is drinking, everybody in the pub is drinking.", "Socratic paradox: All I know is that I know nothing."];

let random = Math.floor(Math.random() * 3);

client.once('ready', () => {
    console.log('Unit - 01 Is Online!');
});

client.on('message', message =>{
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        message.channel.send('bralau!');
    }
    
    if(command === 'help'){
        message.channel.send('help, awoglet, sd2d, ralsei, awospin, brazil, info, cursed');
    }

    if(command === 'awoglet'){
        message.channel.send('https://discord.gg/yhnUznj');
    }

    if(command === 'sd2d'){
        message.channel.send('https://discord.gg/aSaE7Xk');
    }

    if(command === 'ralsei'){
        message.channel.send('he is a fluffy boi');
    }

    if(command === 'awospin'){
        message.channel.send('https://www.youtube.com/watch?v=DtooCL1vYPQ&app=desktop');
    }

    if(command === 'brazil'){
        message.channel.send('YOU ARE GOING TO BRAZIL!');
    }

    if(command === 'info'){
        message.channel.send('Made by : Totiapproach#1366');
    }

    if(command === 'cursed'){
        message.channel.send('https://www.reddit.com/r/cursedimages/');
    }

    if(command === 'paradox'){
        message.channel.send(replies[random]);
    }

    


});
1 Like

Welcome to the GitHub Support Community! The reason you’re receiving the same reply each time is because your random variable is only randomizing on startup, not after each message. Also, I recommend changing your random variable to create a random number while also staying within the range of your reply count automatically. It would look something like this:

let replies = ["reply 1", "reply 2", "reply 3"];

client.on('message', (message) => {
    if (command === 'paradox') {
         // This will create a random number EACH time the command is ran, while also staying within the range of the reply count
         let random = Math.floor(Math.random() * replies.length);
         message.channel.send(replies[random]);
    }
}

Hope this helps!

How do I make it so that one reply has a greater chance of being chosen then other?

1 Like

Welcome to the GitHub Support Community! Check out this StackOverflow thread; should help understand probability in picking random array elements.

1 Like

thank you very much.

1 Like

With the second answer do I just have to type in ‘var chance’ and ‘var items’?