【问题标题】:Sending random file with discord bot使用不和谐机器人发送随机文件
【发布时间】:2021-04-26 22:34:18
【问题描述】:

您好,我有一个问题。

不和谐机器人如何发送具有随机名称的文件。此文件位于特定目录中,只有 1 个文件。

让机器人知道是文件的代码是什么。

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

此代码如何更改机器人允许随机发送文件

【问题讨论】:

标签: javascript discord.js


【解决方案1】:

首先,在每个文件前面加上一个数字,每次递增 1,从 0 开始,例如

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

然后在调用get random file函数时,依次读取每个文件,生成0number of files you have - 1的随机数并输出文件名。

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
  });
});

这应该可行,如果您遇到错误,请在确保根据您的个人需求更改所有内容后告诉我。

【讨论】:

  • 如果是这样怎么办:d28f69e7-3179-43e0-be82-fc45a2d534f2.html dir 文件夹仅包含 1 个文件,其中包含随机数和上述字母
  • 这不是你问的问题,请附加你的问题,因为我显然浪费了我的时间
猜你喜欢
  • 2018-08-05
  • 2020-08-25
  • 2021-04-28
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2021-04-03
  • 2021-02-12
相关资源
最近更新 更多