Overview
The chat handler is the core message processing system that powers Junkie’s Discord interactions. It manages incoming messages, resolves mentions, builds context, and orchestrates team-based AI responses.Chatbot Prefix
Junkie uses the! prefix for chatbot commands. When a message starts with !, the bot processes it through its AI team system.
discord_bot/chat_handler.py:115-121
Message Processing Flow
1. Mention Resolution
The handler converts Discord mentions into readable text for better context understanding:2. Context Building
The system builds a context-aware prompt using conversation history:discord_bot/chat_handler.py:126-141
3. Reply Context Detection
When users reply to specific messages, Junkie includes that context:discord_bot/chat_handler.py:128-139
4. Image Attachment Support
The handler extracts images from both the current message and any replied-to message:discord_bot/chat_handler.py:144-159
5. Team Execution
The prompt is sent to the user’s AI team with session isolation per channel:discord_bot/chat_handler.py:162-185
6. Response Formatting
The bot restores mentions and formats the response:discord_bot/chat_handler.py:191-198
7. Message Chunking
Long responses are split into multiple messages to respect Discord’s 2000 character limit:discord_bot/chat_handler.py:200-203
Team Architecture
Theasync_ask_junkie function manages team creation and execution:
discord_bot/chat_handler.py:25-48
Event Handlers
Message Updates
The handler automatically updates the cache when messages are edited:discord_bot/chat_handler.py:206-208
Message Deletions
Deleted messages are removed from the context cache:discord_bot/chat_handler.py:210-213
Bot Initialization
On startup, the bot initializes the database, sets up MCP tools, and starts message backfill:discord_bot/chat_handler.py:52-67
Cache Integration
Every message (both user and bot messages) is automatically cached for context building:discord_bot/chat_handler.py:104-112
Error Handling
The handler includes comprehensive error handling with user-friendly messages:- Response validation ensures non-empty replies
- Exceptions are logged with full stack traces
- Users receive truncated error messages (max 500 chars)
- Failed requests don’t crash the bot
Performance Metrics
Each response includes execution time for transparency:discord_bot/chat_handler.py:174-198