sync: auto-sync from GURU-BEAST-ROG at 2026-05-01 15:05:53

Author: Mike Swanson
Machine: GURU-BEAST-ROG
Timestamp: 2026-05-01 15:05:53
This commit is contained in:
2026-05-01 15:05:53 -07:00
parent ec98c6c636
commit b008b61440
11 changed files with 429 additions and 559 deletions

View File

@@ -2,30 +2,24 @@
import asyncio
import logging
import sys
from pathlib import Path
import discord
from discord.ext import commands
from dotenv import load_dotenv
from bot.config import settings
from bot.claude.client import ClaudeClient
from bot.claude.client import ClaudeAgentManager
from bot.handlers.message_handler import MessageHandler
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(
level=getattr(logging, settings.log_level.upper()),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.StreamHandler(sys.stdout),
]
handlers=[logging.StreamHandler(sys.stdout)],
)
# Add file handler if log file specified
if settings.log_file:
settings.log_file.parent.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(settings.log_file)
@@ -37,99 +31,100 @@ if settings.log_file:
logger = logging.getLogger(__name__)
# Discord bot setup with required intents
intents = discord.Intents.default()
intents.message_content = True # Required to read message content
intents.message_content = True
intents.guilds = True
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
# Initialize Claude client
claude_client = ClaudeClient()
# Initialize message handler
message_handler: MessageHandler = None
agent_manager = ClaudeAgentManager()
message_handler: MessageHandler | None = None
@bot.event
async def on_ready():
"""Called when the bot successfully connects to Discord."""
global message_handler
logger.info(f"Bot connected as {bot.user.name} (ID: {bot.user.id})")
logger.info(f"Connected to {len(bot.guilds)} guild(s)")
logger.info("[OK] Bot connected as %s (ID: %d)", bot.user.name, bot.user.id)
logger.info("[INFO] Connected to %d guild(s)", len(bot.guilds))
# Validate paths
try:
settings.validate_paths()
logger.info("Path validation successful")
logger.info(f"Vault path: {settings.vault_path}")
logger.info(f"ClaudeTools root: {settings.claudetools_root}")
logger.info(f"Git Bash: {settings.git_bash_path}")
logger.info("[OK] ClaudeTools workspace: %s", settings.claudetools_root)
except FileNotFoundError as e:
logger.error(f"Path validation failed: {e}")
logger.error("Bot will continue but some features may not work")
logger.error("[ERROR] Path validation failed: %s", e)
# Initialize message handler
message_handler = MessageHandler(bot, claude_client)
message_handler = MessageHandler(bot, agent_manager)
# Set bot status
await bot.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name="for @mentions | ClaudeTools MSP Assistant"
name="for @mentions | ClaudeTools Agent",
)
)
logger.info("Bot is ready and listening for mentions!")
logger.info("[OK] Bot is ready and listening for mentions")
for guild in bot.guilds:
logger.info("[DEBUG] Guild: %s (id=%d) channels=%d", guild.name, guild.id, len(guild.text_channels))
for ch in guild.text_channels[:10]:
perms = ch.permissions_for(guild.me)
logger.info("[DEBUG] #%s view=%s read=%s send=%s", ch.name, perms.view_channel, perms.read_message_history, perms.send_messages)
@bot.event
async def on_message(message: discord.Message):
"""Called when a message is sent in a channel the bot can see."""
# Ignore messages from bots
logger.info("[DEBUG] on_message fired: author=%s bot=%s channel=%s content_len=%d mentions=%d",
message.author.name, message.author.bot, getattr(message.channel, 'name', 'DM'),
len(message.content), len(message.mentions))
if message.author.bot:
return
# Check if bot was mentioned
if bot.user in message.mentions:
is_mention = bot.user in message.mentions
is_in_bot_thread = (
isinstance(message.channel, discord.Thread)
and message.channel.owner_id == bot.user.id
)
if is_mention or is_in_bot_thread:
trigger = "mention" if is_mention else "thread-followup"
logger.info(
f"Mentioned by {message.author.name} in #{message.channel.name}: "
f"{message.content[:100]}"
"[INFO] %s by %s in #%s: %s",
trigger,
message.author.name,
message.channel.name,
message.content[:100],
)
await message_handler.handle_mention(message)
return
# Process commands (for future slash commands)
await bot.process_commands(message)
@bot.event
async def on_error(event: str, *args, **kwargs):
"""Called when an error occurs."""
logger.error(f"Error in {event}", exc_info=sys.exc_info())
logger.error("[ERROR] Error in %s", event, exc_info=sys.exc_info())
async def main():
"""Main entry point."""
try:
logger.info("Starting ClaudeTools Discord Bot...")
logger.info(f"Claude Model: {settings.claude_model}")
logger.info(f"ClaudeTools API: {settings.claudetools_api_url}")
logger.info("[INFO] Starting ClaudeTools Discord Bot")
logger.info("[INFO] Claude model: %s", settings.claude_model)
logger.info("[INFO] Workspace: %s", settings.claudetools_root)
# Start the bot
async with bot:
await bot.start(settings.discord_token)
except KeyboardInterrupt:
logger.info("Received keyboard interrupt, shutting down...")
logger.info("[INFO] Keyboard interrupt, shutting down")
except Exception as e:
logger.error(f"Fatal error: {e}", exc_info=True)
logger.error("[ERROR] Fatal error: %s", e, exc_info=True)
raise
finally:
logger.info("Bot shut down complete")
await agent_manager.shutdown()
logger.info("[OK] Bot shut down complete")
if __name__ == "__main__":