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

使用python-telegram-bot的run_polling()遇RuntimeError报错求助

解决PTB运行时"Cannot close a running event loop"错误

这个错误大多出现在Jupyter Notebook/IPython这类自带异步事件循环的环境中,run_polling()尝试创建或关闭循环时会和现有循环产生冲突,以下是几种可行的解决方式:

方法1:切换到普通Python脚本环境运行

将代码保存为.py文件,通过命令行直接执行:

python your_bot_script.py

避开Jupyter这类自带事件循环的运行环境。

方法2:适配Jupyter环境的事件循环

如果必须在Jupyter中运行,可修改代码复用现有循环:

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import asyncio

async def hello(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(f'Hello {update.effective_user.first_name}')

async def main():
    app = ApplicationBuilder().token("你的机器人Token").build()
    app.add_handler(CommandHandler("hello", hello))
    await app.run_polling()

# 适配Jupyter的事件循环逻辑
try:
    loop = asyncio.get_running_loop()
    if loop.is_running():
        loop.create_task(main())
except RuntimeError:
    asyncio.run(main())

方法3:手动控制事件循环

通过手动管理循环生命周期,避免run_polling()自动关闭循环:

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import asyncio

async def hello(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(f'Hello {update.effective_user.first_name}')

app = ApplicationBuilder().token("你的机器人Token").build()
app.add_handler(CommandHandler("hello", hello))

# 手动启动和停止轮询
loop = asyncio.get_event_loop()
loop.run_until_complete(app.initialize())
loop.run_until_complete(app.start())
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    loop.run_until_complete(app.stop())
    loop.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:54:24