An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.
Python ai-agentsai-automationclaudeclaude-codeebbinghausknowledge-graphllmmemory-systemobsidianpersonal-assistantpkmproductivitypythonsecond-braintelegram-botvoice-assistant
feat: unified conversational chat handler (voice + text)
smixs061fb17b37f7
diff --git a/src/d_brain/bot/handlers/__init__.py b/src/d_brain/bot/handlers/__init__.pyindex c119f44..e96e10d 100644--- a/src/d_brain/bot/handlers/__init__.py+++ b/src/d_brain/bot/handlers/__init__.py@@ -2,20 +2,14 @@from d_brain.bot.handlers import (buttons,+ chat,commands,- forward,- photo,process,- text,- voice,)__all__ = ["buttons",+ "chat","commands",- "forward",- "photo","process",- "text",- "voice",]diff --git a/src/d_brain/bot/handlers/chat.py b/src/d_brain/bot/handlers/chat.pynew file mode 100644index 0000000..a040688--- /dev/null+++ b/src/d_brain/bot/handlers/chat.py@@ -0,0 +1,301 @@+"""Unified private chat handler with persistent Claude sessions.++Voice + text only (v3.0): replaces the legacy split handlers for private chats.+All messages are saved to daily (safety net) and routed through+ChatSessionManager for Claude to process and respond.+"""++import asyncio+import html+import logging+from dataclasses import dataclass, field+from datetime import datetime++from aiogram import Bot, F, Router+from aiogram.enums import ChatType+from aiogram.types import Message++from d_brain.bot.formatters import (+ sanitize_telegram_html,+ truncate_html,+ validate_telegram_html,+)+from d_brain.config import get_settings+from d_brain.services.chat_session import ChatSessionManager+from d_brain.services.session import SessionStore+from d_brain.services.storage import VaultStorage+from d_brain.services.transcription import DeepgramTranscriber++router = Router(name="chat")+logger = logging.getLogger(__name__)++# Only handle private chats — groups are handled by group.py+router.message.filter(F.chat.type == ChatType.PRIVATE)++DEBOUNCE_SECONDS = 5.0 # 5 sec debounce+MAX_RESPONSE_LENGTH = 4096+++@dataclass+class BufferedMessage:+ """Single message in the debounce buffer."""++ content: str+ msg_type: str+ timestamp: datetime+++@dataclass+class DebounceBuffer:+ """Per-chat debounce buffer."""++ messages: list[BufferedMessage] = field(default_factory=list)+ task: asyncio.Task[None] | None = None+ chat_id: int = 0+ user_id: int = 0+++# Module-level state+_buffers: dict[int, DebounceBuffer] = {}+_manager: ChatSessionManager | None = None+++def _get_manager() -> ChatSessionManager:+ """Lazy-init ChatSessionManager singleton."""+ global _manager # noqa: PLW0603+ if _manager is None:+ settings = get_settings()+ _manager = ChatSessionManager(settings.vault_path)+ return _manager+++def _get_buffer(chat_id: int, user_id: int) -> DebounceBuffer:+ """Get or create buffer for chat."""+ if chat_id not in _buffers:+ _buffers[chat_id] = DebounceBuffer(chat_id=chat_id, user_id=user_id)+ return _buffers[chat_id]+++def _add_to_buffer(+ chat_id: int, user_id: int, content: str, msg_type: str, bot: Bot+) -> None:+ """Add message to debounce buffer and reset timer."""+ buf = _get_buffer(chat_id, user_id)+ buf.messages.append(+ BufferedMessage(+ content=content,+ msg_type=msg_type,+ timestamp=datetime.now(),+ )+ )++ # Cancel existing debounce task+ if buf.task and not buf.task.done():+ buf.task.cancel()++ # Start new debounce task+ buf.task = asyncio.create_task(_debounce_flush(chat_id, bot))+++async def _debounce_flush(chat_id: int, bot: Bot) -> None:+ """Wait for debounce period, then flush buffer to Claude."""+ try:+ await asyncio.sleep(DEBOUNCE_SECONDS)+ except asyncio.CancelledError:+ return++ buf = _buffers.get(chat_id)+ if not buf or not buf.messages:+ return++ messages = buf.messages[:]+ buf.messages.clear()+ user_id = buf.user_id++ prompt = _build_prompt(messages)++ # Typing indicator loop+ typing_task = asyncio.create_task(_typing_loop(bot, chat_id))++ try:+ manager = _get_manager()+ response = await manager.send_message(user_id, prompt)++ if response:+ await _send_response(bot, chat_id, response)+ else:+ logger.warning("Empty response from Claude for user %d, retrying...", user_id)+ # Retry once before giving up — don't reset session on first empty+ response = await manager.send_message(user_id, prompt)+ if response:+ await _send_response(bot, chat_id, response)+ else:+ logger.warning("Empty response after retry for user %d", user_id)+ await bot.send_message(+ chat_id,+ "Claude не ответил дважды. Повтори сообщение.",+ )++ except Exception as e:+ logger.exception("Chat session error for user %d", user_id)+ error_text = f"Error: {html.escape(str(e)[:200])}"+ try:+ await bot.send_message(chat_id, error_text)+ except Exception:+ logger.exception("Failed to send error message")+ finally:+ typing_task.cancel()+++def _build_prompt(messages: list[BufferedMessage]) -> str:+ """Combine buffered messages into a single prompt."""+ if len(messages) == 1:+ msg = messages[0]+ if msg.msg_type == "text":+ return msg.content+ return f"[{msg.msg_type}] {msg.content}"++ parts = []+ for msg in messages:+ time_str = msg.timestamp.strftime("%H:%M")+ parts.append(f"[{time_str}] [{msg.msg_type}] {msg.content}")+ return "\n".join(parts)+++async def _typing_loop(bot: Bot, chat_id: int) -> None:+ """Send typing action every 4 seconds while processing."""+ try:+ while True:+ await bot.send_chat_action(chat_id, "typing")+ await asyncio.sleep(4)+ except asyncio.CancelledError:+ pass+++async def _send_response(bot: Bot, chat_id: int, text: str) -> None:+ """Send response, splitting if too long for Telegram."""+ sanitized = sanitize_telegram_html(text)+ if not validate_telegram_html(sanitized):+ sanitized = html.escape(text)++ if len(sanitized) <= MAX_RESPONSE_LENGTH:+ try:+ await bot.send_message(chat_id, sanitized)+ except Exception:+ # Fallback: send without HTML+ await bot.send_message(chat_id, sanitized, parse_mode=None)+ return++ # Split into chunks+ chunks = _split_text(sanitized, MAX_RESPONSE_LENGTH)+ for chunk in chunks:+ try:+ await bot.send_message(chat_id, chunk)+ except Exception:+ await bot.send_message(chat_id, chunk, parse_mode=None)+ await asyncio.sleep(0.3)+++def _split_text(text: str, max_len: int) -> list[str]:+ """Split text into chunks respecting Telegram limits."""+ if len(text) <= max_len:+ return [text]++ chunks = []+ remaining = text+ while remaining:+ if len(remaining) <= max_len:+ chunks.append(remaining)+ break+ chunk = truncate_html(remaining, max_len)+ chunks.append(chunk)+ # Move past what we consumed+ consumed = len(chunk.rstrip(".").rstrip())+ if consumed == 0:+ # Safety: force split to avoid infinite loop+ chunks[-1] = remaining[:max_len]+ remaining = remaining[max_len:]+ else:+ remaining = remaining[consumed:].lstrip()+ return chunks+++# --- Handlers ---++[email protected](F.voice)+async def handle_chat_voice(message: Message, bot: Bot) -> None:+ """Handle voice messages in private chat."""+ if not message.voice or not message.from_user:+ return++ settings = get_settings()+ storage = VaultStorage(settings.vault_path)+ transcriber = DeepgramTranscriber(settings.deepgram_api_key)++ try:+ file = await bot.get_file(message.voice.file_id)+ if not file.file_path:+ await message.answer("Failed to download voice")+ return++ file_bytes = await bot.download_file(file.file_path)+ if not file_bytes:+ await message.answer("Failed to download voice")+ return++ transcript = await transcriber.transcribe(file_bytes.read())+ if not transcript:+ await message.answer("Could not transcribe audio")+ return++ # Safety net: save to daily+ timestamp = datetime.fromtimestamp(message.date.timestamp())+ storage.append_to_daily(transcript, timestamp, "[voice]")++ # Log to session+ session = SessionStore(settings.vault_path)+ session.append(+ message.from_user.id,+ "voice",+ text=transcript,+ duration=message.voice.duration,+ msg_id=message.message_id,+ )++ # Add to debounce buffer+ _add_to_buffer(+ message.chat.id, message.from_user.id, transcript, "voice", bot+ )++ except Exception as e:+ logger.exception("Error processing voice in chat")+ await message.answer(f"Error: {e}")++[email protected](F.text, lambda m: not m.text.startswith("/"))+async def handle_chat_text(message: Message, bot: Bot) -> None:+ """Handle text messages in private chat (excluding commands)."""+ if not message.text or not message.from_user:+ return++ settings = get_settings()+ storage = VaultStorage(settings.vault_path)++ # Safety net: save to daily+ timestamp = datetime.fromtimestamp(message.date.timestamp())+ storage.append_to_daily(message.text, timestamp, "[text]")++ # Log to session+ session = SessionStore(settings.vault_path)+ session.append(+ message.from_user.id,+ "text",+ text=message.text,+ msg_id=message.message_id,+ )++ # Add to debounce buffer+ _add_to_buffer(+ message.chat.id, message.from_user.id, message.text, "text", bot+ )diff --git a/src/d_brain/bot/handlers/commands.py b/src/d_brain/bot/handlers/commands.pyindex 08a4c87..e9b34de 100644--- a/src/d_brain/bot/handlers/commands.py+++ b/src/d_brain/bot/handlers/commands.py@@ -1,4 +1,4 @@-"""Command handlers for /start, /help, /status."""+"""Command handlers for /start, /help, /status, /new, /compact."""from datetime import date@@ -8,6 +8,7 @@ from aiogram.types import Messagefrom d_brain.bot.keyboards import get_main_keyboardfrom d_brain.config import get_settings+from d_brain.services.chat_session import ChatSessionManagerfrom d_brain.services.session import SessionStorefrom d_brain.services.storage import VaultStorage@@ -18,17 +19,15 @@ router = Router(name="commands")async def cmd_start(message: Message) -> None:"""Handle /start command."""await message.answer(- "<b>d-brain</b> - твой голосовой дневник\n\n"- "Отправляй мне:\n"- "🎤 Голосовые сообщения\n"- "💬 Текст\n"- "📷 Фото\n"- "↩️ Пересланные сообщения\n\n"- "Всё будет сохранено и обработано.\n\n"+ "<b>d-brain</b> — персональный ассистент\n\n"+ "Просто пиши мне — я отвечу.\n"+ "Голосовые, текст, фото, пересланные — всё принимаю.\n\n""<b>Команды:</b>\n"- "/status - статус сегодняшнего дня\n"- "/process - обработать записи\n"- "/help - справка",+ "/new — новый чат\n"+ "/compact — сжать контекст\n"+ "/status — статус дня\n"+ "/process — обработать записи\n"+ "/help — справка",reply_markup=get_main_keyboard(),)@@ -37,16 +36,15 @@ async def cmd_start(message: Message) -> None:async def cmd_help(message: Message) -> None:"""Handle /help command."""await message.answer(- "<b>Как использовать d-brain:</b>\n\n"- "1. Отправь голосовое — я транскрибирую и сохраню\n"- "2. Отправь текст — сохраню как есть\n"- "3. Отправь фото — сохраню в attachments\n"- "4. Перешли сообщение — сохраню с источником\n\n"- "Вечером используй /process для обработки:\n"- "Мысли → Obsidian\n\n"+ "<b>d-brain — персональный ассистент</b>\n\n"+ "Просто отправляй что угодно — Claude обработает и ответит.\n\n"+ "🎤 Голосовое — транскрибирую и обработаю\n"+ "💬 Текст — обработаю как есть\n\n""<b>Команды:</b>\n"- "/status - сколько записей сегодня\n"- "/process - обработать записи"+ "/new — новый чат (сброс сессии)\n"+ "/compact — сжать контекст сессии\n"+ "/status — статус сегодняшнего дня\n"+ "/process — обработать записи дня")@@ -95,3 +93,36 @@ async def cmd_status(message: Message) -> None:f"- ↩️ Пересланных: {forward_count}"f"{week_stats}")++[email protected](Command("new"))+async def cmd_new(message: Message) -> None:+ """Start fresh Claude session."""+ if not message.from_user:+ return++ settings = get_settings()+ manager = ChatSessionManager(settings.vault_path)+ manager.reset(message.from_user.id)++ await message.answer("Новая сессия. Контекст очищен.")++[email protected](Command("compact"))+async def cmd_compact(message: Message) -> None:+ """Compact current session context."""+ if not message.from_user:+ return++ settings = get_settings()+ manager = ChatSessionManager(settings.vault_path)++ await message.chat.do(action="typing")+ summary = await manager.compact(message.from_user.id)++ if summary and len(summary) > 500:+ summary_text = summary[:500] + "..."+ else:+ summary_text = summary or "No summary."++ await message.answer(f"Контекст сжат.\n\n<i>{summary_text}</i>")diff --git a/src/d_brain/bot/handlers/forward.py b/src/d_brain/bot/handlers/forward.pydeleted file mode 100644index e9320a3..0000000--- a/src/d_brain/bot/handlers/forward.py+++ /dev/null@@ -1,58 +0,0 @@-"""Forwarded message handler."""--import logging-from datetime import datetime--from aiogram import Router-from aiogram.types import Message--from d_brain.config import get_settings-from d_brain.services.session import SessionStore-from d_brain.services.storage import VaultStorage--router = Router(name="forward")-logger = logging.getLogger(__name__)--[email protected](lambda m: m.forward_origin is not None)-async def handle_forward(message: Message) -> None:- """Handle forwarded messages."""- if not message.from_user:- return-- settings = get_settings()- storage = VaultStorage(settings.vault_path)-- # Determine source name- source_name = "Unknown"- origin = message.forward_origin-- if hasattr(origin, "sender_user") and origin.sender_user:- user = origin.sender_user- source_name = user.full_name- elif hasattr(origin, "sender_user_name") and origin.sender_user_name:- source_name = origin.sender_user_name- elif hasattr(origin, "chat") and origin.chat:- chat = origin.chat- source_name = f"@{chat.username}" if chat.username else chat.title or "Channel"- elif hasattr(origin, "sender_name") and origin.sender_name:- source_name = origin.sender_name-- content = message.text or message.caption or "[media]"- msg_type = f"[forward from: {source_name}]"-- timestamp = datetime.fromtimestamp(message.date.timestamp())- storage.append_to_daily(content, timestamp, msg_type)-- # Log to session- session = SessionStore(settings.vault_path)- session.append(- message.from_user.id,- "forward",- text=content,- source=source_name,- msg_id=message.message_id,- )-- await message.answer(f"✓ Сохранено (от {source_name})")- logger.info("Forwarded message saved from: %s", source_name)diff --git a/src/d_brain/bot/handlers/photo.py b/src/d_brain/bot/handlers/photo.pydeleted file mode 100644index 9d75c85..0000000--- a/src/d_brain/bot/handlers/photo.py+++ /dev/null@@ -1,78 +0,0 @@-"""Photo message handler."""--import logging-from datetime import datetime--from aiogram import Bot, Router-from aiogram.types import Message--from d_brain.config import get_settings-from d_brain.services.session import SessionStore-from d_brain.services.storage import VaultStorage--router = Router(name="photo")-logger = logging.getLogger(__name__)--[email protected](lambda m: m.photo is not None)-async def handle_photo(message: Message, bot: Bot) -> None:- """Handle photo messages."""- if not message.photo or not message.from_user:- return-- settings = get_settings()- storage = VaultStorage(settings.vault_path)-- # Get largest photo- photo = message.photo[-1]-- try:- file = await bot.get_file(photo.file_id)- if not file.file_path:- await message.answer("Failed to download photo")- return-- file_bytes = await bot.download_file(file.file_path)- if not file_bytes:- await message.answer("Failed to download photo")- return-- timestamp = datetime.fromtimestamp(message.date.timestamp())- photo_bytes = file_bytes.read()-- # Determine extension from file path- extension = "jpg"- if file.file_path and "." in file.file_path:- extension = file.file_path.rsplit(".", 1)[-1]-- # Save photo and get relative path- relative_path = storage.save_attachment(- photo_bytes,- timestamp.date(),- timestamp,- extension,- )-- # Create content with Obsidian embed- content = f"![[{relative_path}]]"- if message.caption:- content += f"\n\n{message.caption}"-- storage.append_to_daily(content, timestamp, "[photo]")-- # Log to session- session = SessionStore(settings.vault_path)- session.append(- message.from_user.id,- "photo",- path=relative_path,- caption=message.caption,- msg_id=message.message_id,- )-- await message.answer("📷 ✓ Сохранено")- logger.info("Photo saved: %s", relative_path)-- except Exception as e:- logger.exception("Error processing photo")- await message.answer(f"Error: {e}")diff --git a/src/d_brain/bot/handlers/text.py b/src/d_brain/bot/handlers/text.pydeleted file mode 100644index e0e7cb0..0000000--- a/src/d_brain/bot/handlers/text.py+++ /dev/null@@ -1,39 +0,0 @@-"""Text message handler."""--import logging-from datetime import datetime--from aiogram import Router-from aiogram.types import Message--from d_brain.config import get_settings-from d_brain.services.session import SessionStore-from d_brain.services.storage import VaultStorage--router = Router(name="text")-logger = logging.getLogger(__name__)--[email protected](lambda m: m.text is not None and not m.text.startswith("/"))-async def handle_text(message: Message) -> None:- """Handle text messages (excluding commands)."""- if not message.text or not message.from_user:- return-- settings = get_settings()- storage = VaultStorage(settings.vault_path)-- timestamp = datetime.fromtimestamp(message.date.timestamp())- storage.append_to_daily(message.text, timestamp, "[text]")-- # Log to session- session = SessionStore(settings.vault_path)- session.append(- message.from_user.id,- "text",- text=message.text,- msg_id=message.message_id,- )-- await message.answer("✓ Сохранено")- logger.info("Text message saved: %d chars", len(message.text))diff --git a/src/d_brain/bot/handlers/voice.py b/src/d_brain/bot/handlers/voice.pydeleted file mode 100644index 64cb972..0000000--- a/src/d_brain/bot/handlers/voice.py+++ /dev/null@@ -1,66 +0,0 @@-"""Voice message handler."""--import logging-from datetime import datetime--from aiogram import Bot, Router-from aiogram.types import Message--from d_brain.config import get_settings-from d_brain.services.session import SessionStore-from d_brain.services.storage import VaultStorage-from d_brain.services.transcription import DeepgramTranscriber--router = Router(name="voice")-logger = logging.getLogger(__name__)--[email protected](lambda m: m.voice is not None)-async def handle_voice(message: Message, bot: Bot) -> None:- """Handle voice messages."""- if not message.voice or not message.from_user:- return-- await message.chat.do(action="typing")-- settings = get_settings()- storage = VaultStorage(settings.vault_path)- transcriber = DeepgramTranscriber(settings.deepgram_api_key)-- try:- file = await bot.get_file(message.voice.file_id)- if not file.file_path:- await message.answer("Failed to download voice message")- return-- file_bytes = await bot.download_file(file.file_path)- if not file_bytes:- await message.answer("Failed to download voice message")- return-- audio_bytes = file_bytes.read()- transcript = await transcriber.transcribe(audio_bytes)-- if not transcript:- await message.answer("Could not transcribe audio")- return-- timestamp = datetime.fromtimestamp(message.date.timestamp())- storage.append_to_daily(transcript, timestamp, "[voice]")-- # Log to session- session = SessionStore(settings.vault_path)- session.append(- message.from_user.id,- "voice",- text=transcript,- duration=message.voice.duration,- msg_id=message.message_id,- )-- await message.answer(f"🎤 {transcript}\n\n✓ Сохранено")- logger.info("Voice message saved: %d chars", len(transcript))-- except Exception as e:- logger.exception("Error processing voice message")- await message.answer(f"Error: {e}")diff --git a/src/d_brain/bot/main.py b/src/d_brain/bot/main.pyindex c41c92e..09a1c98 100644--- a/src/d_brain/bot/main.py+++ b/src/d_brain/bot/main.py@@ -30,12 +30,9 @@ def create_dispatcher() -> Dispatcher:"""Create and configure the dispatcher with routers."""from d_brain.bot.handlers import (buttons,+ chat,commands,- forward,- photo,process,- text,- voice,)dp = Dispatcher(storage=MemoryStorage())@@ -44,10 +41,7 @@ def create_dispatcher() -> Dispatcher:dp.include_router(commands.router)dp.include_router(process.router)dp.include_router(buttons.router) # Reply keyboard buttons- dp.include_router(voice.router)- dp.include_router(photo.router)- dp.include_router(forward.router)- dp.include_router(text.router) # Must be last (catch-all for text)+ dp.include_router(chat.router) # Catch-all for private chat (LAST)return dpdiff --git a/src/d_brain/services/chat_session.py b/src/d_brain/services/chat_session.pyindex ed10397..26be1bf 100644--- a/src/d_brain/services/chat_session.py+++ b/src/d_brain/services/chat_session.py@@ -32,11 +32,9 @@ class ChatSessionManager:def __init__(self,vault_path: Path | str,- todoist_api_key: str = "",session: Any | None = None,) -> None:self.vault_path = Path(vault_path)- self.todoist_api_key = todoist_api_keyself._session = session if session is not None else get_session(get_settings())async def send_message(self, user_id: int, prompt: str) -> str:diff --git a/tests/test_chat_handler.py b/tests/test_chat_handler.pynew file mode 100644index 0000000..4f22ff1--- /dev/null+++ b/tests/test_chat_handler.py@@ -0,0 +1,31 @@+"""Tests for the unified chat handler."""++import asyncio+++def test_text_message_goes_through_debounce_buffer():+ """Characterization (pre-v3 behavior): an incoming text lands in the+ per-chat debounce buffer and schedules a delayed flush."""+ from d_brain.bot.handlers import chat++ async def run():+ chat._buffers.clear()+ chat._add_to_buffer(chat_id=10, user_id=1, content="привет", msg_type="text", bot=None)+ buf = chat._buffers[10]+ assert [m.content for m in buf.messages] == ["привет"]+ assert buf.task is not None and not buf.task.done()+ buf.task.cancel()++ asyncio.run(run())+++def test_build_prompt_joins_buffered_messages():+ from d_brain.bot.handlers.chat import BufferedMessage, _build_prompt+ from datetime import datetime++ msgs = [+ BufferedMessage("a", "text", datetime(2026, 6, 10, 10, 0)),+ BufferedMessage("b", "voice", datetime(2026, 6, 10, 10, 1)),+ ]+ out = _build_prompt(msgs)+ assert "a" in out and "b" in out and "[voice]" in out