discord.py 1.7.3:如何延长Discord服务器对机器人的响应等待时间?
在discord.py 1.7.3中解决Discord机器人“应用未响应”的问题
无法直接让Discord服务器延长等待时间
Discord平台对交互(如斜杠命令响应)有固定的超时限制(通常为3秒),超过这个时间就会触发“应用未响应”提示,这个限制是平台层面的,无法通过discord.py的设置修改。
解决方案:避免阻塞事件循环,异步处理数据库操作
当前代码中的同步数据库操作会阻塞discord.py的事件循环,导致无法及时响应Discord的交互请求。需要将同步的数据库操作放到后台线程执行,不占用事件循环的时间。
方法1:使用asyncio.to_thread(Python 3.9+适用)
将同步的数据库函数调用包装到线程中执行,不阻塞事件循环:
import asyncio # 在你的命令处理函数中 # 异步执行数据库操作 await asyncio.to_thread(server.register_user, author, nickname) await asyncio.to_thread(server.whitelist_add, nickname) # 构建并发送最终响应 embed = discord.Embed(color=0x0bd50b, title='Done!', description=f'Player **{nickname}** added in white list!') embed.set_thumbnail(url=ctx.author.avatar_url) embed.set_footer(text=f'profile of {author}', icon_url=icon) await ctx.respond(embed=embed, ephemeral=True)
方法2:先发送临时响应,再更新结果
如果数据库操作确实耗时较长,可以先给用户一个临时反馈,完成后再替换为最终结果:
# 先发送临时响应 temp_response = await ctx.respond("正在处理白名单添加请求,请稍候...", ephemeral=True) # 在后台线程执行数据库操作 await asyncio.to_thread(server.register_user, author, nickname) await asyncio.to_thread(server.whitelist_add, nickname) # 构建最终Embed embed = discord.Embed(color=0x0bd50b, title='Done!', description=f'Player **{nickname}** added in white list!') embed.set_thumbnail(url=ctx.author.avatar_url) embed.set_footer(text=f'profile of {author}', icon_url=icon) # 编辑临时响应为最终结果 await temp_response.edit(content=None, embed=embed)
方法3:使用ThreadPoolExecutor(兼容Python 3.8及以下)
如果你的Python版本低于3.9,可以用concurrent.futures.ThreadPoolExecutor来异步执行同步函数:
from concurrent.futures import ThreadPoolExecutor import asyncio # 创建线程池(可全局初始化一次) executor = ThreadPoolExecutor(max_workers=2) # 在命令处理函数中 loop = asyncio.get_event_loop() await loop.run_in_executor(executor, server.register_user, author, nickname) await loop.run_in_executor(executor, server.whitelist_add, nickname) # 后续构建响应同前
内容的提问来源于stack exchange,提问作者JustNimay
相关产品推荐
相关产品推荐

