【问题标题】:Is it possible to get the image attachment when a user reply to the bot's question and make the bot embed it当用户回复机器人的问题并让机器人嵌入时,是否可以获得图像附件
【发布时间】:2020-07-26 23:29:09
【问题描述】:

我正在发出一个命令,当有人键入 !1 时,机器人会发送一个 dm 并要求上传图片,然后机器人会嵌入该图片并将其发送到频道。

这是我目前的代码。

@commands.command(name='1')
async def qwe(self, ctx):
    question = '[Upload image]'
    dm = await ctx.author.create_dm()
    channel = self.client.get_channel()

    embed = discord.Embed(
        description=question,
        colour=0xD5A6BD
    )
    await dm.send(embed=embed)
    await self.client.wait_for('message', check=ctx.author)

    url = ctx.message.attachments
    embed = discord.Embed(
        description='image:',
        colour=0xD5A6BD
    )
    embed.set_image(url=url.url)
    await channel.send(embed=embed)

但是,当我使用上传图片回答机器人时出现此错误:

discord.ext.commands.errors.CommandInvokeError:
Command raised an exception: AttributeError: 'list' object has no attribute 'url'

【问题讨论】:

  • 您可以从您获取的附件列表中获取图片网址,url = url[0].url
  • 我试过了,但是 discord.ext.commands.errors.CommandInvokeError: Command 引发了异常:IndexError: list index out of range
  • 这是因为您要求ctx.message.attachments,这将是一个空列表。实际上,ctx.message 表示调用命令的消息。我添加了一些更改的答案。

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


【解决方案1】:

正如您在文档中看到的,Message.attachments 返回Attachments 的列表。然后,您需要在收到的消息附件列表的第一个元素上调用 url 方法,而不是 ctx.message(这是调用命令的消息)。

@commands.command(name='1')
async def qwe(self, ctx):
    question = '[Upload image]'

    # Sending embed
    embed = discord.Embed(description=question, colour=0xD5A6BD)
    await ctx.author.send(embed=embed)

    # Waiting for user input
    def check(message):
        return isinstance(message.channel, discord.DMChannel) and message.author == ctx.author
    message = await self.client.wait_for('message', check=check)

    # Sending image
    embed = discord.Embed(description='image:', colour=0xD5A6BD)
    attachments = message.attachments
    embed.set_image(url=attachments[0].url)

    await ctx.channel.send(embed=embed)

注意:您不需要调用create_dm 方法。

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2022-10-13
    • 2021-12-31
    • 2020-12-25
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多