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

Asyncio+python-telegram-bot无限线程循环问题求助

Python-telegram-bot后台任务发送消息时线程持续递增的问题解决

问题原因

你遇到的线程持续递增问题,核心在于手动创建并管理asyncio事件循环的方式违反了python-telegram-bot(v20+)的设计规范:

  • python-telegram-bot的Application类本身负责事件循环、异步任务调度以及内部资源(如HTTP客户端线程池)的管理,你手动创建asyncio.new_event_loop()并替换全局循环,会打乱它的内部资源回收机制。
  • 当send_message(触发HTTP请求)和asyncio.sleep结合时,ptb依赖的异步HTTP客户端(如httpx)会尝试创建线程处理连接池,但由于你的手动循环没有触发ptb的内部清理逻辑,这些线程无法被复用或回收,导致每次循环都新增线程。

解决方案

改用python-telegram-bot内置的任务管理和启动机制,让框架统一处理事件循环和资源:

修改后的代码示例:

import asyncio
import logging
import threading
from telegram.ext import Application

TELEGRAM_TOKEN = "bot_token_here"
TELEGRAM_CHAT_ID = "telegram_chat_id_here"

async def work(application):
    while True:
        logging.info(f"=== There are: {threading.active_count()} threads. 1 ===")
        await application.bot.send_message(chat_id=TELEGRAM_CHAT_ID, text="test")
        logging.info(f"=== There are: {threading.active_count()} threads. 2 ===")
        await asyncio.sleep(5)

        threads = threading.enumerate()
        for thread in threads:
            try:
                logging.info(f"Thread name: {thread.name} - alive: {thread.is_alive()} - daemon: {thread.daemon}")
            except Exception as e:
                logging.error(f"Error: {e}")

def main()->None:
    # 构建Application实例
    application = Application.builder().get_updates_http_version('1.1').http_version('1.1').token(TELEGRAM_TOKEN).build()
    
    # 用ptb内置方法添加后台任务,由框架统一调度
    application.create_task(work(application))
    
    # 启动机器人,ptb会自动管理事件循环和资源
    application.run_polling()

if __name__ == "__main__":
    # 配置日志输出
    logging.basicConfig(level=logging.INFO)
    main()

关键说明

  1. 放弃手动管理事件循环:使用application.run_polling()或application.run_webhook()启动机器人,ptb会自动创建和维护事件循环,确保内部资源(包括线程池)被正确复用和回收。
  2. 用create_task添加后台任务:这是ptb推荐的异步任务添加方式,框架会将任务纳入统一调度,避免资源泄露。
  3. 测试验证:修改后线程数量会稳定在固定值(取决于ptb内部线程池配置),不会再持续递增。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:45:08