1

I want to get a random line from a file to my discord bot but i dont know how.

aleadry tried somethings from the website but doesn't help at all, none of them working.

Any help?

[js]

3 Answers3

0

You can use this method:

function getRandomLine(filename){
  fs.readFile(filename, function(err, data){
    if(err) throw err;
    var lines = data.split('\n');
    // this is random line
    const readedLine = lines[Math.floor(Math.random()*lines.length)];
    console.log(readedLine);
 })
}

For more information, you can read this: Grabbing a random line from file

Ramin Rezazadeh
  • 326
  • 1
  • 12
0

While the other solution works, you could use this code to just do it synchronously, making it a bit easier to work with:

function getRandomLine(filename){
   var data = fs.readFileSync(filename, "utf8");
   var lines = data.split('\n');
   return lines[Math.floor(Math.random()*lines.length)];
}
var the_random_line_text = getRandomLine('file.txt');
console.log(the_random_line_text);

Note: Becuse this is now blocking of the main thread if you are reading very large files be carful, it could cause problems. If you are indeed using a very large file I recomend loading it as an array when the program starts and just refrencing that array, not reading the file every time it is needed.

Strike Eagle
  • 852
  • 5
  • 19
0

I found an easier method.

fs = require('fs')
var data;
fs.readFile('filename.txt', 'utf8', function (err,rawData) {
  if (err) {
    return console.log(err);
  }
  data = rawData.split('\n');
});

function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

function getRandomLine(){
  return data[randomInt(0,data.length)];
}

And if your trying to send a message in a command.

message.channel.send(getRandomLine())

Put that in your command.

Change "filename.txt" to your name keep "utf8" the same.

NOTE: works for large files.

4b0
  • 21,981
  • 30
  • 95
  • 142