Bot保存在Discord上的特定频道中发送的所有图像,gif或视频

时间:2019-04-28 02:06:23

标签: javascript node.js discord discord.js

我希望我的机器人在计算机上保存在特定频道中发送的所有图像,视频甚至gif。那有可能吗? 我知道可以通过fs目录制作这种东西,但是我不确定该代码看起来如何,你们可以帮我吗?

2 个答案:

答案 0 :(得分:0)

此代码必须为您提供帮助,

import shutil
from discord.ext import commands
import requests

TOKEN = ""
prefix = "?"
bot = commands.Bot(command_prefix=prefix)
bot.run(TOKEN)
@bot.event
async def on_message(message):
    print("The message's content was", message.content)
    url = message.attachments[0]['url']
    if url[0:26] == "https://cnd.discordapp.com":
        r = requests.get(url, stream=True)
        with open(String.join(uuid.uuid4(),".png"), 'wb') as out_file:
            shutil.copyfileobj(r.raw, out_file)

使用它并创建一个机器人并安装软件包请求discord.py来运行该机器人。

最后,将此机器人添加到您的频道并为其赋予机器人角色。

答案 1 :(得分:0)

要从消息中获取所有图像,GIF和视频,可以使用消息的.attachments属性。这将为您提供该消息中的所有文件(如果其中包含文件)。

使用此属性,您可以创建一个循环,在该循环中,每发送一封邮件,您就可以通过message.attachments集合进行操作。然后,如the documentation所述,您可以在每个附件上调用.url属性以获取从中下载文件的链接。

获得链接后,您可以按照this answer from a different question下载文件。这是从答案中复制的代码:

var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);  // close() is async, call cb after close completes.
    });
  }).on('error', function(err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
  });
};

这意味着您将必须使用Node.js模块fshttp。要使用该代码,可以像

这样调用download方法
download(<The file url to download>, <The file name you want to save it as>, <a callback function which can be called when an error occurs>);