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

discord.py tasks.loop启动报错:no running event loop 问题咨询

解决discord.ext tasks启动时的RuntimeError:no running event loop问题

问题描述

我尝试使用discord.ext的tasks实现机器人每小时向指定频道发送消息,代码如下:

@tasks.loop(hours = 1)
async def remindstudy():
  await bot.wait_until_ready()
  channel = bot.get_channel(1038719402658517054)
  await channel.send("check")
remindstudy.start()

预期每小时发送"check"消息,但运行时抛出如下错误:

Traceback (most recent call last):
  File "main.py", line 137, in <module>
    remindstudy.start()
 File "/home/runner/main-bore-ho-raha-hoon/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 398, in start
    self._task = asyncio.create_task(self._loop(*args, **kwargs))
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/tasks.py", line 381, in create_task
    loop = events.get_running_loop()
RuntimeError: no running event loop

sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

该代码复制自我另一台仍正常运行的旧机器人,但当前机器人无法运行,请问问题出在哪里?

问题原因与解决办法

核心原因

你调用remindstudy.start()时,Discord机器人的事件循环还未启动。asyncio.create_task必须依赖一个已运行的事件循环,而当前代码在事件循环初始化前就触发了任务启动,直接导致RuntimeError: no running event loop错误。

旧机器人能正常运行,是因为它的remindstudy.start()调用位置正确——要么是在on_ready这类机器人事件内部,要么是在事件循环已经启动的时机执行,而当前代码把启动语句放在了事件循环未就绪的位置。

修复方案

将任务启动代码移至机器人的on_ready事件中,确保事件循环运行后再启动定时任务:

@tasks.loop(hours=1)
async def remindstudy():
    await bot.wait_until_ready()
    channel = bot.get_channel(1038719402658517054)
    await channel.send("check")

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")
    # 避免机器人重连时重复启动任务
    if not remindstudy.is_running():
        remindstudy.start()

# 最后启动机器人(这行必须放在代码末尾)
bot.run("你的机器人令牌")

额外注意事项

  • bot.run()会阻塞主线程,务必放在代码的最后一行,否则后续代码无法执行
  • 加入if not remindstudy.is_running()判断,防止机器人意外重连时重复启动任务,导致重复发送消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:05:47