如何让Discord机器人调用Tenor接口自动获取指定标签的GIF并输出
实现方案
方案说明
直接调用GIF平台的官方开放API实现自动拉取带cat标签的GIF,不需要手动维护链接列表,Tenor的免费API完全满足个人机器人的调用量级。
具体实现步骤
- 第一步:安装请求依赖,执行
pip install aiohttp(用异步请求库避免阻塞discord机器人的事件循环) - 第二步:申请Tenor开发者API密钥,将密钥存入运行环境的环境变量,命名为
TENOR_KEY - 第三步:修改原有代码,新增API拉取逻辑、本地资源池更新逻辑
修改后完整代码示例
import discord import os import random import aiohttp client = discord.Client() cat_pictures = ["cats", "cat"] # 原有链接作为备用池,API调用失败时使用 backup_cat_gifs = [ "https://tenor.com/view/dimden-cat-cute-cat-cute-potato-gif-20953746", "https://tenor.com/view/dimden-cute-cat-cute-cat-potato-gif-20953747", "https://tenor.com/view/cute-cat-cute-cat-dimden-gif-19689251", "https://tenor.com/view/dimden-cute-cat-cute-cat-potato-gif-21657791", "https://tenor.com/view/cats-kiss-gif-10385036", "https://tenor.com/view/cute-kitty-best-kitty-alex-cute-pp-kitty-omg-yay-cute-kitty-munchkin-kitten-gif-15917800", "https://tenor.com/view/cute-cat-oh-yeah-awesome-cats-amazing-gif-15805236", "https://tenor.com/view/cat-broken-cat-cat-drinking-cat-licking-cat-air-gif-20661740", "https://tenor.com/view/funny-animals-cute-chicken-cat-fight-dinner-time-gif-8953000"] cat_gif_pool = backup_cat_gifs.copy() TENOR_KEY = os.getenv('TENOR_KEY') TENOR_SEARCH_URL = "https://tenor.googleapis.com/v2/search" # 拉取cat标签GIF更新本地资源池 async def update_cat_gif_pool(limit=50): global cat_gif_pool if not TENOR_KEY: return params = { "q": "cat", "key": TENOR_KEY, "limit": limit, "media_filter": "gif", "random": "true" } try: async with aiohttp.ClientSession() as session: async with session.get(TENOR_SEARCH_URL, params=params) as resp: if resp.status == 200: data = await resp.json() new_gifs = [item['url'] for item in data['results']] # 合并新拉取的GIF和备用池,去重 cat_gif_pool = list(set(new_gifs + backup_cat_gifs)) except Exception as e: # 拉取失败不抛异常,继续用旧资源池 print(f"拉取GIF失败: {e}") @client.event async def on_ready(): print('We have logged in as catbot '.format(client)) # 启动时先拉取一次更新资源池 await update_cat_gif_pool() @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith ('!help'): await message.channel.send(''' I only have two commands right now which are !cat which posts an image of a cat. !cats which gives you a video/gif ''') if any(word in message.content for word in cat_pictures): # 每次调用有10%概率触发资源池更新,保证GIF不重复过时 if random.random() < 0.1: await update_cat_gif_pool() await message.channel.send(random.choice(cat_gif_pool)) # 保留你原有其他逻辑,注意补充cat_apology、cat_sad、cat_dog对应的变量定义 # if any(word in message.content for word in cat_apology): # await message.channel.send(random.choice(cat_sad)) # # if any(word in message.content for word in cat_dog): # await message.channel.send(random.choice(cat_dogs)) client.run(os.getenv('TOKEN'))
注意事项
- 原代码中
cat_apology、cat_sad、cat_dog三个变量没有定义,运行前需要补充对应内容,否则会触发变量未定义报错 - 保留原有手动添加的GIF作为备用池,API调用失败时不会影响机器人正常使用
- 启动时自动拉取一批GIF更新资源池,每次触发关键词有10%概率触发更新,既不会频繁调用API,也能保证GIF资源持续更新
- 自动对资源池去重,避免重复返回相同GIF
内容的提问来源于stack exchange,提问作者dddictionary
相关产品推荐
相关产品推荐

