如何从消息中获取图像并将其显示在embedded discord.py中

2024-04-23 09:50:52 发布

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

我正试图从消息中获取用户的图像,并将其显示在嵌入文件中,但由于某些原因,它无法工作
我对author/footer图标使用了相同的代码,它工作起来没有问题,我不明白为什么它不工作

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,我得到了url,所以我不知道为什么它不起作用(顺便说一句,缩略图也发生了同样的事情)


Tags: orinhttpsimageself消息urlmessage
1条回答
网友
1楼 · 发布于 2024-04-23 09:50:52

“分离函数”必须与检查邮件附件的位置在同一类中。我已经把这个“其他功能”作为一个命令来发送嵌入到通道,它工作得很好。这个班是一个不和谐的齿轮

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

因为“test”类是一个Cog,所以需要从主文件加载它

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

相关问题 更多 >