简体   繁体   English

从文件夹 discord.js 获取随机图像

[英]Getting an random image from a folder discord.js

Hi I am trying to fetch a random image out of a folder and make the discord bot send it.嗨,我正在尝试从文件夹中获取随机图像并让 discord 机器人发送它。 When I type the command I get the following error: (node:15184) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'c:\Users\Charlie\Desktop\discordbot2\t.png'当我键入命令时,我收到以下错误: (node:15184) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'c:\Users\Charlie\Desktop\discordbot2\t.png'

Here is my code:这是我的代码:

var fs = require('fs');
client.on("message",message=>{
  if(message.content==('image')){
    console.log("image")
    var files = fs.readdirSync('folder')
    var chosenFile = files[Math.floor(Math.random() * files.length)] 
    console.log(chosenFile)
    message.channel.send(
      {
        files : [
          chosenFile
        ]
      }
    )
  }
})

The pathname you pass to message.channel.send() in the files option is just the file name.files选项中传递给message.channel.send()的路径名只是文件名。 It's supposed to be a path (relative to the current directory, or absolute), which is how it's interpreted.它应该是一个路径(相对于当前目录或绝对路径),这就是它的解释方式。 As the chosen file isn't in the current directory, it generates the ENOENT "no such file or directory" error.由于所选文件不在当前目录中,它会生成 ENOENT“没有这样的文件或目录”错误。

To make a relative path, you can use path.join , passing the both the path to the directory holding the file and the file name:要创建相对路径,您可以使用path.join ,同时传递保存文件的目录的路径和文件名:

const path = require('path');
...
    message.channel.send({files: [path.join('folder', chosenFile)] })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM