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

Discord Bot报错:Timeout context manager应在任务内使用

Discord.py中await调用报错的解决办法

我在使用discord.py开发时,调用await方法触发了报错,下面是相关代码以及最终找到的解决方法:

问题相关代码

1. 主线程启动线程(main.py)

#main.py
t = threading.Thread(target=examplefunction, args=(msgcontent,channel )) 
t.start()

该线程用于信息收集(仅展示关键代码)。

2. 子函数创建事件循环调用异步方法(examplefunction.py)

#examplefunction.py
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
    
loop.run_until_complete(examplefunction2(content))
loop.close()

3. 异步发送消息的函数(examplefunction2.py)

#examplefunction2.py
bot = discord.Client()

@bot.event
async def mcsending(content):
  channel = content
  print(channel)
  await channel.send('here')

执行到await channel.send('here')时触发报错。

解决步骤

只需要修改examplefunction.py中的代码,将原来的loop.run_until_complete(examplefunction2(content))替换为:

#examplefunction.py
bot.loop.create_task(examplefunction2(content))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:30:21