如何让discord.py等待Socket通信以避免超时错误?
解决discord.py交互超时问题
你的问题核心是Discord要求交互必须在3秒内给出响应,而同步的Socket操作耗时过长导致超时。可以通过「先临时响应+后台处理+编辑响应」的方式解决,具体步骤和代码如下:
核心思路
- 立即发送临时响应,满足Discord的3秒响应要求
- 将耗时的同步Socket操作放到线程中执行,避免阻塞discord.py的事件循环
- 等Socket操作完成后,编辑之前的临时响应,返回最终结果
修改后的代码
import asyncio from discord import app_commands @app_commands.command(name="test", description="socket") async def bot_command(interaction, var: str): # 1. 先发送临时响应,避免超时 await interaction.response.send_message("正在处理请求,请稍候...") # 2. 将同步的socket操作放到线程中执行,不阻塞事件循环 msg = {"platform": "discord", "command": "test", "var": var} # 使用asyncio.to_thread运行同步函数(Python 3.9+支持) result = await asyncio.to_thread(sendsocket, msg) # 3. 编辑之前的响应,返回处理结果 await interaction.edit_original_response(content=result[:2000])
补充说明
- 如果你的Python版本低于3.9,可以用
ThreadPoolExecutor替代asyncio.to_thread:from concurrent.futures import ThreadPoolExecutor # 全局创建一个线程池,避免重复创建 executor = ThreadPoolExecutor(max_workers=4) # 在命令函数中替换这行: result = await interaction.client.loop.run_in_executor(executor, sendsocket, msg) - 绝对不要直接在交互响应的同步流程里做耗时操作,Discord的3秒超时限制是硬性要求,必须先响应再后台处理。
内容的提问来源于stack exchange,提问作者jonhkn
相关产品推荐
相关产品推荐

