Home > OS >  JavaScript Select random line from txt file
JavaScript Select random line from txt file

Time:06-18

I want to make a bot that sends random messages on commands

const { SlashCommandBuilder } = require(`@discordjs/builders`);
const fs = require("fs");
const readLine = require('readline');
var file = './texts/meow.txt';



module.exports = {
  
  data: new SlashCommandBuilder()
     .setName(`meow`)
     .setDescription(`meoww??`),
  async execute(interation) {
    interation.reply({
      content: `sussy cat`,
      emphemral: true });
  },  
};

But i dont know what i should write to line 15 i need help about it.

CodePudding user response:

Firsy you should open the file. To do this, you can

const fs = require('fs');

a = fs.readFileSync('your/file/directory/yourtextfile.txt') // reads the file  as a buffer
a = a.toString() // makes the buffer into a readable string
a = a.split('\n') // makes all the items in the list

And then you can get a random number from 1 to however many lines you have in your text file, and access it as a[random]

randomNum = Math.floor(Math.random() * the amount of lines)
a[randomNum] // gets you the random line!

for context, my text file is

a
b
c
d

CodePudding user response:

Mayhap something like this. It shuffles the lines and returns them in random order without a repeat (until the corpus is exhausted, at which point it shuffles again and repeats with a different random ordering.

const { readFile } = require("fs/promises");

async function getRandomLineGenerator(fn) {
  const lines = (await readFile(fn, 'utf8'))
    .split(/\n|\r\n?/)
    .map(s => s.trim())
    .filter(s => !!s);

  const n = lines.length;
  let i = n;

  if ( i < 1 ) throw new("empty file error");

  return () => {
    if (i >= n) {
      shuffle(lines);
      i = 0;
    }
    return lines[i  ];
  }
}

// Fisher-Yates shuffle
function shuffle(a) {
  for ( let i = a.length - 1; i >= 1; --i ) {
    const j = Math.floor( Math.random() * (i 1) );
    const temp = a[j];
    a[j] = a[i];
    a[i] = temp
  }
}

async function main() {
  const nextLine = await getRandomLineGenerator("some-corpus.txt");
  for (let i = 0 ; i < 100 ;   i ) {
    const randomLine = nextLine();
    console.log(randomLine)
  }
}

let cc;
main()
.then( () => cc = 0 )
.catch( e => {
  console.log("Error", e);
  cc = 1;
});
process.exit(cc);
  • Related