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]
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]
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
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.
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.