【问题标题】:Discord.py bot take file as argument to commandDiscord.py bot 将文件作为命令的参数
【发布时间】:2023-03-29 14:47:01
【问题描述】:

我需要通过将文件附加到命令文本来将文件作为不和谐机器人命令的参数。我该怎么做?我目前有此代码,但该文件未作为参数提取:

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

为什么文件没有作为参数传递?

而且,更重要的是,我怎样才能做到这一点?

具体错误如下:

Ignoring exception in command upload_file:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 721, in invoke
    await self.prepare(ctx)
  File "/usr/local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 685, in prepare
    await self._parse_arguments(ctx)
  File "/usr/local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 599, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/usr/local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 445, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: file is a required argument that is missing.
`

【问题讨论】:

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


【解决方案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 机器人上传到 discord 的服务器)。 url 参数将使您能够下载所述文件的内容并执行您想要对其进行的任何处理。所以这里有一些伪代码应该可以使用 requests 模块下载附件(同样,这都是粗略地浏览一下文档):

@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,并且一些其他信息会与消息一起发送到您的命令机器人(以及其他任何收听的人)。要获取实际的文件数据,您必须从该 url 下载文件。从那里,你可以用它做任何你想做的事情。请注意,请求库是第 3 方,但比对 http 的内置支持要好得多(imo)。我还建议您在命令中添加一些极端情况处理,以确保实际上存在处理附件等。

【讨论】:

    【解决方案2】:

    如果您需要在本地处理文件,有一个非常简单的方法: 在Context: Message 对象有一个名为attachments 的属性。 discord.Attachment(https://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment)列表

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

    它有一个save 函数,接受io.BufferedIOBaseos.PathLike (https://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment.save)

    并且已经根据传输的对象将文件保存在本地 然后你可以用它做任何你想做的事

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2019-07-23
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2020-09-24
      • 2020-09-12
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多