Discord.py bot将文件作为命令的参数

时间:2019-12-04 17:00:20

标签: python python-3.x discord discord.py discord.py-rewrite

我需要通过将文件附加到命令文本中来将文件作为不和谐bot命令的参数。我该怎么做?我目前有以下代码,但是未将文件作为参数:

#!/usr/bin/env Rscript

为什么文件不作为参数传递?

而且,更重要的是,我该怎么做呢?

确切的错误如下:

@bot.command()
async def upload_file(ctx, file:discord.File):
    f = file.fp
    txt = f.read().decode("utf-8")
    file.close()
    print(txt)

3 个答案:

答案 0 :(得分:1)

我已经阅读了一些不一致的py文档,并且我相信您会以错误的方式进行操作。命令参数只是通过它所看到的消息的纯文本上下文进行解析的,因此不会以这种方式获取在其上放置附件的信息,但是您仍然可以执行所需的操作,尽管可以采用其他方式。

键是命令(ctx)的上下文参数:https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context

查看文档,您将看到它具有Message:https://discordpy.readthedocs.io/en/latest/api.html#discord.Message实例,其中包含附件列表:https://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment

附件有一个url参数,用于存储将附件上载到discord的位置(这是为什么不能将文件作为参数,将附件独立于discord bot上载到discord的服务器的关键)。 url参数将使您能够下载所述文件的内容,并进行所需的任何处理。因此,这是一些可以使用请求模块下载附件的伪代码(同样,这完全是对文档的粗略浏览):

@bot.command()
async def upload_file(ctx):
    attachment_url = ctx.message.attachments[0].url
    file_request = requests.get(attachment_url)
    print(file_request.content)

回顾一下,当您将此命令和附件发送给您的机器人时,该附件将被上载到Discords服务器和一个URL,并且一些其他信息也随消息一起发送到您的命令bot(以及其他正在侦听的人)。要获取实际的文件数据,则必须从该URL下载文件。从那里,您可以随心所欲地做任何事情。请注意,请求库是第3方,但比对http的内置支持要好得多(imo)。我还建议您在命令中添加一些边缘情况处理,以确保实际上有要处理的附件等。

答案 1 :(得分:1)

如果您需要在本地使用文件,则有一种非常简单的方法: 在Context中: Message对象具有一个称为attachments的属性。 discord.Attachmenthttps://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment)的列表

我不知道为什么,但是它会一直列出一个对象

它具有save函数,可以接受io.BufferedIOBaseos.PathLikehttps://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment.save

并且已经取决于传输的对象将文件保存在本地 然后,您就可以随心所欲地

答案 2 :(得分:0)

使用此代码的时间:

@bot.command()
async def upload_file(ctx):
    attachment_url = ctx.message.attachments[0].url
    file_request = requests.get(attachment_url)
    print(file_request.content)

结果是

b"data in the file"

为什么会有“ b”?

相关问题