python - 如何从消息中获取图像并将其显示在嵌入的 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
并获得了网址,所以我不知道为什么它不起作用(顺便说一句,缩略图也发生了同样的事情)
解决方案
“单独的功能”必须与您检查邮件附件的地方属于同一类。我已经将此“其他功能”作为将嵌入发送到频道的命令,并且效果很好。班级是一个不和谐的齿轮。
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
推荐阅读
- python - for 循环使用上一项通过标准输入
- r - 如何在不重复 mutate 多次的情况下改变 dplyr 中的许多列?
- azure - 无法获取 Azure 负载均衡器池的 resourceId
- google-chrome - 如何让我的测试扩展在其他网站上运行?
- analytics - Rasa 的分析工具
- tensorflow - 如何获得“检测到”对象的概率值?
- javascript - 了解如何更改 Javascript 属性
- python - 将列表列转换为 2D numpy 数组
- dart - 滚动时 SliverAppBar 内容消失
- go - OAuth 2 和管理服务器端的多个用户访问令牌