Fix Telegram agent image download path

This commit is contained in:
jxxghp
2026-04-11 21:11:03 +08:00
parent cb323653b8
commit bf2d2cbd03
2 changed files with 47 additions and 2 deletions

View File

@@ -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

View File

@@ -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(