Ad

Having One Text.txt File And The Bot Chooses A Component Of It Randomly With Discord.js

- 1 answer

i want to make a joke bot. (just for some friends on my server). I dont want to use an api. But instead make a big text.txt file with the jokes in it. I managed to let the bot respond when I message: test. It responds with a "joke" from the txt file. It only haves one joke in it tough. Now I want to have more jokes in it. And let the bot randomly choose from one of the jokes. The thing is, I dont know how to make the jokes be seperated so the bot can actually choose randomly from it. Here is my code so far:

client.on("message", msg => {
  var textart = fs.readFileSync('./textart.txt', {"encoding": "utf-8"})
  if(msg.content === `test`) {
     msg.channel.send(textart)
  }
  
  
})

I also dont know how to make the bot choose randomly between those jokes too( I'm an beginner so I need some more help with coding) Is there someone thats able to help me out?

Ad

Answer

text txt

Joke 1
Joke 2
const jokes = textart.split(/\n/) // or "\n"
msg.channel.send(jokes[Math.floor(Math.random() * jokes length)])
Ad
source: stackoverflow.com
Ad