0

So I have been trying to figure this out for a while now, but I haven't been able to get it to work. I'm trying to use a discord.js bot command to take a random line from a text file and send it on chat, but I haven't been able to figure it out. Also, would it be easier to use .JSON for this task? Thanks in advance. I tried this Grabbing a random line from file but it still wouldn't work

 if (msg.content === "give random data") {

        //print out a random line from a .txt file

    }
  • Use the 'fs' module of nodejs – RishiC Apr 26 '20 at 06:23
  • Assuming you used that code, I would output the lines variable so you can see that the file is read correctly, maybe also the first line of lines. so `console.log(lines);` and then `console.log(lines[0])` before you try to use lines to select the random line. – nycynik Apr 26 '20 at 07:44

2 Answers2

1

how did it not work? was there any error messages? json is easier but not by much, if its not a data structure i think you should use txt file.

you should read the file, cache it, and then when someone does that command just return lines[Math.floor(Math.random() * lines.length)];

0

If the JSON is in the JS file:

const data = `{
  "1": "hello world",
  "2": "cat dog",
  "3": "john smith"
}`;

client.on('message', msg => {

  if (msg.content === "give random data") {
    let obj = JSON.parse(data);
    let index = Math.floor(Math.random() * 3) + 1;
    let randomLine = obj[String(index)];
    msg.channel.send(randomLine);
  }

});