From bf2d2cbd03db07257a322abe6d2dc9f064d8f018 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Sat, 11 Apr 2026 21:11:03 +0800 Subject: [PATCH] Fix Telegram agent image download path --- app/modules/telegram/telegram.py | 21 +++++++++++++++++++-- tests/test_agent_image_support.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/app/modules/telegram/telegram.py b/app/modules/telegram/telegram.py index 1e1375cc..b21ee4c9 100644 --- a/app/modules/telegram/telegram.py +++ b/app/modules/telegram/telegram.py @@ -205,10 +205,27 @@ class Telegram: return None try: file_info = self._bot.get_file(file_id) - file_url = f"https://api.telegram.org/file/bot{self._telegram_token}/{file_info.file_path}" - resp = RequestUtils(timeout=30).get_res(file_url) + file_url = apihelper.FILE_URL.format( + self._telegram_token, file_info.file_path + ) + resp = RequestUtils( + proxies=apihelper.proxy, timeout=30 + ).get_res(file_url) if resp and resp.content: + logger.info( + "Telegram图片下载成功: file_id=%s, file_path=%s, content_bytes=%s", + file_id, + file_info.file_path, + len(resp.content), + ) return resp.content + logger.warn( + "Telegram图片下载失败: file_id=%s, file_path=%s, file_url=%s, proxy_enabled=%s", + file_id, + getattr(file_info, "file_path", None), + file_url, + bool(apihelper.proxy), + ) except Exception as e: logger.error(f"下载Telegram文件失败: {e}") return None diff --git a/tests/test_agent_image_support.py b/tests/test_agent_image_support.py index c1948cc6..389138c2 100644 --- a/tests/test_agent_image_support.py +++ b/tests/test_agent_image_support.py @@ -4,6 +4,8 @@ import unittest from types import SimpleNamespace from unittest.mock import Mock, patch +from telebot import apihelper + from app.agent.tools.impl.send_message import SendMessageInput from app.chain.message import MessageChain from app.core.config import settings @@ -73,6 +75,32 @@ class AgentImageSupportTest(unittest.TestCase): {"text": "hi", "photo": [{"file_id": "image-1"}]}, ) + def test_telegram_download_file_uses_configured_file_url(self): + telegram = Telegram.__new__(Telegram) + telegram._bot = Mock() + telegram._telegram_token = "token-123" + telegram._bot.get_file.return_value = SimpleNamespace(file_path="photos/a.jpg") + + old_file_url = apihelper.FILE_URL + old_proxy = apihelper.proxy + apihelper.FILE_URL = "https://tg-proxy.example/file/bot{0}/{1}" + apihelper.proxy = {"https": "http://127.0.0.1:7890"} + + try: + with patch( + "app.modules.telegram.telegram.RequestUtils.get_res", + return_value=SimpleNamespace(content=b"image-bytes"), + ) as get_res: + content = telegram.download_file("file-id-1") + finally: + apihelper.FILE_URL = old_file_url + apihelper.proxy = old_proxy + + self.assertEqual(content, b"image-bytes") + get_res.assert_called_once_with( + "https://tg-proxy.example/file/bottoken-123/photos/a.jpg" + ) + def test_process_allows_image_only_message(self): chain = MessageChain() message = CommingMessage(