add images support
This commit is contained in:
14 files changed
+2157
-51
No files matched your search
+145
-32
@@ -18,8 +18,10 @@ from aiogram.types import (
|
||||
Message,
|
||||
)
|
||||
|
||||
from homeagent.agent.attachments import Attachment, build_default_attachment_prompt
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.bot.mcp_handlers import MCPBotController
|
||||
from homeagent.bot.media import MediaGroupBuffer, extract_message_attachments, has_supported_media
|
||||
from homeagent.bot.progress import ProgressReporter
|
||||
from homeagent.bot.utils import split_message
|
||||
from homeagent.config import Settings
|
||||
@@ -57,6 +59,7 @@ def create_bot_router(
|
||||
"""Create and configure the main Aiogram Router."""
|
||||
router = Router(name="main_router")
|
||||
mcp_controller = MCPBotController(mcp_manager, _send_reply) if mcp_manager is not None else None
|
||||
media_group_buffer = MediaGroupBuffer()
|
||||
|
||||
@router.message(Command("start", "help"))
|
||||
async def handle_start(message: Message) -> None:
|
||||
@@ -89,7 +92,8 @@ def create_bot_router(
|
||||
f"• `/reset` — очистить контекст диалога в текущем топике\n"
|
||||
f"• `/help` — показать это сообщение\n\n"
|
||||
f"Просто напиши мне любой вопрос или команду, например:\n"
|
||||
f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_."
|
||||
f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_.\n"
|
||||
f"📎 Также можно присылать **фото, скриншоты, PDF, документы (DOCX/XLSX/PPTX), код, логи и аудио/голосовые** — с подписью или без."
|
||||
)
|
||||
await _send_reply(message, greeting)
|
||||
|
||||
@@ -196,37 +200,99 @@ def create_bot_router(
|
||||
if mcp_controller is not None and await mcp_controller.handle_wizard_message(message):
|
||||
return
|
||||
|
||||
text = message.text or message.caption or ""
|
||||
if not text.strip():
|
||||
grouped_messages = await media_group_buffer.collect(message)
|
||||
if grouped_messages is None:
|
||||
return
|
||||
|
||||
text_parts = [
|
||||
(m.text or m.caption or "").strip()
|
||||
for m in grouped_messages
|
||||
if (m.text or m.caption or "").strip()
|
||||
]
|
||||
text = "\n".join(text_parts)
|
||||
|
||||
reply_msg = message.reply_to_message
|
||||
has_msg_media = any(has_supported_media(m) for m in grouped_messages)
|
||||
has_reply_media = bool(reply_msg and has_supported_media(reply_msg))
|
||||
has_media = has_msg_media or has_reply_media
|
||||
|
||||
if not text and not has_media:
|
||||
return
|
||||
|
||||
chat_id = message.chat.id
|
||||
thread_id = message.message_thread_id
|
||||
active_bot = message.bot
|
||||
|
||||
# 1. Check if the message triggers a skill
|
||||
matched = skill_manager.match_trigger(text)
|
||||
if matched:
|
||||
skill, extra_args = matched
|
||||
prompt_to_run = skill.render(extra_instructions=extra_args)
|
||||
logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id)
|
||||
else:
|
||||
prompt_to_run = text
|
||||
max_size_bytes = max(1, int(settings.MAX_ATTACHMENT_SIZE_MB)) * 1024 * 1024
|
||||
max_count = max(1, int(settings.MAX_ATTACHMENTS_PER_MESSAGE))
|
||||
|
||||
# 2. Show typing indicator and dynamic progress message while agent is working
|
||||
# 1. Show typing indicator and dynamic progress message while downloading / thinking
|
||||
typing_task = asyncio.create_task(_keep_typing(message))
|
||||
progress = ProgressReporter(bot=message.bot, chat_id=chat_id, thread_id=thread_id)
|
||||
await progress.start("⏳ Думаю...")
|
||||
progress = ProgressReporter(bot=active_bot, chat_id=chat_id, thread_id=thread_id) if active_bot else None
|
||||
if progress is not None:
|
||||
await progress.start("📥 Загружаю вложения..." if has_media else "⏳ Думаю...")
|
||||
|
||||
attachments: list[Attachment] = []
|
||||
warnings: list[str] = []
|
||||
try:
|
||||
response_text = await agent.chat(
|
||||
chat_id=chat_id,
|
||||
thread_id=thread_id,
|
||||
user_message=prompt_to_run,
|
||||
on_progress=progress.update,
|
||||
)
|
||||
if has_msg_media and active_bot is not None:
|
||||
msg_atts, msg_warns = await extract_message_attachments(
|
||||
active_bot,
|
||||
grouped_messages,
|
||||
max_size_bytes=max_size_bytes,
|
||||
max_count=max_count,
|
||||
source="message",
|
||||
)
|
||||
attachments.extend(msg_atts)
|
||||
warnings.extend(msg_warns)
|
||||
|
||||
if has_reply_media and reply_msg is not None and active_bot is not None and len(attachments) < max_count:
|
||||
reply_atts, reply_warns = await extract_message_attachments(
|
||||
active_bot,
|
||||
[reply_msg],
|
||||
max_size_bytes=max_size_bytes,
|
||||
max_count=max_count - len(attachments),
|
||||
source="reply",
|
||||
)
|
||||
attachments.extend(reply_atts)
|
||||
warnings.extend(reply_warns)
|
||||
|
||||
if not text and not attachments:
|
||||
if warnings:
|
||||
warning_text = "\n".join(f"⚠️ {w}" for w in warnings)
|
||||
await _send_reply(message, warning_text)
|
||||
return
|
||||
|
||||
# 2. Check if the message triggers a skill
|
||||
matched = skill_manager.match_trigger(text) if text else None
|
||||
if matched:
|
||||
skill, extra_args = matched
|
||||
prompt_to_run = skill.render(extra_instructions=extra_args)
|
||||
logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id)
|
||||
elif text:
|
||||
prompt_to_run = text
|
||||
else:
|
||||
prompt_to_run = build_default_attachment_prompt(attachments)
|
||||
|
||||
if warnings:
|
||||
prompt_to_run += "\n\n[Предупреждения при загрузке вложений]:\n" + "\n".join(
|
||||
f"- {w}" for w in warnings
|
||||
)
|
||||
|
||||
chat_kwargs: dict[str, object] = {
|
||||
"chat_id": chat_id,
|
||||
"thread_id": thread_id,
|
||||
"user_message": prompt_to_run,
|
||||
"on_progress": progress.update if progress is not None else None,
|
||||
}
|
||||
if attachments:
|
||||
chat_kwargs["attachments"] = attachments
|
||||
|
||||
response_text = await agent.chat(**chat_kwargs) # type: ignore[arg-type]
|
||||
finally:
|
||||
typing_task.cancel()
|
||||
await progress.finish()
|
||||
if progress is not None:
|
||||
await progress.finish()
|
||||
|
||||
# 3. Split and send chunks strictly as Rich Messages (up to 32K chars)
|
||||
chunks = split_message(response_text)
|
||||
@@ -381,19 +447,54 @@ def create_bot_router(
|
||||
)
|
||||
return
|
||||
|
||||
# If empty text and no reply context
|
||||
if not cleaned_text and not reply_context:
|
||||
# Extract media/file attachments from the guest message and/or replied message
|
||||
attachments: list[Attachment] = []
|
||||
warnings: list[str] = []
|
||||
max_size_bytes = max(1, int(settings.MAX_ATTACHMENT_SIZE_MB)) * 1024 * 1024
|
||||
max_count = max(1, int(settings.MAX_ATTACHMENTS_PER_MESSAGE))
|
||||
|
||||
if has_supported_media(message):
|
||||
msg_atts, msg_warns = await extract_message_attachments(
|
||||
active_bot,
|
||||
[message],
|
||||
max_size_bytes=max_size_bytes,
|
||||
max_count=max_count,
|
||||
source="message",
|
||||
)
|
||||
attachments.extend(msg_atts)
|
||||
warnings.extend(msg_warns)
|
||||
|
||||
if (
|
||||
message.reply_to_message
|
||||
and has_supported_media(message.reply_to_message)
|
||||
and len(attachments) < max_count
|
||||
):
|
||||
reply_atts, reply_warns = await extract_message_attachments(
|
||||
active_bot,
|
||||
[message.reply_to_message],
|
||||
max_size_bytes=max_size_bytes,
|
||||
max_count=max_count - len(attachments),
|
||||
source="reply",
|
||||
)
|
||||
attachments.extend(reply_atts)
|
||||
warnings.extend(reply_warns)
|
||||
|
||||
# If empty text, no reply context, and no attachments
|
||||
if not cleaned_text and not reply_context and not attachments:
|
||||
if warnings:
|
||||
await _send_guest_reply(active_bot, guest_query_id, "\n".join(f"⚠️ {w}" for w in warnings))
|
||||
return
|
||||
bot_tag = f"@{bot_username}" if bot_username else "@bot"
|
||||
welcome_msg = (
|
||||
f"👋 **Привет! Я персональный AI-ассистент HomeAgent (Ghost Mode).**\n\n"
|
||||
f"Я отвечаю в чатах без необходимости добавления в участники.\n"
|
||||
f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение!"
|
||||
f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение, фото или файл!"
|
||||
)
|
||||
await _send_guest_reply(active_bot, guest_query_id, welcome_msg)
|
||||
return
|
||||
|
||||
# 2. Check if the message triggers a skill
|
||||
matched = skill_manager.match_trigger(cleaned_text)
|
||||
matched = skill_manager.match_trigger(cleaned_text) if cleaned_text else None
|
||||
if matched:
|
||||
skill, extra_args = matched
|
||||
prompt_to_run = skill.render(extra_instructions=extra_args)
|
||||
@@ -402,24 +503,36 @@ def create_bot_router(
|
||||
if reply_context:
|
||||
if cleaned_text:
|
||||
prompt_to_run = f"{reply_context}[Запрос/вопрос пользователя]:\n{cleaned_text}"
|
||||
elif attachments:
|
||||
prompt_to_run = f"{reply_context}{build_default_attachment_prompt(attachments)}"
|
||||
else:
|
||||
prompt_to_run = (
|
||||
f"{reply_context}\n"
|
||||
f"Пользователь упомянул тебя в ответ на это сообщение без дополнительного текста. "
|
||||
f"Пожалуйста, проанализируй это сообщение, объясни его суть или дай полезный ответ по контексту."
|
||||
)
|
||||
else:
|
||||
elif cleaned_text:
|
||||
prompt_to_run = cleaned_text
|
||||
else:
|
||||
prompt_to_run = build_default_attachment_prompt(attachments)
|
||||
|
||||
if warnings:
|
||||
prompt_to_run += "\n\n[Предупреждения при загрузке вложений]:\n" + "\n".join(
|
||||
f"- {w}" for w in warnings
|
||||
)
|
||||
|
||||
# 3. Process with AI agent
|
||||
typing_task = asyncio.create_task(_keep_typing(message))
|
||||
try:
|
||||
response_text = await agent.chat(
|
||||
chat_id=chat_id,
|
||||
thread_id=thread_id,
|
||||
user_message=prompt_to_run,
|
||||
on_progress=None,
|
||||
)
|
||||
guest_chat_kwargs: dict[str, object] = {
|
||||
"chat_id": chat_id,
|
||||
"thread_id": thread_id,
|
||||
"user_message": prompt_to_run,
|
||||
"on_progress": None,
|
||||
}
|
||||
if attachments:
|
||||
guest_chat_kwargs["attachments"] = attachments
|
||||
response_text = await agent.chat(**guest_chat_kwargs) # type: ignore[arg-type]
|
||||
finally:
|
||||
typing_task.cancel()
|
||||
|
||||
|
||||
@@ -1285,12 +1285,22 @@ class MCPBotController:
|
||||
val = None if rest.lower() in ("clear", "none", "off", "-") else rest
|
||||
saved = self.manager.set_default_client_metadata_url(val)
|
||||
if saved:
|
||||
await self.send_reply(
|
||||
message,
|
||||
f"✅ Сохранён OAuth Client ID Metadata URL:\n`{saved}`\n\n"
|
||||
"Теперь для всех MCP-серверов с CIMD (например Zenmoney) ссылка входа будет генерироваться автоматически!",
|
||||
None,
|
||||
)
|
||||
warnings = await self.manager.auth_manager.validate_cimd_url(saved)
|
||||
if warnings:
|
||||
warn_lines = "\n".join(f"⚠️ {w}" for w in warnings)
|
||||
await self.send_reply(
|
||||
message,
|
||||
f"💾 URL сохранён (`{saved}`), но найдены проблемы, из-за которых OAuth-сервер может вернуть `invalid_request`:\n\n"
|
||||
f"{warn_lines}",
|
||||
None,
|
||||
)
|
||||
else:
|
||||
await self.send_reply(
|
||||
message,
|
||||
f"✅ Проверен и сохранён OAuth Client ID Metadata URL:\n`{saved}`\n\n"
|
||||
"Теперь для всех MCP-серверов с CIMD (например Zenmoney) ссылка входа будет генерироваться автоматически!",
|
||||
None,
|
||||
)
|
||||
else:
|
||||
await self.send_reply(message, "🧹 OAuth Client ID Metadata URL очищен.", None)
|
||||
except ValueError as e:
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Telegram media and file extraction helpers, including album (media_group_id) batching."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
from aiogram import Bot
|
||||
from aiogram.types import Message
|
||||
|
||||
from homeagent.agent.attachments import Attachment, format_size, normalize_mime_type
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def has_supported_media(message: Message) -> bool:
|
||||
"""Return True if the Telegram message carries any downloadable image, file, or media."""
|
||||
return bool(
|
||||
message.photo
|
||||
or message.document
|
||||
or message.audio
|
||||
or message.voice
|
||||
or message.video
|
||||
or message.video_note
|
||||
or message.animation
|
||||
or message.sticker
|
||||
)
|
||||
|
||||
|
||||
async def _download_file_bytes(bot: Bot, file_id: str) -> bytes:
|
||||
"""Download a Telegram file by file_id into bytes."""
|
||||
buf = io.BytesIO()
|
||||
result = await bot.download(file_id, destination=buf)
|
||||
data = buf.getvalue()
|
||||
if data:
|
||||
return data
|
||||
if result is not None:
|
||||
if hasattr(result, "getvalue"):
|
||||
return result.getvalue()
|
||||
if hasattr(result, "read"):
|
||||
return result.read()
|
||||
return b""
|
||||
|
||||
|
||||
def _describe_media_item(message: Message) -> Optional[tuple[str, str, str, Optional[int], str]]:
|
||||
"""Inspect a Telegram message and return `(file_id, filename, mime_type, file_size, kind)` or None."""
|
||||
if message.photo:
|
||||
largest = message.photo[-1]
|
||||
uid = getattr(largest, "file_unique_id", None) or "img"
|
||||
return (largest.file_id, f"photo_{uid}.jpg", "image/jpeg", largest.file_size, "image")
|
||||
|
||||
if message.document:
|
||||
doc = message.document
|
||||
uid = getattr(doc, "file_unique_id", None) or "doc"
|
||||
filename = doc.file_name or f"document_{uid}"
|
||||
mime_type = doc.mime_type or "application/octet-stream"
|
||||
kind = "image" if mime_type.lower().startswith("image/") else "document"
|
||||
return (doc.file_id, filename, mime_type, doc.file_size, kind)
|
||||
|
||||
if message.voice:
|
||||
voice = message.voice
|
||||
uid = getattr(voice, "file_unique_id", None) or "voice"
|
||||
mime_type = voice.mime_type or "audio/ogg"
|
||||
return (voice.file_id, f"voice_{uid}.ogg", mime_type, voice.file_size, "voice")
|
||||
|
||||
if message.audio:
|
||||
audio = message.audio
|
||||
uid = getattr(audio, "file_unique_id", None) or "audio"
|
||||
filename = audio.file_name or f"audio_{uid}.mp3"
|
||||
mime_type = audio.mime_type or "audio/mpeg"
|
||||
return (audio.file_id, filename, mime_type, audio.file_size, "audio")
|
||||
|
||||
if message.video:
|
||||
video = message.video
|
||||
uid = getattr(video, "file_unique_id", None) or "video"
|
||||
filename = video.file_name or f"video_{uid}.mp4"
|
||||
mime_type = video.mime_type or "video/mp4"
|
||||
return (video.file_id, filename, mime_type, video.file_size, "video")
|
||||
|
||||
if message.video_note:
|
||||
vn = message.video_note
|
||||
uid = getattr(vn, "file_unique_id", None) or "vnote"
|
||||
return (vn.file_id, f"video_note_{uid}.mp4", "video/mp4", vn.file_size, "video")
|
||||
|
||||
if message.animation:
|
||||
anim = message.animation
|
||||
uid = getattr(anim, "file_unique_id", None) or "anim"
|
||||
filename = anim.file_name or f"animation_{uid}.mp4"
|
||||
mime_type = anim.mime_type or "video/mp4"
|
||||
return (anim.file_id, filename, mime_type, anim.file_size, "animation")
|
||||
|
||||
if message.sticker:
|
||||
sticker = message.sticker
|
||||
uid = getattr(sticker, "file_unique_id", None) or "sticker"
|
||||
if getattr(sticker, "is_animated", False):
|
||||
# Lottie .tgs sticker is gzipped JSON vector animation — skip cleanly via caller warning
|
||||
return (sticker.file_id, f"sticker_{uid}.tgs", "application/x-tgsticker", sticker.file_size, "sticker_animated")
|
||||
if getattr(sticker, "is_video", False):
|
||||
return (sticker.file_id, f"sticker_{uid}.webm", "video/webm", sticker.file_size, "sticker")
|
||||
return (sticker.file_id, f"sticker_{uid}.webp", "image/webp", sticker.file_size, "sticker")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def extract_message_attachments(
|
||||
bot: Optional[Bot],
|
||||
messages: list[Message],
|
||||
*,
|
||||
max_size_bytes: int = 20 * 1024 * 1024,
|
||||
max_count: int = 10,
|
||||
source: str = "message",
|
||||
) -> tuple[list[Attachment], list[str]]:
|
||||
"""Download supported attachments from one or more Telegram messages.
|
||||
|
||||
Returns `(attachments, warnings)`.
|
||||
"""
|
||||
attachments: list[Attachment] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
if bot is None:
|
||||
return attachments, warnings
|
||||
|
||||
for msg in messages:
|
||||
info = _describe_media_item(msg)
|
||||
if info is None:
|
||||
continue
|
||||
|
||||
file_id, filename, raw_mime, file_size, kind = info
|
||||
if kind == "sticker_animated":
|
||||
warnings.append("Анимированные стикеры (.tgs) не поддерживаются для анализа.")
|
||||
continue
|
||||
|
||||
if len(attachments) >= max_count:
|
||||
warnings.append(
|
||||
f"Достигнут лимит вложений ({max_count} файлов на сообщение): `{filename}` пропущен."
|
||||
)
|
||||
continue
|
||||
|
||||
if file_size is not None and file_size > max_size_bytes:
|
||||
warnings.append(
|
||||
f"Файл `{filename}` слишком большой ({format_size(file_size)}). "
|
||||
f"Максимальный размер — {format_size(max_size_bytes)}."
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
data = await _download_file_bytes(bot, file_id)
|
||||
except Exception as e:
|
||||
logger.warning("Failed downloading Telegram attachment '%s' (%s): %s", filename, file_id, e)
|
||||
err_msg = str(e)
|
||||
if "file is too big" in err_msg.lower():
|
||||
warnings.append(
|
||||
f"Файл `{filename}` превышает лимит Telegram Bot API (20 МБ) и не может быть скачан."
|
||||
)
|
||||
else:
|
||||
warnings.append(f"Не удалось скачать вложение `{filename}`: {err_msg}")
|
||||
continue
|
||||
|
||||
if not data:
|
||||
warnings.append(f"Вложение `{filename}` оказалось пустым (0 байт).")
|
||||
continue
|
||||
|
||||
if len(data) > max_size_bytes:
|
||||
warnings.append(
|
||||
f"Файл `{filename}` слишком большой ({format_size(len(data))}). "
|
||||
f"Максимальный размер — {format_size(max_size_bytes)}."
|
||||
)
|
||||
continue
|
||||
|
||||
normalized_mime = normalize_mime_type(filename, raw_mime, data=data)
|
||||
resolved_kind = "image" if normalized_mime.startswith("image/") and kind == "document" else kind
|
||||
attachments.append(
|
||||
Attachment(
|
||||
filename=filename,
|
||||
mime_type=normalized_mime,
|
||||
data=data,
|
||||
kind=resolved_kind,
|
||||
source=source,
|
||||
)
|
||||
)
|
||||
|
||||
return attachments, warnings
|
||||
|
||||
|
||||
@dataclass
|
||||
class _MediaGroupState:
|
||||
messages: list[Message] = field(default_factory=list)
|
||||
last_arrival: float = 0.0
|
||||
first_arrival: float = 0.0
|
||||
|
||||
|
||||
class MediaGroupBuffer:
|
||||
"""Debounces Telegram album updates sharing the same `media_group_id` into one batch."""
|
||||
|
||||
def __init__(self, delay_seconds: float = 0.6, max_wait_seconds: float = 2.5) -> None:
|
||||
self.delay_seconds = delay_seconds
|
||||
self.max_wait_seconds = max_wait_seconds
|
||||
self._groups: dict[tuple[int, Optional[int], str], _MediaGroupState] = {}
|
||||
|
||||
async def collect(self, message: Message) -> Optional[list[Message]]:
|
||||
"""Collect messages belonging to a media group.
|
||||
|
||||
- If `message.media_group_id` is None, returns `[message]` immediately.
|
||||
- For a media group, the first arriving coroutine waits until arrivals settle and
|
||||
returns all collected messages sorted by `message_id`. Subsequent arrivals in the
|
||||
same group append to the batch and return `None`.
|
||||
"""
|
||||
group_id = getattr(message, "media_group_id", None)
|
||||
if not group_id:
|
||||
return [message]
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
now = loop.time()
|
||||
key = (message.chat.id, message.message_thread_id, str(group_id))
|
||||
|
||||
existing = self._groups.get(key)
|
||||
if existing is not None:
|
||||
existing.messages.append(message)
|
||||
existing.last_arrival = now
|
||||
return None
|
||||
|
||||
state = _MediaGroupState(messages=[message], last_arrival=now, first_arrival=now)
|
||||
self._groups[key] = state
|
||||
|
||||
try:
|
||||
while True:
|
||||
now = loop.time()
|
||||
since_last = now - state.last_arrival
|
||||
since_first = now - state.first_arrival
|
||||
if since_last >= self.delay_seconds or since_first >= self.max_wait_seconds:
|
||||
break
|
||||
sleep_for = min(self.delay_seconds - since_last, self.max_wait_seconds - since_first)
|
||||
await asyncio.sleep(max(0.01, sleep_for))
|
||||
finally:
|
||||
self._groups.pop(key, None)
|
||||
|
||||
return sorted(state.messages, key=lambda m: m.message_id)
|
||||
@@ -43,6 +43,9 @@ def format_tool_progress(name: str, args: dict[str, Any]) -> str:
|
||||
if name == "sandbox_reset":
|
||||
return "🧹 Очищаю рабочую песочницу..."
|
||||
|
||||
if name == "inspect_attachment":
|
||||
return "📎 Изучаю прикреплённый файл..."
|
||||
|
||||
if name == "calendar_today_schedule":
|
||||
return "📅 Проверяю расписание на сегодня..."
|
||||
|
||||
|
||||
Reference in new issue
Block a user