Files
abot/message_processor.py
2026-01-14 16:57:36 -08:00

111 lines
3.7 KiB
Python

import logging
from typing import Dict, Any
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
logger = logging.getLogger(__name__)
# Try to import LLM client, but don't fail if it's not available
try:
from llm.local_llm_client import chat_completion
LLM_AVAILABLE = True
except ImportError:
logger.warning("LLM client not available, using simple echo mode")
LLM_AVAILABLE = False
chat_completion = None
def process_mention(
event_data: dict,
slack_client: WebClient,
vector_store: Any,
bot_profile: Any,
tool_registry: Dict[str, Any]
) -> None:
"""
Process messages that mention the bot.
"""
event = event_data.get("event", {})
channel = event.get("channel")
user = event.get("user")
text = event.get("text", "")
ts = event.get("ts") # This is the message timestamp
logger.info(f"Processing mention from {user} in {channel}")
# Remove bot mention from text
from config import BOT_USER_ID
clean_text = text.replace(f"<@{BOT_USER_ID}>", "").strip()
# Get bot configuration
bot_name = getattr(bot_profile, "BOT_IDENTIFIER", "Bot")
system_prompt = getattr(bot_profile, "SYSTEM_PROMPT", "You are a helpful assistant.")
try:
# Try to get RAG context if enabled
rag_enabled = getattr(bot_profile, "ENABLE_RAG_INSERT", False)
context = ""
if rag_enabled:
try:
# Search for similar messages
similar = vector_store.search_similar(clean_text, limit=3)
if similar:
context = "\nRelevant context:\n" + "\n".join(similar)
except AttributeError:
logger.warning("RAG retrieval failed: search_similar not implemented")
except Exception as e:
logger.error(f"RAG retrieval error: {e}")
# Generate response
if LLM_AVAILABLE and chat_completion:
try:
# Use LLM to generate response
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": clean_text}
]
if context:
messages.insert(1, {"role": "system", "content": f"Context: {context}"})
llm_response = chat_completion(messages)
response_text = llm_response.get("content", "Sorry, I couldn't generate a response.")
except Exception as e:
logger.error(f"LLM error: {e}", exc_info=True)
response_text = f"You said: {clean_text}"
else:
# Simple echo response when LLM not available
response_text = f"You said: {clean_text}"
if context:
response_text += f"\n{context}"
# Send message to channel (NOT as a thread reply)
slack_client.chat_postMessage(
channel=channel,
text=response_text
)
logger.info(f"Sent response to {channel}")
except SlackApiError as e:
logger.error(f"Slack API error: {e.response['error']}", exc_info=True)
try:
slack_client.chat_postMessage(
channel=channel,
text="Sorry, I encountered a Slack API error."
)
except:
pass
except Exception as e:
logger.error(f"Error processing mention: {e}", exc_info=True)
try:
slack_client.chat_postMessage(
channel=channel,
text="⚠️ Sorry, I encountered an internal error."
)
except:
pass