You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用discord.py开发Discord机器人时缩略图无法显示的问题

Discord.py Embed缩略图无法显示的排查与解决

问题背景

使用discord.py开发Discord机器人时,遇到Embed缩略图无法正常显示的问题。代码逻辑无明显错误,缩略图URL有效且可直接访问,机器人也具备必要权限,但消息发送后缩略图始终不展示。

相关代码

embedMessage = discord.Embed(
    title=entry.title,
    description=entry.description,
    url=entry.link,
    color=self.color,
)

url_thumbnail = entry.links[1]["href"]
embedMessage.set_thumbnail(url=url_thumbnail)

# 日期格式转换
date_obj = datetime.strptime(
    entry.published, "%a, %d %b %Y %H:%M:%S %z"
)
date_format = date_obj.strftime("%a, %d %b %Y %H:%M")

embedMessage.set_footer(text=date_format)

await channel.send(
    content="🚀 New Post on PSTHC 📰", embed=embedMessage
)

已确认信息

  • 缩略图URL示例:https://www.staticbo.psthc.fr/wp-content/uploads/2023/11/Logo-PGW23.png(可正常访问)
  • Embed对象已正确设置缩略图URL
  • 机器人拥有「嵌入链接」「发送消息」等必要权限

可能原因及解决建议

1. Discord缓存限制

Discord会缓存图片资源,若该URL曾返回错误(如404、权限问题),可能被标记为无效,即使后续恢复正常也不会加载。

  • 解决方法:给URL添加随机参数绕过缓存:
    import random
    url_thumbnail = f"{entry.links[1]['href']}?v={random.randint(1, 10000)}"
    embedMessage.set_thumbnail(url=url_thumbnail)
    

2. 图片服务器CORS策略限制

部分服务器会设置跨域规则,拒绝Discord的爬虫请求访问图片。

  • 解决方法:
    1. 检查图片服务器响应头,确认是否包含Access-Control-Allow-Origin且允许Discord域名
    2. 下载图片后通过附件上传:
      import requests
      from io import BytesIO
      
      response = requests.get(url_thumbnail)
      image_data = BytesIO(response.content)
      file = discord.File(image_data, filename="thumbnail.png")
      embedMessage.set_thumbnail(url="attachment://thumbnail.png")
      await channel.send(content="🚀 New Post on PSTHC 📰", embed=embedMessage, file=file)
      

3. 图片格式/大小不符合要求

Discord对Embed缩略图有明确限制:

  • 格式仅支持JPG、PNG、WebP、GIF
  • 建议文件大小不超过256KB,过大图片可能被拒绝加载
  • 解决方法:检查图片格式与大小,必要时压缩后使用

4. discord.py版本兼容问题

旧版本discord.py可能存在Embed设置bug,或与Discord API新版本不兼容。

  • 解决方法:更新到最新稳定版本:
    pip install -U discord.py
    

5. 频道权限限制

即使机器人全局有权限,目标频道可能单独禁用了「嵌入链接」权限。

  • 解决方法:检查目标频道的权限设置,确保机器人在该频道拥有「嵌入链接」权限

内容的提问来源于stack exchange,提问作者Elie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:23:25