fix(send_message): route standalone Telegram sends through TELEGRAM_PROXY

When the send_message tool runs outside the gateway process (agent loop,
TUI, cron, etc.), _gateway_runner_ref() returns None and the standalone
path in _send_telegram constructs Bot(token=token) directly, bypassing
any configured proxy. In regions where api.telegram.org is blocked, the
send times out after ~5s with 'Telegram send failed: Timed out' and
nothing ever shows up in gateway.log because the request never reaches
the gateway.

Resolve TELEGRAM_PROXY (via gateway.platforms.base.resolve_proxy_url,
which also honours HTTPS_PROXY/HTTP_PROXY/ALL_PROXY and NO_PROXY) just
before constructing the Bot. When a proxy is found, attach an
HTTPXRequest(proxy=...) for both 'request' and 'get_updates_request',
matching what gateway/platforms/telegram.py already does for in-gateway
sends and what the Discord standalone sender already does. Any
exception attaching the proxy falls back cleanly to a direct connection,
preserving prior behaviour for users without a proxy configured.

Adds tests/tools/test_send_message_telegram_proxy.py covering both the
proxy-configured and no-proxy cases.
This commit is contained in:
pepelax 2026-05-14 04:34:44 +00:00 committed by Teknium
parent 785993bcae
commit edce8a5fd4
2 changed files with 178 additions and 1 deletions

View file

@ -816,7 +816,30 @@ async def _send_telegram(token, chat_id, message, media_files=None, thread_id=No
formatted = message
send_parse_mode = ParseMode.MARKDOWN_V2
bot = Bot(token=token)
# Honour a configured proxy (telegram.proxy_url in config.yaml, exported
# as TELEGRAM_PROXY env var by load_gateway_config). Without this, the
# standalone send path bypasses the proxy and times out in regions
# where api.telegram.org is blocked. The in-gateway adapter does the
# same thing in gateway/platforms/telegram.py.
try:
from gateway.platforms.base import resolve_proxy_url
_tg_proxy = resolve_proxy_url("TELEGRAM_PROXY", target_hosts=["api.telegram.org"])
except Exception:
_tg_proxy = None
if _tg_proxy:
try:
from telegram.request import HTTPXRequest
logger.info("send_message: standalone Telegram send routed through proxy %s", _tg_proxy)
bot = Bot(
token=token,
request=HTTPXRequest(proxy=_tg_proxy),
get_updates_request=HTTPXRequest(proxy=_tg_proxy),
)
except Exception as _proxy_err:
logger.warning("send_message: failed to attach Telegram proxy (%s), falling back to direct connection", _proxy_err)
bot = Bot(token=token)
else:
bot = Bot(token=token)
int_chat_id = int(chat_id)
media_files = media_files or []
thread_kwargs = {}