首页 > 解决方案 > Randompuppys 不会在 discord.js 上从 reddit 上获取图像

问题描述

我正在尝试让 Discord.js 机器人从 Reddit 获取图像并将它们发布到频道中,但它一直说没有要发送的内容,我想知道是否有人能指出我做错了什么。

(我正在使用命令处理程序)

代码:

const randomPuppy = require('random-puppy');
const snekfetch = require('snekfetch');

module.exports = {
    name: "reddit",
    category: "info",
    description: "Sends subreddit images",
    run: async (client, Message, args, subreddit) => {
        let reddit = [
            "dankmemes",
            "meme"
          ]

          randomPuppy(subreddit).then(url => {
              snekfetch.get(url).then(async res => {
                  await Message.channel.send({
                      file: [{
                          attachment: res.body,
                          name: 'image.png'
                      }]
                  });
              }).catch(err => console.error(err));
          });
    }
}

标签: discorddiscord.js

解决方案


  • 当我尝试使用 random-puppy 从 r/dankmemes 获取图像时,其中很多是 GIF 或视频。确保您使用正确的扩展名并增加restRequestTimeout文件发送时间。
  • fileDiscord.js 中的属性在MessageOptionsv11 中被弃用,并在 v12 中被删除。你应该files改用。
  • snekfetch 已弃用,您应该改用node-fetch

使用它来初始化您的客户端,这会将超时设置为 1 分钟而不是默认的 15 秒:

const client = new Client({restRequestTimeout: 60000})

在您的命令文件中:

// returns .jpg, .png, .gif, .mp4 etc
// for more info see https://nodejs.org/api/path.html#path_path_extname_path
const {extname} = require('path')
const fetch = require('node-fetch')

/* ... */

// in your run function
// you can use thens if you want but I find this easier to read
try {
  const url = await randomPuppy(subreddit)
  const res = await fetch(url)
  await Message.channel.send({
    files: [{
      attachment: res.body,
      name: `image${extname(url)}`
    }]
  })
} catch (err) {
  console.error(err)
}

推荐阅读