Skip to content

[Feature]为 Telegram 适配器添加独立代理支持,解决轮询超时和无法单独为tg机器人配置代理问题 #9343

Description

@joeyLin311

Description / 描述

问题描述

在 AstrBot v4.26.7 中配置 Telegram 机器人时,因网络环境无法直连 api.telegram.org,Telegram 适配器轮询持续报 TimedOut 错误,机器人无法启动。独立配置文件也不能给tg机器人单独配置http代理, 使用全局代理无法精细化控制会话http出站。

错误日志

[ERRO] Telegram polling crashed with exception: TimedOut: Timed out.
Traceback:
  httpx.ConnectTimeout → httpcore.ConnectTimeout
  → telegram.error.TimedOut

根因分析

  1. 全局代理影响所有适配器:在 core_lifecycle.py 中设置 http_proxy 环境变量会影响所有平台适配器(包括微信),但仅希望 Telegram 机器人走代理。
  2. Telegram 适配器无独立代理配置tg_adapter.py_build_application() 未对 python-telegram-botApplicationBuilder 传入代理参数。
  3. python-telegram-bot 轮询需要额外代理设置ApplicationBuilder.proxy() 仅覆盖常规 Bot API 请求,getUpdates 轮询需通过 .get_updates_proxy() 单独设置。

涉及文件

文件 改动类型
astrbot/core/platform/sources/telegram/tg_adapter.py 代码修改
astrbot/core/config/default.py 配置 Schema 注册
data/cmd_config.json 配置添加

修改详情

1. tg_adapter.py_build_application() 方法

改动前

def _build_application(self) -> None:
    self.application = (
        ApplicationBuilder()
        .token(self.config["telegram_token"])
        .base_url(self.base_url)
        .base_file_url(self.file_base_url)
        .build()
    )

改动后

def _build_application(self) -> None:
    builder = (
        ApplicationBuilder()
        .token(self.config["telegram_token"])
        .base_url(self.base_url)
        .base_file_url(self.file_base_url)
    )
    telegram_proxy = self.config.get("telegram_proxy", "")
    if telegram_proxy:
        builder = builder.proxy(telegram_proxy).get_updates_proxy(telegram_proxy)
        logger.info(f"Telegram adapter using proxy: {telegram_proxy}")
    self.application = builder.build()

2. default.py — 配置 Schema 注册

platformtelegram 适配器的字段定义中新增:

"telegram_proxy": {
    "description": "Telegram 专用代理",
    "type": "string",
    "hint": "仅 Telegram 适配器使用的代理地址,如 http://proxy-ip。留空则不使用代理。",
},

并在默认示例配置中添加:

"telegram_proxy": "",

3. cmd_config.json — 启用配置

在 Telegram 平台适配器配置中添加:

"telegram_proxy": "http://proxy-ip"

同时将全局 http_proxy 清空,避免影响其他适配器。

验证方法

  1. 检查进程 TCP 连接是否含有到代理 proxy-ip 的 established 连接
  2. 通过代理请求 Telegram getMe API 确认连通性
  3. 向 Telegram 机器人发送消息确认正常回复
  4. 确认 WebChat/微信等其他适配器不经过代理

Use Case / 使用场景

No response

Willing to Submit PR? / 是否愿意提交PR?

  • Yes, I am willing to submit a PR. / 是的,我愿意提交 PR。

Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:platformThe bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on.enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions