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

discord.py开发:如何获取Tenor分享链接GIF直链实现Embed嵌入

从Tenor分享链接获取GIF直链实现Discord Embed发送

你当前直接传入Tenor分享视图链接的写法无法生效,因为这类链接是网页展示链接,不是GIF资源直链,Discord无法直接解析网页内容加载图片,必须通过官方API获取.gif后缀的直链地址,稳定性和合规性都有保障。

前置准备

  • 申请Tenor免费API Key,个人非商用场景的配额完全可以满足普通Discord机器人的使用需求
  • 确保你的运行环境安装了requests库,用于发起API请求,安装命令为pip install requests

实现步骤

  • 正则匹配用户传入的Tenor分享链接,提取链接中携带的唯一GIF ID
  • 携带API Key和GIF ID调用Tenor官方GIF查询接口
  • 从接口返回的媒体格式列表中,选取合适尺寸的.gif直链
  • 将直链传入Embed的图片参数,完成消息发送

修改后的完整代码

import re
import requests
import discord

# 替换为你自己申请的Tenor API Key
TENOR_API_KEY = "YOUR_TENOR_API_KEY"

@client.command()
async def gifembed(ctx, link):
    # 校验Tenor链接格式,提取GIF ID
    id_match = re.match(r'^https?://tenor\.com/view/[a-zA-Z0-9\-_]+-(\d+)/?$', link.strip())
    if not id_match:
        await ctx.respond("传入的链接不是有效的Tenor分享链接", ephemeral=True)
        return
    gif_id = id_match.group(1)

    try:
        api_resp = requests.get(
            "https://tenor.googleapis.com/v2/gifs",
            params={
                "key": TENOR_API_KEY,
                "ids": gif_id,
                "media_filter": "gif"
            },
            timeout=10
        )
        api_resp.raise_for_status()
        result = api_resp.json()
        if not result.get("results"):
            await ctx.respond("未查询到对应GIF资源", ephemeral=True)
            return
        # 选取中等尺寸GIF,平衡清晰度和加载速度
        direct_gif_url = result["results"][0]["media_formats"]["mediumgif"]["url"]
    except Exception as e:
        await ctx.respond(f"GIF加载失败:{str(e)}", ephemeral=True)
        return

    embed = discord.Embed(title="Here's your embed", color=0xb0ff70)
    embed.set_image(url=direct_gif_url)
    await ctx.respond(embed=embed)

注意事项

不要使用爬取Tenor网页源码提取直链的方案,Tenor前端页面结构会不定期调整,这类方案极易失效,同时违反Tenor服务条款。官方API是唯一长期稳定的实现方案。
如果需要调整GIF尺寸,可以从接口返回的media_formats字段中选取其他格式,比如tinygif(小尺寸低清,加载快)、gif(原尺寸高清,体积大)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:24:13