Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - Sending random file with discord bot

Hello I have a question.

How can a discord bot send a file with random name. This file is in a specific directory and it's only 1 file.

What's the code that allow the bot know that is the file.

message.author.send("HTML:", {
    files: [{
        attachment: 'C:/Users/username/Downloads/specificFolder/fileisHere',
        name: 'filename.html'
    }]
})

how can this code change that the bot allow send randomly file

question from:https://stackoverflow.com/questions/65845500/sending-random-file-with-discord-bot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, prefix each file with a number, incrementing by 1 each time and starting at 0 e.g

0file.txt
1file.txt
2file.txt 
... etc

Then when you call the get random file function read each file in turn, and generate a random number from 0 to number of files you have - 1 and output the filename.

const fs = require('fs') //require fs to open files etc

//read files from the directory - I chose a directory called `dir001`
fs.readdir("./dir001", (err, files) => {
  if (err) {
    console.log(err);
  }

  let dirFiles = files.filter((f) => f.split(".").pop() === "txt"); // if the files end with txt - change for your needs

  if (dirFiles.length === 0) {
    console.log("No dir files found"); //if no files found return
    return;
  }

  let randInt = Math.floor(Math.random() * <number of files in the dir>); // generate random number from 0 to number of files in the dir

  dirFiles.forEach((f) => {
    if (!f.startsWith(randInt)) return; // if the file doesnt start with randInt(), return
    message.channel.send(`random file: ${f}`); // output the randomized file
  });
});

This should work, please let me know if you get errors, after making sure you changed everything to your individual needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...