Discord.py正在为“say”命令发送附件

2024-06-09 21:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的机器人有一个“say”命令,它重复用户在命令消息中写的内容:

  @commands.command(name = "say",
                    aliases = ['s'],
                    brief = "Repeats <message>",
                    help = "Repeats <message> passed in after the command."
                    )
  @commands.cooldown(1, cmd_cd, commands.BucketType.user)
  async def say(self, ctx, *, message):
      if ctx.message.attachments:
          await ctx.send(content=message, files=ctx.message.attachments)
      await ctx.send(message)

我希望它也包括附件,如果用户包括任何,但我似乎无法让它工作。我不断得到错误:

Command raised an exception: InvalidArgument: files parameter must be a list of File

我做错了什么?在discord.py docs中,它表示ctx.message.attachments属性返回一个列表,那么为什么我会得到这个错误呢? 我只是希望它发送附件的方式与用户发送附件的方式完全相同。不使用嵌入就可以做到这一点吗


Tags: 用户命令sendmessage附件错误方式files
2条回答

错误告诉您,它需要类型为FileList变量,但是attachments检索类型为attachment的列表

如果您检查文档中的attachment,可以看到它可以使用to_file()方法轻松地转换为File

因此,要使函数正常工作,您需要向files传递一个包含以下文件的新列表:

async def say(self, ctx, *, message):
  if ctx.message.attachments:
     new_list = list(map(lambda x:x.to_file(), ctx.message.attachments))
     await ctx.send(content=message, files=new_list)
  await ctx.send(message)

感谢@Shunya的帮助。在尝试他们的方法时,我发现了一种更简单的方法:

async def say(self, ctx, *, message):
  if ctx.message.attachments:
     await ctx.send(content=message, files=[await f.to_file() for f in ctx.message.attachments])
  await ctx.send(message)

相关问题 更多 >