首页 > 解决方案 > 如何从消息中获取图像并将其显示在嵌入的 discord.py 中

问题描述

我正在尝试从消息中获取用户的图像并将其显示在嵌入中,但由于某种原因它不起作用
我对作者/页脚图标使用相同的代码并且它没有问题,我不明白为什么这没有用

if len(message.attachments) > 0:
    attachment = message.attachments[0]
    if attachment.filename.endswith(".jpg") or attachment.filename.endswith(".jpeg") or attachment.filename.endswith(".png") or attachment.filename.endswith(".webp") or attachment.filename.endswith(".gif"):
        self.image = attachment.url
    elif "https://images-ext-1.discordapp.net" in message.content or "https://tenor.com/view/" in message.content:
        self.image = message.content

# In a separate function

e = discord.Embed()
e.set_image(url=self.image)

我尝试打印self.image并获得了网址,所以我不知道为什么它不起作用(顺便说一句,缩略图也发生了同样的事情)

标签: pythonpython-3.xdiscorddiscord.py

解决方案


“单独的功能”必须与您检查邮件附件的地方属于同一类。我已经将此“其他功能”作为将嵌入发送到频道的命令,并且效果很好。班级是一个不和谐的齿轮。

import discord
from discord.ext import commands

class test(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if len(message.attachments) > 0:
            attachment = message.attachments[0]
        else:
            return
        if attachment.filename.endswith(".jpg") or attachment.filename.endswith(".jpeg") or attachment.filename.endswith(".png") or attachment.filename.endswith(".webp") or attachment.filename.endswith(".gif"):
            self.image = attachment.url
        elif "https://images-ext-1.discordapp.net" in message.content or "https://tenor.com/view/" in message.content:
            self.image = message.content

    @commands.command(name="t")
    async def other_function(self, ctx):
        e = discord.Embed()
        e.set_image(url=self.image)
        await ctx.send(embed=e)

当然,您还需要具有设置功能。

def setup(bot):
    bot.add_cog(test(bot)) #Replace "test" with the name of your class

因为“测试”类是一个 Cog,所以您需要从主文件中加载它。

bot.load_extension('cog_file') #without the ".py" extension

推荐阅读