如何将URL图片上传至Discord用于Embed并解决链接过期问题
解决Discord Embed中Instagram图片链接过期的问题
核心思路是通过Discord Webhook的多部分表单请求上传图片,将图片托管到Discord服务器,然后在Embed中引用Discord托管的图片(而非直接用Instagram的临时链接),这样既不会显示为附件,也能避免链接过期。
具体实现步骤
- 用Instaloader下载目标Instagram帖子的图片到本地临时文件
- 构造包含Embed数据和图片文件的multipart/form-data请求
- 在Embed的
image.url字段中使用attachment://[文件名]格式引用上传的图片 - 发送请求到Discord Webhook URL
代码示例(Python)
import requests import os from instaloader import Instaloader, Post # 1. 获取并下载Instagram帖子图片 L = Instaloader() # 如需访问受限内容,可添加登录逻辑 # L.login("your_username", "your_password") # 通过短代码获取目标帖子 post_shortcode = "ABC123" post = Post.from_shortcode(L.context, post_shortcode) image_filename = f"ig_post_{post_shortcode}.jpg" # 下载图片到临时目录 L.download_post(post, target="temp", filename=image_filename) # 2. 构造Discord Webhook请求参数 webhook_url = "https://discord.com/api/webhooks/your_webhook_id/your_webhook_token" # 定义Embed结构,用attachment语法引用上传的图片 embed_data = { "embeds": [ { "title": post.title, "description": post.caption, "image": { "url": f"attachment://{image_filename}" }, "footer": { "text": f"Posted by @{post.owner_username}" } } ] } # 3. 准备多部分表单数据 files = { "file": open(f"temp/{image_filename}", "rb") } payload = {"payload_json": str(embed_data)} # 4. 发送请求 response = requests.post(webhook_url, data=payload, files=files) response.raise_for_status() # 清理临时文件 os.remove(f"temp/{image_filename}")
关键说明
- 必须使用
multipart/form-data格式发送请求,普通JSON请求无法上传文件 attachment://[文件名]是Discord Webhook的专属语法,会自动将上传的图片转换为永久有效的CDN链接- 上传的图片不会以独立附件形式展示,仅在Embed的指定位置显示
- 全程无需依赖Discord第三方库,仅用
requests和instaloader即可实现
内容的提问来源于stack exchange,提问作者Ryan Luu
相关产品推荐
相关产品推荐

