discord.py中Giphy API响应慢/无响应 求aiohttp改写解决方案
问题原因
- 你当前使用的
giphy_client属于同步SDK,直接在异步的discord.py框架中调用会阻塞事件循环,闲置后Giphy服务端的旧连接过期,同步请求等待超时就会出现响应慢、无响应的故障 - 每次触发命令都重新初始化API实例,增加了不必要的连接开销
改造前置
先安装aiohttp依赖:
pip install aiohttp
完整改写代码
import discord from discord.ext import commands import aiohttp import random # 替换为你自己的Giphy API Key GIPHY_API_KEY = "Your Giphy API Key Here" # 全局复用aiohttp ClientSession,避免每次请求新建连接 client_session = None client = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # bot启动时初始化ClientSession @client.event async def on_ready(): global client_session client_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) print("Bot is ready") # bot关闭时销毁ClientSession,释放连接资源 @client.event async def close(): await client_session.close() await super().close() @client.command() async def gif(ctx, *, q = 'dance'): try: # 异步调用Giphy搜索接口 params = { "api_key": GIPHY_API_KEY, "q": q, "limit": 7, "rating": "r" } async with client_session.get("https://api.giphy.com/v1/gifs/search", params=params) as resp: if resp.status != 200: await ctx.send("请求Giphy接口失败,请稍后重试") return api_data = await resp.json() lst = api_data.get("data", []) if not lst: await ctx.send("未找到对应关键词的GIF") return giff = random.choice(lst) emb = discord.Embed(title = f"Requested by {ctx.author} {q}" ) emb.set_image(url= f'https://media.giphy.com/media/{giff["id"]}/giphy.gif') await ctx.send(embed = emb) except aiohttp.ClientError: await ctx.send("网络请求异常,请稍后重试") # 启动bot,替换为你自己的Bot Token client.run("Your Discord Bot Token Here")
优化说明
- 全程使用异步请求,不会阻塞discord.py的事件循环,闲置后连接过期也会自动重建,不会出现长时间无响应的问题
- 全局复用ClientSession,复用TCP连接,大幅降低请求开销
- 增加了10秒超时设置,避免请求无限等待
- 完善了异常处理逻辑,覆盖接口报错、无返回结果、网络异常等场景
内容的提问来源于stack exchange,提问作者IamNewbie
相关产品推荐
相关产品推荐

