Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat: Enhanced Slack integration with interactive UI and comprehensive setup guide

cyhhao0bb66c4389bf
diff --git a/.env.example b/.env.example
index 9d91c93e1..2a69a41f6 100644
--- a/.env.example
+++ b/.env.example
@@ -1,13 +1,26 @@
-# Telegram Configuration
-TELEGRAM_BOT_TOKEN=your_bot_token_here
+# IM Platform Selection
+# Options: telegram, slack
+IM_PLATFORM=telegram
+
+# ============== Telegram Configuration ==============
+TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
# Optional: Target chat ID to send all Claude Code outputs
# If set, all outputs will be sent to this chat instead of the original chat
-TARGET_CHAT_ID=
+TELEGRAM_TARGET_CHAT_ID=
+
+# ============== Slack Configuration ==============
+# Required for Slack
+SLACK_BOT_TOKEN=xoxb-your-slack-bot-token
+
+# Required for Socket Mode (recommended)
+SLACK_APP_TOKEN=xapp-your-slack-app-token
+
+# Optional: For webhook mode instead of Socket Mode
+SLACK_SIGNING_SECRET=your-signing-secret
-# Optional: Comma-separated list of allowed Telegram user IDs
-# Leave empty to allow all users
-ALLOWED_USERS=
+# Optional: Default channel for outputs
+SLACK_TARGET_CHANNEL=
# Claude Configuration
CLAUDE_PERMISSION_MODE=bypassPermissions
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 000000000..e4ae966da
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,125 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Project Overview
+
+This is a multi-platform remote control bot for Claude Code, supporting both Telegram and Slack. Users can send messages through IM platforms to execute Claude Code commands remotely. The system provides session management, message queuing, and real-time feedback.
+
+## Development Commands
+
+### Environment Setup
+```bash
+# Create virtual environment and install dependencies
+python3 -m venv venv
+source venv/bin/activate # On Windows: venv\Scripts\activate
+pip install -r requirements.txt
+
+# Create configuration from template
+cp .env.example .env
+# Edit .env with your platform and credentials
+```
+
+### Running the Bot
+```bash
+# Start the bot (preferred - includes process management)
+./start.sh
+
+# Alternative direct start
+python main.py
+
+# Stop the bot
+./stop.sh
+
+# Check bot status
+./status.sh
+```
+
+### Development Testing
+```bash
+# Test imports and basic functionality
+python3 -c "from config.settings import AppConfig; from modules.im_factory import IMFactory; print('Imports successful!')"
+
+# Check logs in real-time
+tail -f logs/bot_*.log
+
+# Manual testing with specific platform
+IM_PLATFORM=telegram python main.py
+IM_PLATFORM=slack python main.py
+```
+
+## Architecture Overview
+
+### Multi-Platform Design Pattern
+The system uses an abstract factory pattern with platform-agnostic interfaces:
+
+1. **BaseIMClient** (`modules/base_im_client.py`): Abstract base class defining the IM interface
+2. **IMFactory** (`modules/im_factory.py`): Creates appropriate platform clients
+3. **Controller** (`core/controller.py`): Platform-agnostic business logic coordinator
+
+### Key Components
+
+- **Configuration System** (`config/settings.py`): Environment-based config with platform-specific validation
+- **Session Management** (`modules/session_manager.py`): Per-user message queues and execution state
+- **Claude Integration** (`modules/claude_client.py`): Wrapper around Claude Code SDK
+- **Settings Management** (`modules/settings_manager.py`): User preferences and message type visibility
+
+### Platform Implementations
+- **TelegramBot** (`modules/telegram_bot.py`): Telegram-specific implementation with inline keyboards
+- **SlackBot** (`modules/slack_bot.py`): Slack-specific implementation with thread support and Socket Mode
+
+### Message Flow
+1. User sends message via IM platform
+2. Platform-specific client converts to `MessageContext`
+3. Controller queues message per user
+4. Claude Code executes message sequentially
+5. Real-time output streamed back through same IM platform
+
+## Configuration Requirements
+
+### Essential Environment Variables
+- `IM_PLATFORM`: Must be "telegram" or "slack"
+- Platform-specific tokens (see `.env.example`)
+- `CLAUDE_CWD`: Working directory for Claude Code execution
+
+### Platform Switching
+The system dynamically loads the appropriate IM client based on `IM_PLATFORM`. Configuration validation ensures required tokens are present for the selected platform.
+
+## Adding New IM Platforms
+
+To extend support to new platforms (Discord, Teams, etc.):
+
+1. Create new client class inheriting from `BaseIMClient`
+2. Implement all abstract methods (send_message, edit_message, etc.)
+3. Create platform config class inheriting from `BaseIMConfig`
+4. Add platform to `IMFactory.create_client()`
+5. Update `AppConfig.from_env()` validation
+6. Add environment variables to `.env.example`
+
+Reference `modules/slack_bot.py` for a complete implementation example.
+
+## Thread and Session Management
+
+### Slack Thread Handling
+Slack conversations are automatically organized into threads using `thread_timestamps` dict. Each user/channel combination gets a persistent thread for continuity.
+
+### Session Isolation
+Each user has an independent message queue and execution state managed by `SessionManager`. This allows concurrent users without interference.
+
+### Callback System
+The controller registers command handlers with IM clients through a callback system, allowing platform-agnostic command handling while preserving platform-specific features (inline keyboards, thread replies, etc.).
+
+## Deployment Notes
+
+### Process Management
+- `start.sh` provides daemon-style execution with PID tracking
+- Logs are automatically rotated and stored in `logs/` directory
+- Virtual environment detection and activation is automatic
+
+### Error Handling
+- Graceful degradation for missing optional tokens
+- Automatic retry with exponential backoff for network failures
+- Comprehensive logging for debugging platform-specific issues
+
+### Socket Mode vs Webhooks
+For Slack, Socket Mode is preferred as it doesn't require public endpoints. The system automatically uses Socket Mode if `SLACK_APP_TOKEN` is provided.
\ No newline at end of file
diff --git a/README.md b/README.md
index d7062c884..38b1d97ff 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
-# Claude Proxy - Telegram Bot for Remote Claude Code Control
+# Claude Code Remote Control Bot
-A modular system for controlling Claude Code through Telegram Bot.
+A modular system for controlling Claude Code through multiple instant messaging platforms (Telegram, Slack).
## Quick Start
@@ -12,10 +12,14 @@ pip install -r requirements.txt
2. Create `.env` file from template:
```bash
cp .env.example .env
-# Edit .env with your Telegram bot token
+# Edit .env with your platform choice and credentials
```
-3. Run the bot:
+3. Choose your platform:
+ - Set `IM_PLATFORM=telegram` for Telegram
+ - Set `IM_PLATFORM=slack` for Slack
+
+4. Run the bot:
```bash
./start.sh
# or
@@ -24,75 +28,122 @@ python main.py
## Configuration
-### Environment Variables
+### Platform Selection
+
+Set `IM_PLATFORM` in your `.env` file:
+- `telegram` - Use Telegram Bot
+- `slack` - Use Slack Bot
+
+### Telegram Configuration
- `TELEGRAM_BOT_TOKEN` (required): Your Telegram bot token from @BotFather
-- `TARGET_CHAT_ID` (optional): Specific chat ID to send all Claude Code outputs
+- `TELEGRAM_TARGET_CHAT_ID` (optional): Specific chat ID to send all Claude Code outputs
- Use `/start` command to get your chat ID
- If set, all outputs go to this chat regardless of where commands come from
-- `ALLOWED_USERS` (optional): Comma-separated list of allowed user IDs
- - Leave empty to allow all users
- - Example: `ALLOWED_USERS=123456789,987654321`
+
+### Slack Configuration
+
+- `SLACK_BOT_TOKEN` (required): Your Slack bot token (starts with `xoxb-`)
+- `SLACK_APP_TOKEN` (required for Socket Mode): App-level token (starts with `xapp-`)
+- `SLACK_TARGET_CHANNEL` (optional): Default channel for all outputs
+
+For detailed Slack setup instructions, see [docs/SLACK_SETUP.md](docs/SLACK_SETUP.md).
+
+### Claude Configuration
+
- `CLAUDE_CWD`: Working directory for Claude Code (default: `./_tmp`)
+- `CLAUDE_PERMISSION_MODE`: Permission mode (default: `bypassPermissions`)
+- `CLAUDE_CONTINUE_CONVERSATION`: Continue conversations (default: `true`)
+- `CLAUDE_SYSTEM_PROMPT`: Custom system prompt (optional)
+
+### Application Configuration
+
- `LOG_LEVEL`: Logging level (default: `INFO`)
## Architecture
```
-claude-proxy/
+claude-code-bot/
├── config/
-│ └── settings.py # Configuration management
+│ └── settings.py # Configuration management
├── modules/
│ ├── __init__.py
-│ ├── telegram_bot.py # Telegram bot interface
-│ ├── claude_client.py # Claude Code SDK wrapper
-│ └── session_manager.py # Session and message queue management
+│ ├── base_im_client.py # Abstract base class for IM platforms
+│ ├── base_im_config.py # Base configuration class
+│ ├── telegram_bot.py # Telegram implementation
+│ ├── slack_bot.py # Slack implementation
+│ ├── im_factory.py # Factory for creating IM clients
+│ ├── claude_client.py # Claude Code SDK wrapper
+│ ├── session_manager.py # Session and message queue management
+│ └── settings_manager.py # User settings management
├── core/
│ ├── __init__.py
-│ └── controller.py # Main application controller
-├── utils/
-│ ├── __init__.py
-│ └── message_formatter.py # Message formatting utilities
-├── main.py # Application entry point
-└── requirements.txt # Dependencies
+│ └── controller.py # Platform-agnostic controller
+├── docs/
+│ └── SLACK_SETUP.md # Slack setup documentation
+├── main.py # Application entry point
+└── requirements.txt # Dependencies
```
## Features
-1. **Automatic Execution**: Messages are processed automatically in order - no manual trigger needed
-2. **Message Queue**: User messages are queued and executed sequentially
-3. **Real-time Feedback**: Claude Code outputs are forwarded to Telegram in real-time
-4. **Target Chat Support**: Optionally send all outputs to a specific chat ID
+### Core Features
+1. **Multi-Platform Support**: Works with Telegram and Slack
+2. **Automatic Execution**: Messages are processed automatically in order
+3. **Message Queue**: User messages are queued and executed sequentially
+4. **Real-time Feedback**: Claude Code outputs are forwarded in real-time
5. **Session Management**: Supports multiple concurrent users with independent queues
-6. **Permission Control**: Configure allowed users via environment variables
-7. **Status Tracking**: Visual indicators for queue and execution status
-8. **Working Directory Management**: Change Claude Code's working directory on the fly
-
-## Modules
-
-### telegram_bot
-- Handles all Telegram interactions
-- Commands:
- - `/start` - Shows chat ID and user ID
- - `/status` - Display queue and execution status
- - `/clear` - Clear message queue
- - `/cwd` - Show current working directory
- - `/set_cwd <path>` - Change working directory
- - `/execute` - Manually trigger queue processing
-- Automatic message queue processing
-- Message formatting and rate limiting
-
-### claude_client
-- Wraps Claude Code SDK
-- Manages Claude Code options and queries
-- Handles streaming responses
-
-### session_manager
-- Manages user sessions
-- Message queue operations
-- Session state tracking
-
-### controller
-- Coordinates between modules
-- Main application logic
-- Error handling
\ No newline at end of file
+6. **Status Tracking**: Visual indicators for queue and execution status
+7. **Working Directory Management**: Change Claude Code's working directory on the fly
+8. **Personalization Settings**: Configure which message types to display
+
+### Platform-Specific Features
+
+#### Telegram
+- Direct message and group chat support
+- Inline keyboard for settings
+- Message threading via reply-to
+- Markdown formatting support
+
+#### Slack
+- **Thread Support**: Each conversation is organized in its own thread
+- **Socket Mode**: No need for public webhooks
+- **Channel & DM Support**: Works in both channels and direct messages
+- **Mention-based Triggering**: In channels, mention the bot to interact
+
+## Commands
+
+All platforms support the same commands:
+- `/start` - Shows welcome message and IDs
+- `/status` - Display queue and execution status
+- `/clear` - Clear message queue
+- `/cwd` - Show current working directory
+- `/set_cwd <path>` - Change working directory
+- `/execute` - Manually trigger queue processing
+- `/queue` - Show messages in queue
+- `/settings` - Configure message visibility
+
+## Usage
+
+### Telegram
+1. Start a chat with your bot
+2. Send messages directly - they'll be queued and processed automatically
+3. Use commands with `/` prefix
+
+### Slack
+1. **In Channels**: Mention the bot (`@bot-name your message`)
+2. **In DMs**: Send messages directly
+3. Commands work with `/` prefix
+4. Each user's conversation is organized in a thread
+
+## Adding New Platforms
+
+The architecture supports easy addition of new IM platforms:
+
+1. Create a new class inheriting from `BaseIMClient`
+2. Implement all abstract methods
+3. Add configuration class inheriting from `BaseIMConfig`
+4. Update `IMFactory` to support the new platform
+5. Add platform-specific environment variables
+
+See `modules/slack_bot.py` for a complete implementation example.
\ No newline at end of file
diff --git a/config/settings.py b/config/settings.py
index e61d399e7..9e78fa5e9 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -1,13 +1,16 @@
import os
+import logging
from dataclasses import dataclass
from typing import Optional
+from modules.base_im_config import BaseIMConfig
+
+logger = logging.getLogger(__name__)
@dataclass
-class TelegramConfig:
+class TelegramConfig(BaseIMConfig):
bot_token: str
target_chat_id: Optional[int] = None # Target chat ID to send all messages
- allowed_users: Optional[list[int]] = None # Optional: Restrict who can use the bot
@classmethod
def from_env(cls) -> 'TelegramConfig':
@@ -16,14 +19,20 @@ class TelegramConfig:
raise ValueError("TELEGRAM_BOT_TOKEN environment variable is required")
target_chat_id = None
- target_chat_id_str = os.getenv("TARGET_CHAT_ID")
+ target_chat_id_str = os.getenv("TELEGRAM_TARGET_CHAT_ID")
if target_chat_id_str:
target_chat_id = int(target_chat_id_str)
- allowed_users_str = os.getenv("ALLOWED_USERS", "")
- allowed_users = [int(uid) for uid in allowed_users_str.split(",") if uid] if allowed_users_str else None
-
- return cls(bot_token=bot_token, target_chat_id=target_chat_id, allowed_users=allowed_users)
+ return cls(bot_token=bot_token, target_chat_id=target_chat_id)
+
+ def validate(self) -> bool:
+ """Validate Telegram configuration"""
+ if not self.bot_token:
+ raise ValueError("TELEGRAM_BOT_TOKEN is required")
+ if not self.bot_token.startswith(('bot', 'xox')):
+ # Basic token format check
+ logger.warning("Telegram bot token format might be invalid")
+ return True
@dataclass
@@ -43,16 +52,64 @@ class ClaudeConfig:
)
+@dataclass
+class SlackConfig(BaseIMConfig):
+ bot_token: str
+ app_token: Optional[str] = None # For Socket Mode
+ signing_secret: Optional[str] = None # For webhook mode
+ target_channel: Optional[str] = None # Default channel for outputs
+
+ @classmethod
+ def from_env(cls) -> 'SlackConfig':
+ bot_token = os.getenv("SLACK_BOT_TOKEN")
+ if not bot_token:
+ raise ValueError("SLACK_BOT_TOKEN environment variable is required")
+
+ return cls(
+ bot_token=bot_token,
+ app_token=os.getenv("SLACK_APP_TOKEN"),
+ signing_secret=os.getenv("SLACK_SIGNING_SECRET"),
+ target_channel=os.getenv("SLACK_TARGET_CHANNEL")
+ )
+
+ def validate(self) -> bool:
+ """Validate Slack configuration"""
+ if not self.bot_token:
+ raise ValueError("SLACK_BOT_TOKEN is required")
+ if not self.bot_token.startswith('xoxb-'):
+ raise ValueError("Invalid Slack bot token format (should start with xoxb-)")
+ if self.app_token and not self.app_token.startswith('xapp-'):
+ raise ValueError("Invalid Slack app token format (should start with xapp-)")
+ return True
+
+
@dataclass
class AppConfig:
- telegram: TelegramConfig
- claude: ClaudeConfig
+ platform: str # 'telegram' or 'slack'
+ telegram: Optional[TelegramConfig] = None
+ slack: Optional[SlackConfig] = None
+ claude: ClaudeConfig = None
log_level: str = "INFO"
@classmethod
def from_env(cls) -> 'AppConfig':
- return cls(
- telegram=TelegramConfig.from_env(),
+ platform = os.getenv("IM_PLATFORM", "telegram").lower()
+
+ if platform not in ["telegram", "slack"]:
+ raise ValueError(f"Invalid IM_PLATFORM: {platform}. Must be 'telegram' or 'slack'")
+
+ config = cls(
+ platform=platform,
claude=ClaudeConfig.from_env(),
log_level=os.getenv("LOG_LEVEL", "INFO")
- )
\ No newline at end of file
+ )
+
+ # Load platform-specific config
+ if platform == "telegram":
+ config.telegram = TelegramConfig.from_env()
+ config.telegram.validate()
+ elif platform == "slack":
+ config.slack = SlackConfig.from_env()
+ config.slack.validate()
+
+ return config
\ No newline at end of file
diff --git a/core/controller.py b/core/controller.py
index 8d6c04f10..f853a5756 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -2,10 +2,9 @@ import asyncio
import logging
import os
from typing import Optional
-from telegram.helpers import escape_markdown
-from telegram import InlineKeyboardButton, InlineKeyboardMarkup
-from config import AppConfig
-from modules.telegram_bot import TelegramBot
+from config.settings import AppConfig
+from modules.base_im_client import BaseIMClient, MessageContext, InlineKeyboard, InlineButton
+from modules.im_factory import IMFactory
from modules.claude_client import ClaudeClient
from modules.session_manager import SessionManager
from modules.settings_manager import SettingsManager
@@ -17,7 +16,7 @@ logger = logging.getLogger(__name__)
class Controller:
def __init__(self, config: AppConfig):
self.config = config
- self.telegram_bot = TelegramBot(config.telegram)
+ self.im_client: BaseIMClient = IMFactory.create_client(config)
self.claude_client = ClaudeClient(config.claude)
self.session_manager = SessionManager()
self.settings_manager = SettingsManager()
@@ -30,57 +29,137 @@ class Controller:
def _setup_callbacks(self):
"""Setup callback connections between modules"""
- self.telegram_bot.register_callbacks(
+ # Create command handlers dict
+ self.command_handlers = {
+ 'start': self.handle_start,
+ 'execute': self.handle_execute,
+ 'status': self.handle_status,
+ 'clear': self.handle_clear,
+ 'cwd': self.handle_cwd,
+ 'set_cwd': self.handle_set_cwd,
+ 'queue': self.handle_queue,
+ 'settings': self.handle_settings
+ }
+
+ # Register callbacks with the IM client
+ self.im_client.register_callbacks(
on_message=self.handle_user_message,
- on_execute=self.handle_execute,
- on_status=self.handle_status,
- on_clear=self.handle_clear,
- on_cwd=self.handle_cwd,
- on_set_cwd=self.handle_set_cwd,
- on_queue=self.handle_queue,
- on_settings=self.handle_settings,
+ on_command=self.command_handlers,
on_callback_query=self.handle_callback_query
)
- async def handle_user_message(self, chat_id: int, user_id: int, message: str) -> str:
+ async def handle_start(self, context: MessageContext, args: str = ""):
+ """Handle /start command with interactive buttons"""
+ platform_name = self.config.platform.capitalize()
+
+ # Get user and channel info
+ user_info = await self.im_client.get_user_info(context.user_id)
+ channel_info = await self.im_client.get_channel_info(context.channel_id)
+
+ # For non-Slack platforms, use traditional text message
+ if self.config.platform != "slack":
+ message_text = f"""Welcome to Claude Code Remote Control Bot!
+
+Platform: {platform_name}
+User ID: {context.user_id}
+Channel/Chat ID: {context.channel_id}
+
+Commands:
+/start - Show this message
+/execute - Manually start processing queue
+/clear - Clear message queue
+/status - Show current status
+/queue - Show messages in queue
+/cwd - Show current working directory
+/set_cwd <path> - Set working directory
+/settings - Personalization settings
+
+How it works:
+• Send any message to add it to the queue
+• Messages are automatically processed in order
+• Claude Code executes each message sequentially"""
+
+ await self.im_client.send_message(context, message_text)
+ return
+
+ # For Slack, create interactive buttons using Block Kit
+ user_name = user_info.get('real_name') or user_info.get('name') or 'User'
+
+ # Create interactive buttons for commands
+ buttons = [
+ # Row 1: Status commands
+ [
+ InlineButton(text="📊 Queue Status", callback_data="cmd_status"),
+ InlineButton(text="📋 Show Queue", callback_data="cmd_queue")
+ ],
+ # Row 2: Queue management
+ [
+ InlineButton(text="🚀 Execute Queue", callback_data="cmd_execute"),
+ InlineButton(text="🗑️ Clear Queue", callback_data="cmd_clear")
+ ],
+ # Row 3: Directory commands
+ [
+ InlineButton(text="📁 Current Dir", callback_data="cmd_cwd"),
+ InlineButton(text="⚙️ Settings", callback_data="cmd_settings")
+ ],
+ # Row 4: Help and info
+ [
+ InlineButton(text="ℹ️ How it Works", callback_data="info_how_it_works"),
+ InlineButton(text="📖 All Commands", callback_data="info_all_commands")
+ ]
+ ]
+
+ keyboard = InlineKeyboard(buttons=buttons)
+
+ welcome_text = f"""🎉 **Welcome to Claude Code Remote Control Bot!**
+
+👋 Hello **{user_name}**!
+🔧 Platform: **{platform_name}**
+📍 Channel: **{channel_info.get('name', 'Unknown')}**
+
+**Quick Actions:**
+Choose a command below or type any message to add it to the processing queue."""
+
+ target_context = self._get_target_context(context)
+ await self.im_client.send_message_with_buttons(
+ target_context,
+ welcome_text,
+ keyboard,
+ parse_mode='markdown'
+ )
+
+ async def handle_user_message(self, context: MessageContext, message: str):
"""Handle incoming user message"""
try:
- await self.session_manager.add_message(user_id, chat_id, message)
- logger.info(f"User {user_id} added message to queue")
+ await self.session_manager.add_message(context.user_id, context.channel_id, message)
+ logger.info(f"User {context.user_id} added message to queue")
# Check if not already executing, then start processing
- if not await self.session_manager.is_executing(user_id):
- asyncio.create_task(self.process_user_queue(chat_id, user_id))
+ if not await self.session_manager.is_executing(context.user_id):
+ asyncio.create_task(self.process_user_queue(context))
- # Don't return any message - user doesn't want confirmation
- return None
+ # Don't send confirmation - user doesn't want it
except Exception as e:
logger.error(f"Error handling message: {e}")
- return "Error adding message to queue."
+ await self.im_client.send_message(context, "Error adding message to queue.")
- async def process_user_queue(self, chat_id: int, user_id: int):
+ async def process_user_queue(self, context: MessageContext):
"""Process all messages in user's queue sequentially"""
try:
# Mark as executing
- await self.session_manager.set_executing(user_id, True)
+ await self.session_manager.set_executing(context.user_id, True)
- # Use target chat ID if configured, otherwise use the original chat
- target_chat_id = self.config.telegram.target_chat_id or chat_id
+ # Determine target context (use configured target channel/chat if available)
+ target_context = self._get_target_context(context)
- while await self.session_manager.has_messages(user_id):
+ while await self.session_manager.has_messages(context.user_id):
# Get next message
- message = await self.session_manager.get_next_message(user_id)
+ message = await self.session_manager.get_next_message(context.user_id)
if not message:
break
- # Don't send processing notification - user doesn't want it
- # await self.telegram_bot.send_message(
- # target_chat_id,
- # f"🚀 Processing: {message[:50]}..."
- # )
-
# Get user's CWD from settings if available
- custom_cwd = self.settings_manager.get_custom_cwd(user_id)
+ custom_cwd = self.settings_manager.get_custom_cwd(context.user_id)
if custom_cwd:
# Temporarily set the CWD for this execution
original_cwd = self.claude_client.options.cwd
@@ -89,30 +168,40 @@ class Controller:
# Execute with Claude
async def on_claude_message(claude_msg: str, message_type: str = None):
# Check if this message type should be hidden
- if message_type and self.settings_manager.is_message_type_hidden(user_id, message_type):
- logger.info(f"Skipping {message_type} message for user {user_id} (hidden in settings)")
+ if message_type and self.settings_manager.is_message_type_hidden(context.user_id, message_type):
+ logger.info(f"Skipping {message_type} message for user {context.user_id} (hidden in settings)")
return
- # Send Claude's formatted output with smart formatting based on message type
- await self.telegram_bot.send_message_smart(target_chat_id, claude_msg, message_type)
+ # Send Claude's formatted output
+ # For Slack, we want to maintain thread context
+ if self.config.platform == "slack" and hasattr(self.im_client, 'get_or_create_thread'):
+ # Get or create thread for this conversation
+ thread_ts = await self.im_client.get_or_create_thread(
+ target_context.channel_id,
+ target_context.user_id
+ )
+ if thread_ts:
+ target_context.thread_id = thread_ts
+
+ await self.im_client.send_message(target_context, claude_msg, parse_mode='markdown')
try:
- await self.claude_client.stream_execute(message, on_claude_message, user_id)
+ await self.claude_client.stream_execute(message, on_claude_message, context.user_id)
# Restore original CWD if it was changed
if custom_cwd:
self.claude_client.options.cwd = original_cwd
# Check if there are more messages
- remaining = await self.session_manager.has_messages(user_id)
+ remaining = await self.session_manager.has_messages(context.user_id)
if remaining:
- await self.telegram_bot.send_message(
- target_chat_id,
- f"✅ Completed. Processing next message..."
+ await self.im_client.send_message(
+ target_context,
+ "✅ Completed. Processing next message..."
)
else:
- await self.telegram_bot.send_message(
- target_chat_id,
+ await self.im_client.send_message(
+ target_context,
"✅ All messages processed!"
)
@@ -121,8 +210,8 @@ class Controller:
# Restore original CWD if it was changed
if custom_cwd:
self.claude_client.options.cwd = original_cwd
- await self.telegram_bot.send_message(
- target_chat_id,
+ await self.im_client.send_message(
+ target_context,
f"❌ Error processing message: {str(e)}\nStopping queue processing."
)
break
@@ -132,59 +221,76 @@ class Controller:
except Exception as e:
logger.error(f"Error in process_user_queue: {e}")
- target_chat_id = self.config.telegram.target_chat_id or chat_id
- await self.telegram_bot.send_message(
- target_chat_id,
+ target_context = self._get_target_context(context)
+ await self.im_client.send_message(
+ target_context,
f"❌ Unexpected error: {str(e)}"
)
finally:
- await self.session_manager.set_executing(user_id, False)
+ await self.session_manager.set_executing(context.user_id, False)
- async def handle_execute(self, chat_id: int, user_id: int):
- """Handle manual execute command - now just starts queue processing"""
- target_chat_id = self.config.telegram.target_chat_id or chat_id
+ def _get_target_context(self, context: MessageContext) -> MessageContext:
+ """Get target context based on configuration"""
+ target_context = MessageContext(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ thread_id=context.thread_id,
+ platform_specific=context.platform_specific
+ )
+
+ # Override channel_id if target is configured
+ if self.config.platform == "telegram" and self.config.telegram and self.config.telegram.target_chat_id:
+ target_context.channel_id = str(self.config.telegram.target_chat_id)
+ elif self.config.platform == "slack" and self.config.slack and self.config.slack.target_channel:
+ target_context.channel_id = self.config.slack.target_channel
+
+ return target_context
+
+ async def handle_execute(self, context: MessageContext, args: str = ""):
+ """Handle manual execute command"""
+ target_context = self._get_target_context(context)
- if await self.session_manager.is_executing(user_id):
- await self.telegram_bot.send_message(
- target_chat_id,
+ if await self.session_manager.is_executing(context.user_id):
+ await self.im_client.send_message(
+ target_context,
"Already processing messages. Please wait..."
)
return
- if not await self.session_manager.has_messages(user_id):
- await self.telegram_bot.send_message(
- target_chat_id,
+ if not await self.session_manager.has_messages(context.user_id):
+ await self.im_client.send_message(
+ target_context,
"No messages in queue."
)
return
# Start processing
- asyncio.create_task(self.process_user_queue(chat_id, user_id))
+ asyncio.create_task(self.process_user_queue(context))
- async def handle_status(self, chat_id: int, user_id: int) -> str:
+ async def handle_status(self, context: MessageContext, args: str = ""):
"""Handle status command"""
try:
- status = await self.session_manager.get_status(user_id)
- return status
+ status = await self.session_manager.get_status(context.user_id)
+ await self.im_client.send_message(context, status)
except Exception as e:
logger.error(f"Error getting status: {e}")
- return "Error getting status."
+ await self.im_client.send_message(context, "Error getting status.")
- async def handle_clear(self, chat_id: int, user_id: int) -> str:
+ async def handle_clear(self, context: MessageContext, args: str = ""):
"""Handle clear command"""
try:
- response = await self.session_manager.clear_queue(user_id)
- logger.info(f"User {user_id} cleared queue")
- return response
+ response = await self.session_manager.clear_queue(context.user_id)
+ logger.info(f"User {context.user_id} cleared queue")
+ await self.im_client.send_message(context, response)
except Exception as e:
logger.error(f"Error clearing queue: {e}")
- return "Error clearing queue."
+ await self.im_client.send_message(context, "Error clearing queue.")
- async def handle_cwd(self, chat_id: int, user_id: int) -> str:
+ async def handle_cwd(self, context: MessageContext, args: str = ""):
"""Handle cwd command - show current working directory"""
try:
# Check if user has custom CWD in settings
- custom_cwd = self.settings_manager.get_custom_cwd(user_id)
+ custom_cwd = self.settings_manager.get_custom_cwd(context.user_id)
current_cwd = custom_cwd if custom_cwd else self.claude_client.options.cwd
absolute_path = os.path.abspath(current_cwd)
@@ -201,14 +307,20 @@ class Controller:
else:
response_text += "\n💡 (Default from .env)"
- return escape_markdown(response_text, version=2)
+ await self.im_client.send_message(context, response_text, parse_mode='markdown')
except Exception as e:
logger.error(f"Error getting cwd: {e}")
- return f"Error getting working directory: {str(e)}"
+ await self.im_client.send_message(context, f"Error getting working directory: {str(e)}")
- async def handle_set_cwd(self, chat_id: int, user_id: int, new_path: str) -> str:
+ async def handle_set_cwd(self, context: MessageContext, args: str):
"""Handle set_cwd command - change working directory"""
try:
+ if not args:
+ await self.im_client.send_message(context, "Usage: /set_cwd <path>")
+ return
+
+ new_path = args.strip()
+
# Expand user path and get absolute path
expanded_path = os.path.expanduser(new_path)
absolute_path = os.path.abspath(expanded_path)
@@ -220,153 +332,225 @@ class Controller:
os.makedirs(absolute_path, exist_ok=True)
logger.info(f"Created directory: {absolute_path}")
except Exception as e:
- return f"❌ Cannot create directory: {str(e)}"
+ await self.im_client.send_message(context, f"❌ Cannot create directory: {str(e)}")
+ return
if not os.path.isdir(absolute_path):
- error_text = f"❌ Path exists but is not a directory: {absolute_path}"
- return escape_markdown(error_text, version=2)
+ await self.im_client.send_message(
+ context,
+ f"❌ Path exists but is not a directory: {absolute_path}"
+ )
+ return
# Save to user settings
- self.settings_manager.set_custom_cwd(user_id, absolute_path)
+ self.settings_manager.set_custom_cwd(context.user_id, absolute_path)
- logger.info(f"User {user_id} changed cwd to: {absolute_path}")
+ logger.info(f"User {context.user_id} changed cwd to: {absolute_path}")
response_text = (
f"✅ Working directory changed to:\n"
f"{absolute_path}\n\n"
f"This setting has been saved for your user."
)
- return escape_markdown(response_text, version=2)
+ await self.im_client.send_message(context, response_text, parse_mode='markdown')
except Exception as e:
logger.error(f"Error setting cwd: {e}")
- return f"❌ Error setting working directory: {str(e)}"
+ await self.im_client.send_message(context, f"❌ Error setting working directory: {str(e)}")
- async def handle_queue(self, chat_id: int, user_id: int) -> str:
+ async def handle_queue(self, context: MessageContext, args: str = ""):
"""Handle queue command - show queue details"""
try:
- response = await self.session_manager.get_queue_details(user_id)
- logger.info(f"User {user_id} requested queue status")
- return response
+ response = await self.session_manager.get_queue_details(context.user_id)
+ logger.info(f"User {context.user_id} requested queue status")
+ await self.im_client.send_message(context, response)
except Exception as e:
logger.error(f"Error getting queue details: {e}")
- return f"Error getting queue information: {str(e)}"
+ await self.im_client.send_message(context, f"Error getting queue information: {str(e)}")
- async def handle_settings(self, chat_id: int, user_id: int):
+ async def handle_settings(self, context: MessageContext, args: str = ""):
"""Handle settings command - show settings menu with inline keyboard"""
try:
# Get current settings
- user_settings = self.settings_manager.get_user_settings(user_id)
+ user_settings = self.settings_manager.get_user_settings(context.user_id)
# Get available message types and display names
message_types = self.settings_manager.get_available_message_types()
display_names = self.settings_manager.get_message_type_display_names()
- # Create inline keyboard buttons in 2x2 layout
- keyboard = []
+ # Create inline keyboard buttons
buttons = []
for msg_type in message_types:
is_hidden = msg_type in user_settings.hidden_message_types
checkbox = "☑️" if is_hidden else "⬜"
display_name = display_names.get(msg_type, msg_type)
- button_text = f"{checkbox} Hide {display_name}"
- callback_data = f"toggle_msg_{msg_type}"
- buttons.append(InlineKeyboardButton(button_text, callback_data=callback_data))
-
- # Arrange buttons in 2x2 layout
- for i in range(0, len(buttons), 2):
- row = buttons[i:i+2]
- keyboard.append(row)
+ button = InlineButton(
+ text=f"{checkbox} Hide {display_name}",
+ callback_data=f"toggle_msg_{msg_type}"
+ )
+ buttons.append([button]) # One button per row for now
- # Add info button on its own line
- keyboard.append([InlineKeyboardButton("ℹ️ About Message Types", callback_data="info_msg_types")])
+ # Add info button
+ buttons.append([InlineButton("ℹ️ About Message Types", callback_data="info_msg_types")])
- reply_markup = InlineKeyboardMarkup(keyboard)
+ keyboard = InlineKeyboard(buttons=buttons)
# Send settings message
- target_chat_id = self.config.telegram.target_chat_id or chat_id
- await self.telegram_bot.send_settings_message(
- target_chat_id,
- "⚙️ *Settings \\- Message Visibility*\n\n"
- "Select which message types to hide from Claude output:",
- reply_markup
+ target_context = self._get_target_context(context)
+ await self.im_client.send_message_with_buttons(
+ target_context,
+ "⚙️ *Settings - Message Visibility*\n\nSelect which message types to hide from Claude output:",
+ keyboard,
+ parse_mode='markdown'
)
except Exception as e:
logger.error(f"Error showing settings: {e}")
- target_chat_id = self.config.telegram.target_chat_id or chat_id
- await self.telegram_bot.send_message(
- target_chat_id,
+ target_context = self._get_target_context(context)
+ await self.im_client.send_message(
+ target_context,
f"❌ Error showing settings: {str(e)}"
)
- async def handle_callback_query(self, callback_query):
+ async def handle_callback_query(self, context: MessageContext, callback_data: str):
"""Handle inline keyboard callbacks"""
try:
- user_id = callback_query.from_user.id
- data = callback_query.data
+ # Handle command button clicks from /start message
+ if callback_data.startswith("cmd_"):
+ command = callback_data.replace("cmd_", "")
+ logger.info(f"Executing command via button click: {command}")
+
+ # Execute the corresponding command handler
+ if command in self.command_handlers:
+ handler = self.command_handlers[command]
+ await handler(context, "")
+ else:
+ await self.im_client.send_message(context, f"❌ Unknown command: {command}")
+ return
- # Check permission
- if not self.telegram_bot.check_permission(user_id):
- await callback_query.answer("You are not authorized to use this bot.")
+ # Handle info button clicks from /start message
+ elif callback_data.startswith("info_"):
+ if callback_data == "info_how_it_works":
+ info_text = """📚 *How Claude Code Bot Works:*
+
+🔄 *Message Processing:*
+• Send any message to add it to your personal queue
+• Messages are processed _automatically_ in order
+• Each message is sent to Claude Code for execution
+
+⚡ *Queue Management:*
+• Only *one message per user* is processed at a time
+• Use 🚀 Execute Queue to manually trigger processing
+• Use 🗑️ Clear Queue to remove all pending messages
+
+📁 *Directory Control:*
+• Set working directory with `/set_cwd <path>`
+• All Claude Code operations use your specified directory
+• Default directory can be configured in settings
+
+🎛️ *Personalization:*
+• Use ⚙️ Settings to customize message visibility
+• Hide `system messages`, `responses`, or `results` as needed
+• Settings are saved _per user_"""
+
+ elif callback_data == "info_all_commands":
+ info_text = """📖 *All Available Commands:*
+
+*📊 Status & Queue:*
+• `/status` or 📊 - Show current queue status
+• `/queue` or 📋 - Display all messages in queue
+• `/execute` or 🚀 - Manually process queue
+• `/clear` or 🗑️ - Clear all queued messages
+
+*📁 Directory Management:*
+• `/cwd` or 📁 - Show current working directory
+• `/set_cwd <path>` - Change working directory
+
+*⚙️ Configuration:*
+• `/settings` or ⚙️ - Open personalization settings
+• `/start` - Show this welcome screen
+
+*💬 Three Ways to Use:*
+• *Direct commands*: Use slash commands like `/status`
+• *Button clicks*: Click buttons in this interface
+• *Natural messages*: Just type your request normally
+• *Channel mentions*: Type `@BotName your message here`
+
+_Tip: All commands work in DMs, channels, and threads!_"""
+
+ await self.im_client.send_message(context, info_text, parse_mode='markdown')
return
- if data.startswith("toggle_msg_"):
+ # Handle settings toggle buttons (existing functionality)
+ elif callback_data.startswith("toggle_msg_"):
# Toggle message type visibility
- msg_type = data.replace("toggle_msg_", "")
- is_hidden = self.settings_manager.toggle_hidden_message_type(user_id, msg_type)
+ msg_type = callback_data.replace("toggle_msg_", "")
+ is_hidden = self.settings_manager.toggle_hidden_message_type(context.user_id, msg_type)
- # Update the keyboard with 2x2 layout
- user_settings = self.settings_manager.get_user_settings(user_id)
+ # Update the keyboard
+ user_settings = self.settings_manager.get_user_settings(context.user_id)
message_types = self.settings_manager.get_available_message_types()
display_names = self.settings_manager.get_message_type_display_names()
- keyboard = []
buttons = []
for mt in message_types:
is_hidden_now = mt in user_settings.hidden_message_types
checkbox = "☑️" if is_hidden_now else "⬜"
display_name = display_names.get(mt, mt)
- button_text = f"{checkbox} Hide {display_name}"
- callback_data = f"toggle_msg_{mt}"
- buttons.append(InlineKeyboardButton(button_text, callback_data=callback_data))
-
- # Arrange buttons in 2x2 layout
- for i in range(0, len(buttons), 2):
- row = buttons[i:i+2]
- keyboard.append(row)
+ button = InlineButton(
+ text=f"{checkbox} Hide {display_name}",
+ callback_data=f"toggle_msg_{mt}"
+ )
+ buttons.append([button])
- keyboard.append([InlineKeyboardButton("ℹ️ About Message Types", callback_data="info_msg_types")])
+ buttons.append([InlineButton("ℹ️ About Message Types", callback_data="info_msg_types")])
- reply_markup = InlineKeyboardMarkup(keyboard)
+ keyboard = InlineKeyboard(buttons=buttons)
# Update message
- await callback_query.edit_message_reply_markup(reply_markup=reply_markup)
+ if context.message_id:
+ await self.im_client.edit_message(
+ context,
+ context.message_id,
+ keyboard=keyboard
+ )
- # Answer callback with display name
- display_names = self.settings_manager.get_message_type_display_names()
+ # Answer callback
display_name = display_names.get(msg_type, msg_type)
action = "hidden" if is_hidden else "shown"
- await callback_query.answer(f"{display_name} messages are now {action}")
- elif data == "info_msg_types":
+ # Platform-specific callback answering
+ if self.config.platform == "telegram":
+ # For Telegram, we need the actual callback query object
+ # This is a limitation we'll need to address
+ pass
+ elif self.config.platform == "slack":
+ # For Slack, we might send an ephemeral message
+ await self.im_client.send_message(
+ context,
+ f"{display_name} messages are now {action}",
+ parse_mode='markdown'
+ )
+
+ elif callback_data == "info_msg_types":
# Show info about message types
info_text = (
"📋 *Message Types Info:*\n\n"
- "• *System* \- System initialization and status messages\n"
- "• *Response* \- Tool execution responses and results\n"
- "• *Assistant* \- Claude's messages and explanations\n"
- "• *Result* \- Final execution results and summaries\n\n"
- "Hidden messages won't be sent to Telegram\."
+ "• *System* - System initialization and status messages\n"
+ "• *Response* - Tool execution responses and results\n"
+ "• *Assistant* - Claude's messages and explanations\n"
+ "• *Result* - Final execution results and summaries\n\n"
+ "Hidden messages won't be sent to your IM platform."
)
- await callback_query.answer()
- await callback_query.message.reply_text(info_text, parse_mode='MarkdownV2')
+
+ # Send as new message
+ await self.im_client.send_message(context, info_text, parse_mode='markdown')
except Exception as e:
logger.error(f"Error handling callback query: {e}")
- await callback_query.answer(f"Error: {str(e)}")
+ await self.im_client.send_message(context, f"Error: {str(e)}")
async def periodic_cleanup(self):
"""Periodic cleanup of inactive sessions"""
@@ -381,12 +565,12 @@ class Controller:
def run(self):
"""Run the controller"""
- logger.info("Starting Claude Proxy Controller...")
+ logger.info(f"Starting Claude Proxy Controller with {self.config.platform} platform...")
# Start cleanup task
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.cleanup_task = loop.create_task(self.periodic_cleanup())
- # Run telegram bot
- self.telegram_bot.run()
\ No newline at end of file
+ # Run the IM client
+ self.im_client.run()
\ No newline at end of file
diff --git a/docs/SLACK_SETUP.md b/docs/SLACK_SETUP.md
new file mode 100644
index 000000000..48ba77f9d
--- /dev/null
+++ b/docs/SLACK_SETUP.md
@@ -0,0 +1,514 @@
+# Slack Bot Setup Guide
+
+This guide will walk you through setting up a Slack bot for the Claude Code Remote Control Bot.
+
+## Prerequisites
+
+- Admin access to a Slack workspace
+- Python 3.6 or higher installed
+- Claude Code Remote Control Bot cloned and dependencies installed
+
+## Step 1: Create a Slack App
+
+1. Go to [https://api.slack.com/apps](https://api.slack.com/apps)
+2. Click **"Create New App"** → **"From scratch"**
+3. Enter an app name (e.g., "Claude Code Bot")
+4. Select your workspace
+5. Click **"Create App"**
+
+## Step 2: Configure Bot Token Scopes
+
+1. In your app's settings, navigate to **"OAuth & Permissions"** in the sidebar
+2. Scroll down to **"Scopes"** → **"Bot Token Scopes"**
+3. Add the following OAuth scopes:
+ - `channels:history` - View messages in public channels
+ - `channels:read` - View basic information about public channels
+ - `chat:write` - Send messages as bot
+ - `im:history` - View direct message history
+ - `im:read` - View basic information about direct messages
+ - `im:write` - Send direct messages
+ - `app_mentions:read` - View messages that mention your bot
+ - `users:read` - View basic information about users (required for welcome messages)
+
+## Step 3: Install App to Workspace
+
+1. Still in **"OAuth & Permissions"**, scroll to the top
+2. Click **"Install to Workspace"**
+3. Review the permissions and click **"Allow"**
+4. Copy the **Bot User OAuth Token** (starts with `xoxb-`)
+ - Save this as `SLACK_BOT_TOKEN` in your `.env` file
+
+## Step 4: Enable Socket Mode (Recommended)
+
+Socket Mode allows your bot to connect without exposing a public URL.
+
+1. Go to **"Socket Mode"** in the sidebar
+2. Toggle **"Enable Socket Mode"** to On
+3. You'll be prompted to generate an app-level token:
+ - Token Name: "Socket Mode Token"
+ - Add scope: `connections:write`
+ - Click **"Generate"**
+4. Copy the **App-Level Token** (starts with `xapp-`)
+ - Save this as `SLACK_APP_TOKEN` in your `.env` file
+
+## Step 5: Configure Event Subscriptions
+
+1. Go to **"Event Subscriptions"** in the sidebar
+2. Toggle **"Enable Events"** to On
+3. Under **"Subscribe to bot events"**, add:
+ - `message.channels` - Messages in public channels
+ - `message.im` - Direct messages
+ - `app_mention` - When someone mentions your bot
+4. Click **"Save Changes"**
+
+## Step 6: Configure Native Slash Commands (Recommended)
+
+Native Slack slash commands provide the best user experience with autocomplete and help text. Here's a detailed step-by-step guide:
+
+### 6.1 Access Slash Commands Configuration
+
+**详细步骤**:
+1. **打开浏览器** 并导航到 [https://api.slack.com/apps](https://api.slack.com/apps)
+2. **登录你的 Slack 账户** (如果尚未登录)
+3. **找到你的 App**: 在 "Your Apps" 列表中找到之前创建的 Claude Code Bot 应用
+4. **点击应用名称** 进入应用管理界面
+5. **导航到斜杠命令**: 在左侧边栏中,找到 **"Features"** 分组,点击 **"Slash Commands"**
+6. **查看当前状态**: 你会看到标题为 "Slash Commands" 的页面,显示任何现有的命令
+
+**页面说明**:
+- 如果是新应用,页面会显示 "You haven't created any slash commands yet"
+- 右上角有绿色的 **"Create New Command"** 按钮
+- 现有命令会以列表形式显示,每个命令都有编辑选项
+
+### 6.2 创建命令的通用流程
+
+**每个命令的创建步骤**:
+1. **点击 "Create New Command"** 按钮 (页面右上角的绿色按钮)
+2. **填写命令表单** (详见下方每个命令的具体配置)
+3. **点击 "Save"** 保存命令
+4. **等待确认** - Slack 会显示 "Your slash command was saved!" 的成功消息
+5. **返回命令列表** 验证命令已创建
+
+**重要提醒**:
+- ⚠️ 每次只能创建一个命令,需要重复8次这个过程
+- ⚠️ 命令名称不能重复,不能包含空格
+- ⚠️ 所有字段都区分大小写
+
+### 6.3 推荐创建的命令 (逐一配置)
+
+**配置原则**:
+- 所有命令的 **Request URL** 都留空 (我们使用 Socket Mode)
+- 所有命令都要勾选 **"Escape channels, users, and links"**
+- 按照下面的模板逐个创建,可以直接复制粘贴
+
+---
+
+#### 命令 1/8: `/claude-start`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-start
+Request URL: (留空)
+Short Description: Show welcome message and help
+Usage Hint: Get started with Claude Code bot
+```
+**操作步骤**:
+1. 点击 **"Create New Command"**
+2. 在 **"Command"** 字段填入: `/claude-start`
+3. **"Request URL"** 保持空白 (不要填任何内容)
+4. 在 **"Short Description"** 字段填入: `Show welcome message and help`
+5. 在 **"Usage Hint"** 字段填入: `Get started with Claude Code bot`
+6. ✅ **勾选** "Escape channels, users, and links" 复选框
+7. 点击 **"Save"** 按钮
+8. 看到绿色成功消息后点击 **"← Back to Slash Commands"**
+
+#### 命令 2/8: `/claude-status`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-status
+Request URL: (留空)
+Short Description: Show current queue status
+Usage Hint: Check queue and execution status
+```
+**重复上述步骤,将对应内容填入表单各字段**
+
+---
+
+#### 命令 3/8: `/claude-clear`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-clear
+Request URL: (留空)
+Short Description: Clear message queue
+Usage Hint: Clear all queued messages
+```
+
+---
+
+#### 命令 4/8: `/claude-cwd`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-cwd
+Request URL: (留空)
+Short Description: Show current working directory
+Usage Hint: Display current working directory
+```
+
+---
+
+#### 命令 5/8: `/claude-set-cwd`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-set-cwd
+Request URL: (留空)
+Short Description: Set working directory
+Usage Hint: Set working directory: /path/to/directory
+```
+
+---
+
+#### 命令 6/8: `/claude-queue`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-queue
+Request URL: (留空)
+Short Description: Show message queue
+Usage Hint: View messages in queue
+```
+
+---
+
+#### 命令 7/8: `/claude-settings`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-settings
+Request URL: (留空)
+Short Description: Configure personalization settings
+Usage Hint: Open personalization settings menu
+```
+
+---
+
+#### 命令 8/8: `/claude-execute`
+**📋 复制这些内容到表单**:
+```
+Command: /claude-execute
+Request URL: (留空)
+Short Description: Process queue manually
+Usage Hint: Manually trigger queue processing
+```
+
+**🎉 完成后**: 返回 Slash Commands 主页面,你应该看到所有8个命令都已列出。
+
+### 6.4 Important Configuration Notes
+
+- **Request URL**: Always leave this empty when using Socket Mode (recommended)
+- **Socket Mode Required**: These commands only work when Socket Mode is enabled (Step 4)
+- **Case Sensitive**: Command names are case-sensitive
+- **No Automation**: Currently, Slack doesn't provide an API to create slash commands programmatically - they must be created manually through the web interface
+- **3-Second Response**: The bot has 3 seconds to acknowledge slash commands (handled automatically)
+
+### 6.5 Verification
+
+After creating all commands:
+1. Go back to the main "Slash Commands" page
+2. You should see all 8 commands listed
+3. Each command should show "✅ Configured" status
+
+### 6.6 快速设置检查清单
+
+**逐项检查确保设置正确**:
+- [ ] 访问了 [https://api.slack.com/apps](https://api.slack.com/apps) 并选择了正确的应用
+- [ ] 导航到了 "Features" > "Slash Commands" 页面
+- [ ] 创建了 `/claude-start` 命令
+- [ ] 创建了 `/claude-status` 命令
+- [ ] 创建了 `/claude-clear` 命令
+- [ ] 创建了 `/claude-cwd` 命令
+- [ ] 创建了 `/claude-set-cwd` 命令
+- [ ] 创建了 `/claude-queue` 命令
+- [ ] 创建了 `/claude-settings` 命令
+- [ ] 创建了 `/claude-execute` 命令
+- [ ] 所有命令的 **Request URL** 都是空白的
+- [ ] 所有命令都勾选了 **"Escape channels, users, and links"**
+- [ ] 在 Slash Commands 主页面能看到全部8个命令列出
+
+### 6.7 常见问题排查
+
+#### ❌ 问题:命令创建后不显示自动完成
+**原因**: 应用可能需要重新安装到工作区
+**解决方案**:
+1. 前往 "OAuth & Permissions" 页面
+2. 点击 "Reinstall to Workspace"
+3. 重新授权应用
+
+#### ❌ 问题:输入 `/claude-` 没有命令提示
+**可能原因**:
+- 命令名称拼写错误 (检查是否有多余空格或字符)
+- 应用未正确安装到当前工作区
+- Socket Mode 未启用
+
+**解决步骤**:
+1. 检查命令列表,确认命令名称完全正确
+2. 确认 Socket Mode 已启用 (Step 4)
+3. 确认 bot 已添加到当前频道: `/invite @YourBotName`
+
+#### ❌ 问题:"This command doesn't exist" 错误
+**原因**: 命令配置有误或未保存成功
+**解决方案**:
+1. 回到 Slash Commands 页面验证命令确实存在
+2. 检查命令名称是否与输入完全匹配
+3. 尝试删除并重新创建该命令
+
+#### ❌ 问题:命令执行后无响应
+**原因**: Bot 应用可能未运行或连接有问题
+**解决方案**:
+1. 检查 bot 进程是否在运行
+2. 查看 bot 日志是否有错误信息
+3. 确认 `SLACK_APP_TOKEN` 和 `SLACK_BOT_TOKEN` 配置正确
+
+### 6.8 设置完成验证
+
+**测试步骤**:
+1. 在任意频道或 DM 中输入 `/claude-`
+2. 应该看到所有8个命令的自动完成列表
+3. 选择 `/claude-start` 并发送
+4. Bot 应该响应欢迎消息
+
+**预期结果**:
+- ✅ 命令自动完成正常工作
+- ✅ 命令执行后 bot 能正确响应
+- ✅ 在频道中使用命令会创建线程回复
+
+### 6.7 Automation Possibilities (Currently Limited)
+
+**Can Slash Commands Be Created Automatically?**
+
+Unfortunately, as of 2025, Slack does not provide an API to programmatically create slash commands. They must be created manually through the Slack App Management interface at [api.slack.com/apps](https://api.slack.com/apps).
+
+**Why No Automation?**
+- Slack considers slash commands part of the app's core configuration
+- Each command requires careful consideration of permissions and scope
+- Manual creation ensures proper security review
+- Prevents automated spam of command namespaces
+
+**Alternative Approaches:**
+- Use the existing `/claude-*` command pattern for consistency
+- Focus on @ mention + command syntax for dynamic commands
+- Consider using Slack's Block Kit for interactive menus instead of many commands
+
+**Future Possibilities:**
+- Slack may introduce API endpoints for slash command management
+- Consider using Slack's Workflow Builder for some automation needs
+- Monitor Slack's developer blog for new automation features
+
+## Step 7: Configure Your Environment
+
+Update your `.env` file with the following:
+
+```env
+# Set platform to slack
+IM_PLATFORM=slack
+
+# Slack configuration
+SLACK_BOT_TOKEN=xoxb-your-bot-token-here
+SLACK_APP_TOKEN=xapp-your-app-token-here
+
+# Optional: Default channel for all outputs
+SLACK_TARGET_CHANNEL=C1234567890
+```
+
+### Finding Channel IDs
+
+To find a channel ID:
+1. Right-click on the channel name in Slack
+2. Select **"View channel details"**
+3. Scroll to the bottom
+4. The Channel ID starts with `C` for public channels
+
+## Step 8: Invite Bot to Channels
+
+Before the bot can interact with a channel, you need to invite it:
+
+1. In Slack, go to the channel
+2. Type `/invite @YourBotName`
+3. Press Enter
+
+## Step 9: Start the Bot
+
+```bash
+python main.py
+```
+
+## Usage
+
+### Command Methods
+
+The bot supports multiple ways to use commands:
+
+#### 1. Native Slash Commands (Recommended)
+If you configured slash commands in Step 6:
+```
+/claude-start
+/claude-status
+/claude-cwd
+```
+- Provides autocomplete and help text
+- Works in any channel where the bot is invited
+- Most user-friendly experience
+
+#### 2. @ Mention + Command
+Mention the bot followed by a command:
+```
+@YourBotName /start
+@YourBotName /status
+@YourBotName /cwd
+```
+
+#### 3. Direct Message Commands
+In DMs with the bot, use commands directly:
+```
+/start
+/status
+/cwd
+```
+
+### In Channels
+- Mention the bot: `@YourBotName your message here`
+- The bot will create a thread for the conversation
+
+### In Direct Messages
+- Send any message directly to the bot
+- No mention needed in DMs
+
+### Commands
+All commands work the same as in Telegram:
+- `/start` - Show welcome message
+- `/execute` - Manually process queue
+- `/clear` - Clear message queue
+- `/status` - Show current status
+- `/queue` - Show messages in queue
+- `/cwd` - Show working directory
+- `/set_cwd <path>` - Set working directory
+- `/settings` - Configure message visibility
+
+## Thread Support
+
+The Slack bot automatically uses threads to organize conversations:
+- Each user's messages are grouped in a thread
+- Responses from Claude Code appear in the same thread
+- This keeps channel history clean and organized
+
+## Troubleshooting
+
+### Bot not responding
+1. Check that the bot is online (green dot in Slack)
+2. Verify the bot was invited to the channel
+3. Check logs for any error messages
+
+### Permission errors
+1. Ensure all required scopes are added
+2. Reinstall the app to workspace after adding scopes
+3. Verify tokens are correctly set in `.env`
+
+### Socket Mode issues
+1. Ensure `SLACK_APP_TOKEN` is set correctly
+2. Check that the app-level token has `connections:write` scope
+3. Verify Socket Mode is enabled in app settings
+
+### Slash Command Issues
+
+#### Slash commands not appearing in autocomplete
+**Symptoms:** When typing `/claude-`, no autocomplete suggestions appear
+**Solutions:**
+1. Verify slash commands were created successfully in app settings
+2. Check that the bot is installed in the workspace
+3. Try reinstalling the app to workspace
+4. Ensure you're in a channel where the bot is invited
+
+#### "Command not found" error
+**Symptoms:** Slack shows "Sorry, `/claude-start` didn't work. You might be looking for something else?"
+**Solutions:**
+1. Double-check command spelling in Slack App settings
+2. Ensure Socket Mode is enabled and connected
+3. Verify `SLACK_APP_TOKEN` is set correctly
+4. Check bot logs for connection errors
+5. Try restarting the bot application
+
+#### Slash commands timeout
+**Symptoms:** Slack shows "Timeout: Command failed to respond"
+**Solutions:**
+1. Check bot application is running and connected
+2. Verify Socket Mode connection is stable
+3. Look for errors in bot logs during command execution
+4. Ensure the bot responds within 3 seconds (handled automatically by our code)
+
+#### Commands work in DMs but not in channels
+**Symptoms:** Slash commands work in direct messages but fail in channels
+**Solutions:**
+1. Ensure bot is invited to the channel: `/invite @YourBotName`
+2. Check bot has necessary channel permissions
+3. Verify `channels:history` and `channels:read` scopes are added
+
+#### "This app doesn't have permission to respond" error
+**Symptoms:** Bot receives command but can't respond
+**Solutions:**
+1. Add missing OAuth scopes: `chat:write`, `im:write`
+2. Reinstall app to workspace after adding scopes
+3. Check `SLACK_BOT_TOKEN` is correctly set
+
+#### Slash commands show but execute as text
+**Symptoms:** Commands appear as regular messages instead of executing
+**Solutions:**
+1. Verify Socket Mode is enabled (not webhook mode)
+2. Check `_handle_slash_command` method is being called in logs
+3. Ensure command mapping in `slack_bot.py` is correct
+4. Restart the bot application
+
+### Debug Commands
+
+Use these methods to test if slash commands are working:
+
+#### Test in Direct Message
+1. Send a DM to the bot
+2. Try `/claude-start`
+3. Should work without @ mention
+
+#### Test in Channel with @ Mention
+1. In a channel where bot is invited
+2. Try `@YourBotName /start`
+3. Should create a thread with response
+
+#### Check Bot Status
+1. Look for "🟢 Online" indicator next to bot name
+2. If offline, check connection and tokens
+3. Restart bot if needed
+
+#### Verify Command Registration
+Check the bot logs for these messages on startup:
+```
+INFO - Starting Slack bot in Socket Mode...
+INFO - A new session has been established
+```
+
+## Alternative: Webhook Mode
+
+If you prefer to use webhooks instead of Socket Mode:
+
+1. Set up a public HTTPS endpoint
+2. Configure the Request URL in Event Subscriptions
+3. Add `SLACK_SIGNING_SECRET` to your `.env`
+4. Remove or leave empty `SLACK_APP_TOKEN`
+
+Note: Webhook mode requires a publicly accessible HTTPS endpoint, which is more complex to set up.
+
+## Security Considerations
+
+- Never commit tokens to version control
+- Use environment variables for all sensitive data
+- Regularly rotate your tokens
+- Only grant necessary permissions to the bot
+
+## Additional Resources
+
+- [Slack API Documentation](https://api.slack.com/)
+- [Python Slack SDK](https://slack.dev/python-slack-sdk/)
+- [Socket Mode Guide](https://api.slack.com/apis/connections/socket)
\ No newline at end of file
diff --git a/main.py b/main.py
index 1b995a142..05377b4a4 100644
--- a/main.py
+++ b/main.py
@@ -3,7 +3,7 @@ import os
import sys
import logging
from dotenv import load_dotenv
-from config import AppConfig
+from config.settings import AppConfig
from core.controller import Controller
# Load environment variables from .env file
diff --git a/modules/base_im_client.py b/modules/base_im_client.py
new file mode 100644
index 000000000..91f6427ca
--- /dev/null
+++ b/modules/base_im_client.py
@@ -0,0 +1,155 @@
+from abc import ABC, abstractmethod
+from typing import Optional, Callable, Dict, Any
+from dataclasses import dataclass
+
+
+@dataclass
+class MessageContext:
+ """Platform-agnostic message context"""
+ user_id: str
+ channel_id: str
+ thread_id: Optional[str] = None
+ message_id: Optional[str] = None
+ platform_specific: Optional[Dict[str, Any]] = None
+
+
+@dataclass
+class InlineButton:
+ """Platform-agnostic inline button"""
+ text: str
+ callback_data: str
+
+
+@dataclass
+class InlineKeyboard:
+ """Platform-agnostic inline keyboard"""
+ buttons: list[list[InlineButton]] # 2D array for row/column layout
+
+
+class BaseIMClient(ABC):
+ """Abstract base class for IM platform clients"""
+
+ def __init__(self, config: Any):
+ self.config = config
+
+ @abstractmethod
+ async def send_message(self, context: MessageContext, text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None) -> str:
+ """Send a text message
+
+ Args:
+ context: Message context (channel, thread, etc)
+ text: Message text
+ parse_mode: Optional formatting mode (markdown, html, etc)
+ reply_to: Optional message ID to reply to
+
+ Returns:
+ Message ID of sent message
+ """
+ pass
+
+ @abstractmethod
+ async def send_message_with_buttons(self, context: MessageContext, text: str,
+ keyboard: InlineKeyboard,
+ parse_mode: Optional[str] = None) -> str:
+ """Send a message with inline buttons
+
+ Args:
+ context: Message context
+ text: Message text
+ keyboard: Inline keyboard configuration
+ parse_mode: Optional formatting mode
+
+ Returns:
+ Message ID of sent message
+ """
+ pass
+
+ @abstractmethod
+ async def edit_message(self, context: MessageContext, message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None) -> bool:
+ """Edit an existing message
+
+ Args:
+ context: Message context
+ message_id: ID of message to edit
+ text: New text (if provided)
+ keyboard: New keyboard (if provided)
+
+ Returns:
+ Success status
+ """
+ pass
+
+ @abstractmethod
+ async def answer_callback(self, callback_id: str, text: Optional[str] = None,
+ show_alert: bool = False) -> bool:
+ """Answer a callback query from inline button
+
+ Args:
+ callback_id: Callback query ID
+ text: Optional notification text
+ show_alert: Show as alert popup
+
+ Returns:
+ Success status
+ """
+ pass
+
+ @abstractmethod
+ def register_handlers(self):
+ """Register platform-specific message and command handlers"""
+ pass
+
+ @abstractmethod
+ def run(self):
+ """Start the bot/client"""
+ pass
+
+ @abstractmethod
+ async def get_user_info(self, user_id: str) -> Dict[str, Any]:
+ """Get information about a user
+
+ Args:
+ user_id: Platform-specific user ID
+
+ Returns:
+ User information dict
+ """
+ pass
+
+ @abstractmethod
+ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
+ """Get information about a channel/chat
+
+ Args:
+ channel_id: Platform-specific channel ID
+
+ Returns:
+ Channel information dict
+ """
+ pass
+
+ # Callback registration methods
+ def register_callbacks(self,
+ on_message: Optional[Callable] = None,
+ on_command: Optional[Dict[str, Callable]] = None,
+ on_callback_query: Optional[Callable] = None,
+ **kwargs):
+ """Register callback functions for different events
+
+ Args:
+ on_message: Callback for text messages
+ on_command: Dict of command callbacks
+ on_callback_query: Callback for button clicks
+ **kwargs: Additional platform-specific callbacks
+ """
+ self.on_message_callback = on_message
+ self.on_command_callbacks = on_command or {}
+ self.on_callback_query_callback = on_callback_query
+
+ # Store any additional callbacks
+ for key, value in kwargs.items():
+ setattr(self, f"{key}_callback", value)
\ No newline at end of file
diff --git a/modules/base_im_config.py b/modules/base_im_config.py
new file mode 100644
index 000000000..410d2a8d3
--- /dev/null
+++ b/modules/base_im_config.py
@@ -0,0 +1,26 @@
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class BaseIMConfig(ABC):
+ """Abstract base class for IM platform configurations"""
+
+ @classmethod
+ @abstractmethod
+ def from_env(cls) -> 'BaseIMConfig':
+ """Create configuration from environment variables"""
+ pass
+
+ @abstractmethod
+ def validate(self) -> bool:
+ """Validate the configuration
+
+ Returns:
+ True if configuration is valid
+
+ Raises:
+ ValueError: If configuration is invalid
+ """
+ pass
\ No newline at end of file
diff --git a/modules/claude_client.py b/modules/claude_client.py
index 6127d2d34..46f78707b 100644
--- a/modules/claude_client.py
+++ b/modules/claude_client.py
@@ -71,7 +71,7 @@ class ClaudeClient:
# Get ClaudeCode's current working directory
cwd = self.options.cwd or os.getcwd()
-
+
# Normalize paths for consistent comparison
cwd = os.path.normpath(cwd)
full_path = os.path.normpath(full_path)
@@ -178,11 +178,13 @@ class ClaudeClient:
url_str = str(block.input["url"])
escaped_url = escape_markdown(url_str, version=2)
input_info.append(f"🌐 URL: `{escaped_url}`")
-
+
if "prompt" in block.input and block.input["prompt"]:
prompt_str = str(block.input["prompt"])
if len(prompt_str) > 100:
- escaped_prompt = escape_markdown(prompt_str[:100], version=2) + "\\.\\.\\."
+ escaped_prompt = (
+ escape_markdown(prompt_str[:100], version=2) + "\\.\\.\\."
+ )
else:
escaped_prompt = escape_markdown(prompt_str, version=2)
input_info.append(f"📝 Prompt: {escaped_prompt}")
@@ -195,7 +197,7 @@ class ClaudeClient:
else:
escaped_old = escape_markdown(old_str, version=2)
input_info.append(f"🔍 Old: `{escaped_old}`")
-
+
if "new_string" in block.input and block.input["new_string"]:
new_str = str(block.input["new_string"])
if len(new_str) > 50:
@@ -212,15 +214,17 @@ class ClaudeClient:
# Other tool-specific parameters
if "limit" in block.input and block.input["limit"]:
input_info.append(f"🔢 Limit: {block.input['limit']}")
-
+
if "offset" in block.input and block.input["offset"]:
input_info.append(f"📍 Offset: {block.input['offset']}")
# Task tool parameters
if "subagent_type" in block.input and block.input["subagent_type"]:
- escaped_agent = escape_markdown(str(block.input["subagent_type"]), version=2)
+ escaped_agent = escape_markdown(
+ str(block.input["subagent_type"]), version=2
+ )
input_info.append(f"🤖 Agent: `{escaped_agent}`")
-
+
if "plan" in block.input and block.input["plan"]:
plan_str = str(block.input["plan"])
if len(plan_str) > 100:
@@ -233,16 +237,18 @@ class ClaudeClient:
if "cell_id" in block.input and block.input["cell_id"]:
escaped_cell_id = escape_markdown(str(block.input["cell_id"]), version=2)
input_info.append(f"📊 Cell ID: `{escaped_cell_id}`")
-
+
if "cell_type" in block.input and block.input["cell_type"]:
- escaped_cell_type = escape_markdown(str(block.input["cell_type"]), version=2)
+ escaped_cell_type = escape_markdown(
+ str(block.input["cell_type"]), version=2
+ )
input_info.append(f"📝 Cell Type: `{escaped_cell_type}`")
# WebSearch parameters
if "allowed_domains" in block.input and block.input["allowed_domains"]:
domains_count = len(block.input["allowed_domains"])
input_info.append(f"✅ Allowed domains: {domains_count}")
-
+
if "blocked_domains" in block.input and block.input["blocked_domains"]:
domains_count = len(block.input["blocked_domains"])
input_info.append(f"🚫 Blocked domains: {domains_count}")
@@ -251,11 +257,11 @@ class ClaudeClient:
if "glob" in block.input and block.input["glob"]:
escaped_glob = escape_markdown(str(block.input["glob"]), version=2)
input_info.append(f"🎯 Glob: `{escaped_glob}`")
-
+
if "type" in block.input and block.input["type"]:
escaped_type = escape_markdown(str(block.input["type"]), version=2)
input_info.append(f"📄 Type: `{escaped_type}`")
-
+
if "output_mode" in block.input and block.input["output_mode"]:
escaped_mode = escape_markdown(str(block.input["output_mode"]), version=2)
input_info.append(f"📊 Output mode: `{escaped_mode}`")
@@ -266,11 +272,22 @@ class ClaudeClient:
# Handle content specifically based on tool type
# Tools that already show all their parameters don't need JSON
show_json = True
- no_json_tools = ["Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep", "WebFetch", "WebSearch"]
-
+ no_json_tools = [
+ "Bash",
+ "Read",
+ "Write",
+ "Edit",
+ "MultiEdit",
+ "LS",
+ "Glob",
+ "Grep",
+ "WebFetch",
+ "WebSearch",
+ ]
+
if block.name in no_json_tools:
show_json = False
-
+
if block.name == "TodoWrite":
# TodoWrite has complex todos array - show as markdown list
if "todos" in block.input and block.input["todos"]:
@@ -306,7 +323,11 @@ class ClaudeClient:
tool_info += (
f"\n• {status_emoji} {priority_emoji} {escaped_content}"
)
- elif "content" in block.input and block.input["content"] and block.name in ["Write", "Edit", "MultiEdit"]:
+ elif (
+ "content" in block.input
+ and block.input["content"]
+ and block.name in ["Write", "Edit", "MultiEdit"]
+ ):
# Show content in code block for file write operations
content = str(block.input["content"])
if len(content) > 300:
@@ -370,7 +391,7 @@ class ClaudeClient:
def _format_user_message(self, message: UserMessage) -> str:
"""Format UserMessage"""
- formatted_parts = ["👤 *User*"]
+ formatted_parts = ["👤 *Response*"]
content_parts = self._process_content_blocks(message.content)
formatted_parts.extend(content_parts)
return "\n\n".join(formatted_parts)
@@ -406,7 +427,9 @@ class ClaudeClient:
return True
return False
- async def stream_execute(self, prompt: str, on_message: Callable, user_id: int = None):
+ async def stream_execute(
+ self, prompt: str, on_message: Callable, user_id: int = None
+ ):
"""Execute query with streaming output"""
try:
async for message in query(prompt=prompt, options=self.options):
@@ -420,21 +443,23 @@ class ClaudeClient:
# Determine message type for filtering (simplified to main categories)
message_type = None
- if hasattr(message, '__class__'):
+ if hasattr(message, "__class__"):
class_name = message.__class__.__name__
- if class_name == 'SystemMessage':
- message_type = 'system'
- elif class_name == 'UserMessage':
- message_type = 'user' # This shows tool responses
- elif class_name == 'AssistantMessage':
- message_type = 'assistant'
- elif class_name == 'ResultMessage':
- message_type = 'result'
+ if class_name == "SystemMessage":
+ message_type = "system"
+ elif class_name == "UserMessage":
+ message_type = "user" # This shows tool responses
+ elif class_name == "AssistantMessage":
+ message_type = "assistant"
+ elif class_name == "ResultMessage":
+ message_type = "result"
formatted_message = self.format_message(message)
if formatted_message and formatted_message.strip():
await on_message(formatted_message, message_type)
except Exception as e:
logger.error(f"Error in streaming execution: {e}")
- await on_message(f"❌ Error: {str(e)}", 'system') # Error messages go to system category
+ await on_message(
+ f"❌ Error: {str(e)}", "system"
+ ) # Error messages go to system category
raise
diff --git a/modules/im_factory.py b/modules/im_factory.py
new file mode 100644
index 000000000..c4fa83259
--- /dev/null
+++ b/modules/im_factory.py
@@ -0,0 +1,52 @@
+import logging
+from typing import Union
+
+from .base_im_client import BaseIMClient
+from .telegram_bot import TelegramBot
+from .slack_bot import SlackBot
+from config.settings import AppConfig, TelegramConfig, SlackConfig
+
+logger = logging.getLogger(__name__)
+
+
+class IMFactory:
+ """Factory class to create the appropriate IM client based on platform"""
+
+ @staticmethod
+ def create_client(config: AppConfig) -> BaseIMClient:
+ """Create and return the appropriate IM client based on configuration
+
+ Args:
+ config: Application configuration
+
+ Returns:
+ Instance of platform-specific IM client
+
+ Raises:
+ ValueError: If platform is not supported
+ """
+ platform = config.platform.lower()
+
+ if platform == "telegram":
+ if not config.telegram:
+ raise ValueError("Telegram configuration not found")
+ logger.info("Creating Telegram client")
+ return TelegramBot(config.telegram)
+
+ elif platform == "slack":
+ if not config.slack:
+ raise ValueError("Slack configuration not found")
+ logger.info("Creating Slack client")
+ return SlackBot(config.slack)
+
+ else:
+ raise ValueError(f"Unsupported IM platform: {platform}")
+
+ @staticmethod
+ def get_supported_platforms() -> list[str]:
+ """Get list of supported platforms
+
+ Returns:
+ List of supported platform names
+ """
+ return ["telegram", "slack"]
\ No newline at end of file
diff --git a/modules/slack_bot.py b/modules/slack_bot.py
new file mode 100644
index 000000000..84fb192e2
--- /dev/null
+++ b/modules/slack_bot.py
@@ -0,0 +1,487 @@
+import asyncio
+import logging
+from typing import Dict, Any, Optional, Callable
+from slack_sdk.web.async_client import AsyncWebClient
+from slack_sdk.socket_mode.aiohttp import SocketModeClient
+from slack_sdk.socket_mode.request import SocketModeRequest
+from slack_sdk.socket_mode.response import SocketModeResponse
+from slack_sdk.errors import SlackApiError
+
+from .base_im_client import BaseIMClient, MessageContext, InlineKeyboard, InlineButton
+from config.settings import SlackConfig
+
+logger = logging.getLogger(__name__)
+
+
+class SlackBot(BaseIMClient):
+ """Slack implementation of the IM client"""
+
+ def __init__(self, config: SlackConfig):
+ super().__init__(config)
+ self.config = config
+ self.web_client = None
+ self.socket_client = None
+
+ # Store thread timestamps for conversation continuity
+ self.thread_timestamps: Dict[str, str] = {}
+
+ # Store callback handlers
+ self.command_handlers: Dict[str, Callable] = {}
+ self.slash_command_handlers: Dict[str, Callable] = {}
+
+ def _ensure_clients(self):
+ """Ensure web and socket clients are initialized"""
+ if self.web_client is None:
+ self.web_client = AsyncWebClient(token=self.config.bot_token)
+
+ if self.socket_client is None and self.config.app_token:
+ self.socket_client = SocketModeClient(
+ app_token=self.config.app_token,
+ web_client=self.web_client
+ )
+
+ async def send_message(self, context: MessageContext, text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None) -> str:
+ """Send a message to Slack"""
+ self._ensure_clients()
+ try:
+ # Prepare message kwargs
+ kwargs = {
+ 'channel': context.channel_id,
+ 'text': text
+ }
+
+ # Handle thread replies
+ if context.thread_id:
+ kwargs['thread_ts'] = context.thread_id
+ # Optionally broadcast to channel
+ if context.platform_specific and context.platform_specific.get('reply_broadcast'):
+ kwargs['reply_broadcast'] = True
+
+ # Handle formatting
+ if parse_mode == 'markdown':
+ kwargs['mrkdwn'] = True
+
+ # Send message
+ response = await self.web_client.chat_postMessage(**kwargs)
+
+ # Store thread timestamp for future replies
+ if not context.thread_id and response['ts']:
+ thread_key = f"{context.channel_id}:{context.user_id}"
+ self.thread_timestamps[thread_key] = response['ts']
+
+ return response['ts']
+
+ except SlackApiError as e:
+ logger.error(f"Error sending Slack message: {e}")
+ raise
+
+ async def send_message_with_buttons(self, context: MessageContext, text: str,
+ keyboard: InlineKeyboard,
+ parse_mode: Optional[str] = None) -> str:
+ """Send a message with interactive buttons"""
+ self._ensure_clients()
+ try:
+ # Convert our generic keyboard to Slack blocks
+ blocks = [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn" if parse_mode == 'markdown' else "plain_text",
+ "text": text
+ }
+ }
+ ]
+
+ # Add action blocks for buttons
+ for row_idx, row in enumerate(keyboard.buttons):
+ elements = []
+ for button in row:
+ elements.append({
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": button.text
+ },
+ "action_id": button.callback_data,
+ "value": button.callback_data
+ })
+
+ blocks.append({
+ "type": "actions",
+ "block_id": f"actions_{row_idx}",
+ "elements": elements
+ })
+
+ # Prepare message kwargs
+ kwargs = {
+ 'channel': context.channel_id,
+ 'blocks': blocks,
+ 'text': text # Fallback text
+ }
+
+ # Handle thread replies
+ if context.thread_id:
+ kwargs['thread_ts'] = context.thread_id
+
+ response = await self.web_client.chat_postMessage(**kwargs)
+ return response['ts']
+
+ except SlackApiError as e:
+ logger.error(f"Error sending Slack message with buttons: {e}")
+ raise
+
+ async def edit_message(self, context: MessageContext, message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None) -> bool:
+ """Edit an existing Slack message"""
+ self._ensure_clients()
+ try:
+ kwargs = {
+ 'channel': context.channel_id,
+ 'ts': message_id
+ }
+
+ if text:
+ kwargs['text'] = text
+
+ if keyboard:
+ # Convert keyboard to blocks (similar to send_message_with_buttons)
+ blocks = []
+ if text:
+ blocks.append({
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": text
+ }
+ })
+
+ for row_idx, row in enumerate(keyboard.buttons):
+ elements = []
+ for button in row:
+ elements.append({
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": button.text
+ },
+ "action_id": button.callback_data,
+ "value": button.callback_data
+ })
+
+ blocks.append({
+ "type": "actions",
+ "block_id": f"actions_{row_idx}",
+ "elements": elements
+ })
+
+ kwargs['blocks'] = blocks
+
+ await self.web_client.chat_update(**kwargs)
+ return True
+
+ except SlackApiError as e:
+ logger.error(f"Error editing Slack message: {e}")
+ return False
+
+ async def answer_callback(self, callback_id: str, text: Optional[str] = None,
+ show_alert: bool = False) -> bool:
+ """Answer a Slack interactive callback"""
+ # In Slack, we don't have a direct equivalent to Telegram's answer_callback_query
+ # Instead, we typically update the message or send an ephemeral message
+ # This will be handled in the event processing
+ return True
+
+ def register_handlers(self):
+ """Register Slack event handlers"""
+ if not self.socket_client:
+ logger.warning("Socket mode client not configured, skipping handler registration")
+ return
+
+ # Register socket mode request handler
+ self.socket_client.socket_mode_request_listeners.append(self._handle_socket_mode_request)
+
+ async def _handle_socket_mode_request(self, client: SocketModeClient, req: SocketModeRequest):
+ """Handle incoming Socket Mode requests"""
+ try:
+ if req.type == "events_api":
+ # Handle Events API events
+ await self._handle_event(req.payload)
+ elif req.type == "slash_commands":
+ # Handle slash commands
+ await self._handle_slash_command(req.payload)
+ elif req.type == "interactive":
+ # Handle interactive components (buttons, etc.)
+ await self._handle_interactive(req.payload)
+
+ # Acknowledge the request
+ response = SocketModeResponse(envelope_id=req.envelope_id)
+ await client.send_socket_mode_response(response)
+
+ except Exception as e:
+ logger.error(f"Error handling socket mode request: {e}")
+ # Still acknowledge even on error
+ response = SocketModeResponse(envelope_id=req.envelope_id)
+ await client.send_socket_mode_response(response)
+
+ async def _handle_event(self, payload: Dict[str, Any]):
+ """Handle Events API events"""
+ event = payload.get("event", {})
+ event_type = event.get("type")
+
+ if event_type == "message":
+ # Ignore bot messages
+ if event.get("bot_id"):
+ return
+
+ # Check if this message contains a bot mention
+ # If it does, skip processing as it will be handled by app_mention event
+ text = event.get("text", "")
+ import re
+ if re.search(r'<@[\w]+>', text):
+ logger.info(f"Skipping message event with bot mention: '{text}'")
+ return
+
+ # Extract context
+ context = MessageContext(
+ user_id=event.get("user"),
+ channel_id=event.get("channel"),
+ thread_id=event.get("thread_ts"),
+ message_id=event.get("ts"),
+ platform_specific={
+ "team_id": payload.get("team_id"),
+ "event": event
+ }
+ )
+
+ # Handle slash commands in regular messages (only in DMs or direct messages)
+ if text.startswith("/"):
+ parts = text.split(maxsplit=1)
+ command = parts[0][1:] # Remove the /
+ args = parts[1] if len(parts) > 1 else ""
+
+ if command in self.on_command_callbacks:
+ handler = self.on_command_callbacks[command]
+ await handler(context, args)
+ return
+
+ # Handle as regular message
+ if self.on_message_callback:
+ await self.on_message_callback(context, text)
+
+ elif event_type == "app_mention":
+ # Handle @mentions
+ context = MessageContext(
+ user_id=event.get("user"),
+ channel_id=event.get("channel"),
+ thread_id=event.get("thread_ts"),
+ message_id=event.get("ts"),
+ platform_specific={
+ "team_id": payload.get("team_id"),
+ "event": event
+ }
+ )
+
+ # Remove the mention from the text
+ text = event.get("text", "")
+ import re
+ text = re.sub(r'<@[\w]+>', '', text).strip()
+
+ logger.info(f"App mention processed: original='{event.get('text')}', cleaned='{text}'")
+
+ # Check if this is a command after mention
+ if text.startswith("/"):
+ parts = text.split(maxsplit=1)
+ command = parts[0][1:] # Remove the /
+ args = parts[1] if len(parts) > 1 else ""
+
+ logger.info(f"Command detected: '{command}', available: {list(self.on_command_callbacks.keys())}")
+
+ if command in self.on_command_callbacks:
+ logger.info(f"Executing command handler for: {command}")
+ handler = self.on_command_callbacks[command]
+ await handler(context, args)
+ return
+ else:
+ logger.warning(f"Command '{command}' not found in callbacks")
+
+ # Handle as regular message
+ logger.info(f"Handling as regular message: '{text}'")
+ if self.on_message_callback:
+ await self.on_message_callback(context, text)
+
+ async def _handle_slash_command(self, payload: Dict[str, Any]):
+ """Handle native Slack slash commands"""
+ command = payload.get("command", "").lstrip("/")
+
+ # Map Slack slash commands to internal commands
+ command_mapping = {
+ 'claude-start': 'start',
+ 'claude-status': 'status',
+ 'claude-clear': 'clear',
+ 'claude-cwd': 'cwd',
+ 'claude-set-cwd': 'set_cwd',
+ 'claude-queue': 'queue',
+ 'claude-settings': 'settings',
+ 'claude-execute': 'execute'
+ }
+
+ # Get the actual command name
+ actual_command = command_mapping.get(command, command)
+
+ # Create context for slash command
+ context = MessageContext(
+ user_id=payload.get("user_id"),
+ channel_id=payload.get("channel_id"),
+ platform_specific=payload
+ )
+
+ # Send immediate acknowledgment to Slack
+ response_url = payload.get("response_url")
+
+ # Try to handle as registered command
+ if actual_command in self.on_command_callbacks:
+ handler = self.on_command_callbacks[actual_command]
+
+ # Send immediate "processing" response for long-running commands
+ if response_url and actual_command not in ['start', 'status', 'clear', 'cwd', 'queue']:
+ await self.send_slash_response(response_url, f"⏳ Processing `/{command}`...")
+
+ await handler(context, payload.get("text", ""))
+ elif actual_command in self.slash_command_handlers:
+ handler = self.slash_command_handlers[actual_command]
+ await handler(context, payload.get("text", ""))
+ else:
+ # Send response back to Slack for unknown command
+ if response_url:
+ available_commands = [f"`/{k}`" for k in command_mapping.keys()]
+ await self.send_slash_response(
+ response_url,
+ f"❌ Unknown command: `/{command}`\n\nAvailable commands:\n{chr(10).join(available_commands)}"
+ )
+
+ async def _handle_interactive(self, payload: Dict[str, Any]):
+ """Handle interactive components (buttons, etc.)"""
+ if payload.get("type") == "block_actions":
+ # Handle button clicks
+ user = payload.get("user", {})
+ actions = payload.get("actions", [])
+
+ for action in actions:
+ if action.get("type") == "button":
+ callback_data = action.get("action_id")
+
+ if self.on_callback_query_callback:
+ # Create a context for the callback
+ context = MessageContext(
+ user_id=user.get("id"),
+ channel_id=payload.get("channel", {}).get("id"),
+ message_id=payload.get("message", {}).get("ts"),
+ platform_specific={
+ "trigger_id": payload.get("trigger_id"),
+ "response_url": payload.get("response_url"),
+ "action": action,
+ "payload": payload
+ }
+ )
+
+ await self.on_callback_query_callback(context, callback_data)
+
+ def run(self):
+ """Run the Slack bot"""
+ if self.config.app_token:
+ # Socket Mode
+ logger.info("Starting Slack bot in Socket Mode...")
+
+ async def start():
+ self._ensure_clients()
+ self.register_handlers()
+ await self.socket_client.connect()
+ await asyncio.sleep(float("inf"))
+
+ asyncio.run(start())
+ else:
+ # Web API only mode (for development/testing)
+ logger.warning("No app token provided, running in Web API only mode")
+ # In this mode, you would typically run a web server to receive events
+ # For now, just keep the program running
+ try:
+ asyncio.run(asyncio.sleep(float("inf")))
+ except KeyboardInterrupt:
+ logger.info("Shutting down...")
+
+ async def get_user_info(self, user_id: str) -> Dict[str, Any]:
+ """Get information about a Slack user"""
+ self._ensure_clients()
+ try:
+ response = await self.web_client.users_info(user=user_id)
+ user = response['user']
+ return {
+ 'id': user['id'],
+ 'name': user.get('name'),
+ 'real_name': user.get('real_name'),
+ 'display_name': user.get('profile', {}).get('display_name'),
+ 'email': user.get('profile', {}).get('email'),
+ 'is_bot': user.get('is_bot', False)
+ }
+ except SlackApiError as e:
+ logger.error(f"Error getting user info: {e}")
+ raise
+
+ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
+ """Get information about a Slack channel"""
+ self._ensure_clients()
+ try:
+ response = await self.web_client.conversations_info(channel=channel_id)
+ channel = response['channel']
+ return {
+ 'id': channel['id'],
+ 'name': channel.get('name'),
+ 'is_private': channel.get('is_private', False),
+ 'is_im': channel.get('is_im', False),
+ 'is_channel': channel.get('is_channel', False),
+ 'topic': channel.get('topic', {}).get('value'),
+ 'purpose': channel.get('purpose', {}).get('value')
+ }
+ except SlackApiError as e:
+ logger.error(f"Error getting channel info: {e}")
+ raise
+
+ def register_callbacks(self, on_message: Optional[Callable] = None,
+ on_command: Optional[Dict[str, Callable]] = None,
+ on_callback_query: Optional[Callable] = None,
+ **kwargs):
+ """Register callback functions for different events"""
+ super().register_callbacks(on_message, on_command, on_callback_query, **kwargs)
+
+ # Register command handlers
+ if on_command:
+ self.command_handlers.update(on_command)
+
+ # Register any slash command handlers passed in kwargs
+ if 'on_slash_command' in kwargs:
+ slash_commands = kwargs['on_slash_command']
+ if isinstance(slash_commands, dict):
+ self.slash_command_handlers.update(slash_commands)
+
+ async def get_or_create_thread(self, channel_id: str, user_id: str) -> Optional[str]:
+ """Get existing thread timestamp or return None for new thread"""
+ thread_key = f"{channel_id}:{user_id}"
+ return self.thread_timestamps.get(thread_key)
+
+ async def send_slash_response(self, response_url: str, text: str,
+ ephemeral: bool = True) -> bool:
+ """Send response to a slash command via response_url"""
+ try:
+ import aiohttp
+ async with aiohttp.ClientSession() as session:
+ await session.post(response_url, json={
+ "text": text,
+ "response_type": "ephemeral" if ephemeral else "in_channel"
+ })
+ return True
+ except Exception as e:
+ logger.error(f"Error sending slash command response: {e}")
+ return False
\ No newline at end of file
diff --git a/modules/telegram_bot.py b/modules/telegram_bot.py
index a940d2f5e..87f5f25ac 100644
--- a/modules/telegram_bot.py
+++ b/modules/telegram_bot.py
@@ -1,242 +1,104 @@
import asyncio
import logging
-from typing import Callable, Optional
-from telegram import Update, Bot, InlineKeyboardMarkup
+from typing import Callable, Optional, Dict, Any
+from telegram import Update, Bot, InlineKeyboardMarkup as TGInlineKeyboardMarkup, InlineKeyboardButton as TGInlineKeyboardButton
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler
from telegram.helpers import escape_markdown
from telegram.error import TelegramError
-from config import TelegramConfig
+from config.settings import TelegramConfig
+from .base_im_client import BaseIMClient, MessageContext, InlineKeyboard, InlineButton
logger = logging.getLogger(__name__)
-class TelegramBot:
+class TelegramBot(BaseIMClient):
def __init__(self, config: TelegramConfig):
- self.config = config
+ super().__init__(config)
self.application = Application.builder().token(config.bot_token).build()
- self.message_callback: Optional[Callable] = None
- self.execute_callback: Optional[Callable] = None
- self.status_callback: Optional[Callable] = None
- self.clear_callback: Optional[Callable] = None
- self.cwd_callback: Optional[Callable] = None
- self.set_cwd_callback: Optional[Callable] = None
- self.queue_callback: Optional[Callable] = None
- self.settings_callback: Optional[Callable] = None
- self.callback_query_handler: Optional[Callable] = None
-
- def check_permission(self, user_id: int) -> bool:
- """Check if user is allowed to use the bot"""
- if not self.config.allowed_users:
- return True
- return user_id in self.config.allowed_users
-
- async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /start command"""
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
- if not self.check_permission(user_id):
- await update.message.reply_text("Sorry, you are not authorized to use this bot.")
- return
-
- message_text = f"""Welcome to Claude Code Remote Control Bot!
-
-Your Chat ID: {chat_id}
-
-Commands:
-/start - Show this message and IDs
-/execute - Manually start processing queue
-/clear - Clear message queue
-/status - Show current status
-/queue - Show messages in queue
-/cwd - Show current working directory
-/set_cwd <path> - Set working directory
-/settings - Personalization settings
-
-How it works:
-• Send any message to add it to the queue
-• Messages are automatically processed in order
-• Claude Code executes each message sequentially"""
-
- # Use official escape function for the entire message
- escaped_message = escape_markdown(message_text, version=2)
+ # Store callback queries for answering
+ self._callback_queries: Dict[str, Any] = {}
+
+ async def handle_telegram_message(self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):
+ """Handle incoming text messages from Telegram"""
+ # Create MessageContext
+ context = MessageContext(
+ user_id=str(update.effective_user.id),
+ channel_id=str(update.effective_chat.id),
+ message_id=str(update.message.message_id),
+ platform_specific={'update': update, 'tg_context': tg_context}
+ )
- await update.message.reply_text(escaped_message, parse_mode='MarkdownV2')
-
- async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle incoming text messages"""
- if not self.check_permission(update.effective_user.id):
- return
-
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
message_text = update.message.text
- if self.message_callback:
- response = await self.message_callback(chat_id, user_id, message_text)
- if response:
- await update.message.reply_text(response)
-
- async def execute_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /execute command"""
- if not self.check_permission(update.effective_user.id):
- return
+ # Check if it's a command
+ if message_text.startswith('/'):
+ parts = message_text.split(maxsplit=1)
+ command = parts[0][1:] # Remove the /
+ args = parts[1] if len(parts) > 1 else ""
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
-
- if self.execute_callback:
- await self.execute_callback(chat_id, user_id)
+ if command in self.on_command_callbacks:
+ await self.on_command_callbacks[command](context, args)
+ elif self.on_message_callback:
+ await self.on_message_callback(context, message_text)
- async def clear_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /clear command"""
- if not self.check_permission(update.effective_user.id):
- return
-
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
+ async def handle_telegram_callback(self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):
+ """Handle callback queries from inline keyboards"""
+ query = update.callback_query
- if self.clear_callback:
- response = await self.clear_callback(chat_id, user_id)
- if response:
- await update.message.reply_text(response)
-
- async def status_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /status command"""
- if not self.check_permission(update.effective_user.id):
- return
-
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
+ # Store the query for later use in answer_callback
+ self._callback_queries[query.id] = query
- if self.status_callback:
- response = await self.status_callback(chat_id, user_id)
- if response:
- await update.message.reply_text(response)
-
- async def cwd_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /cwd command"""
- if not self.check_permission(update.effective_user.id):
- return
-
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
+ # Create MessageContext
+ context = MessageContext(
+ user_id=str(query.from_user.id),
+ channel_id=str(query.message.chat_id),
+ message_id=str(query.message.message_id),
+ platform_specific={'query': query, 'update': update, 'tg_context': tg_context, 'callback_id': query.id}
+ )
- if self.cwd_callback:
- response = await self.cwd_callback(chat_id, user_id)
- if response:
- await update.message.reply_text(response, parse_mode='MarkdownV2')
+ if self.on_callback_query_callback:
+ await self.on_callback_query_callback(context, query.data)
- async def set_cwd_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /set_cwd command"""
- if not self.check_permission(update.effective_user.id):
+ async def _wrap_command(self, command_name: str, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):
+ """Wrap a command handler to convert Update to MessageContext"""
+ if command_name not in self.on_command_callbacks:
return
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
-
- # Extract path from command
+ # Extract args
message_text = update.message.text
parts = message_text.split(maxsplit=1)
+ args = parts[1] if len(parts) > 1 else ""
- if len(parts) < 2:
- await update.message.reply_text("Usage: /set_cwd <path>")
- return
-
- new_path = parts[1].strip()
-
- if self.set_cwd_callback:
- response = await self.set_cwd_callback(chat_id, user_id, new_path)
- if response:
- await update.message.reply_text(response, parse_mode='MarkdownV2')
-
- async def queue_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /queue command"""
- if not self.check_permission(update.effective_user.id):
- return
-
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
-
- if self.queue_callback:
- response = await self.queue_callback(chat_id, user_id)
- if response:
- await update.message.reply_text(response)
-
- async def settings_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle /settings command"""
- if not self.check_permission(update.effective_user.id):
- return
-
- chat_id = update.effective_chat.id
- user_id = update.effective_user.id
+ # Create MessageContext
+ context = MessageContext(
+ user_id=str(update.effective_user.id),
+ channel_id=str(update.effective_chat.id),
+ message_id=str(update.message.message_id),
+ platform_specific={'update': update, 'tg_context': tg_context}
+ )
- if self.settings_callback:
- await self.settings_callback(chat_id, user_id)
-
- async def handle_callback_query(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle callback queries from inline keyboards"""
- if self.callback_query_handler:
- await self.callback_query_handler(update.callback_query)
-
- def register_callbacks(self,
- on_message: Callable = None,
- on_execute: Callable = None,
- on_status: Callable = None,
- on_clear: Callable = None,
- on_cwd: Callable = None,
- on_set_cwd: Callable = None,
- on_queue: Callable = None,
- on_settings: Callable = None,
- on_callback_query: Callable = None):
- """Register callback functions"""
- self.message_callback = on_message
- self.execute_callback = on_execute
- self.status_callback = on_status
- self.clear_callback = on_clear
- self.cwd_callback = on_cwd
- self.set_cwd_callback = on_set_cwd
- self.queue_callback = on_queue
- self.settings_callback = on_settings
- self.callback_query_handler = on_callback_query
+ await self.on_command_callbacks[command_name](context, args)
def setup_handlers(self):
"""Setup bot command and message handlers"""
- self.application.add_handler(CommandHandler("start", self.start))
- self.application.add_handler(CommandHandler("execute", self.execute_command))
- self.application.add_handler(CommandHandler("clear", self.clear_command))
- self.application.add_handler(CommandHandler("status", self.status_command))
- self.application.add_handler(CommandHandler("queue", self.queue_command))
- self.application.add_handler(CommandHandler("cwd", self.cwd_command))
- self.application.add_handler(CommandHandler("set_cwd", self.set_cwd_command))
- self.application.add_handler(CommandHandler("settings", self.settings_command))
- self.application.add_handler(CallbackQueryHandler(self.handle_callback_query))
+ # Register command handlers dynamically
+ for command in self.on_command_callbacks:
+ handler = lambda update, context, cmd=command: asyncio.create_task(
+ self._wrap_command(cmd, update, context)
+ )
+ self.application.add_handler(CommandHandler(command, handler))
+
+ # Register callback query handler
+ self.application.add_handler(CallbackQueryHandler(self.handle_telegram_callback))
+
+ # Register message handler
self.application.add_handler(
- MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message)
+ MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_telegram_message)
)
- async def send_message(self, chat_id: int, text: str, parse_mode: str = None):
- """Send message to specific chat"""
- bot = self.application.bot
-
- # Split long messages
- if len(text) > 4000:
- for i in range(0, len(text), 4000):
- await bot.send_message(
- chat_id=chat_id,
- text=text[i:i+4000],
- parse_mode=parse_mode if parse_mode != 'Markdown' else 'MarkdownV2'
- )
- await asyncio.sleep(0.1) # Avoid rate limiting
- else:
- await bot.send_message(
- chat_id=chat_id,
- text=text,
- parse_mode=parse_mode if parse_mode != 'Markdown' else 'MarkdownV2'
- )
-
- async def send_settings_message(self, chat_id: int, text: str, reply_markup: InlineKeyboardMarkup):
+ async def send_settings_message(self, chat_id: int, text: str, reply_markup: TGInlineKeyboardMarkup):
"""Send message with inline keyboard"""
bot = self.application.bot
await bot.send_message(
@@ -349,4 +211,183 @@ How it works:
break
retry_delay = min(retry_delay * 1.5, 60) # Exponential backoff, max 60s
- attempt += 1
\ No newline at end of file
+ attempt += 1
+
+ # Implementation of BaseIMClient abstract methods
+
+ async def send_message(self, context: MessageContext, text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None) -> str:
+ """Send a text message - BaseIMClient implementation"""
+ bot = self.application.bot
+
+ # Convert MessageContext to Telegram chat_id
+ chat_id = int(context.channel_id)
+
+ # Handle thread_id as reply_to_message_id in Telegram
+ kwargs = {
+ 'chat_id': chat_id,
+ 'text': text
+ }
+
+ if parse_mode:
+ kwargs['parse_mode'] = parse_mode if parse_mode != 'markdown' else 'MarkdownV2'
+
+ if reply_to or context.thread_id:
+ kwargs['reply_to_message_id'] = int(reply_to or context.thread_id)
+
+ try:
+ message = await bot.send_message(**kwargs)
+ return str(message.message_id)
+ except TelegramError as e:
+ logger.error(f"Error sending message: {e}")
+ raise
+
+ async def send_message_with_buttons(self, context: MessageContext, text: str,
+ keyboard: InlineKeyboard,
+ parse_mode: Optional[str] = None) -> str:
+ """Send a message with inline buttons - BaseIMClient implementation"""
+ bot = self.application.bot
+
+ # Convert our generic keyboard to Telegram keyboard
+ tg_keyboard = []
+ for row in keyboard.buttons:
+ tg_row = []
+ for button in row:
+ tg_button = TGInlineKeyboardButton(
+ text=button.text,
+ callback_data=button.callback_data
+ )
+ tg_row.append(tg_button)
+ tg_keyboard.append(tg_row)
+
+ reply_markup = TGInlineKeyboardMarkup(tg_keyboard)
+
+ chat_id = int(context.channel_id)
+
+ try:
+ message = await bot.send_message(
+ chat_id=chat_id,
+ text=text,
+ parse_mode=parse_mode if parse_mode != 'markdown' else 'MarkdownV2',
+ reply_markup=reply_markup
+ )
+ return str(message.message_id)
+ except TelegramError as e:
+ logger.error(f"Error sending message with buttons: {e}")
+ raise
+
+ async def edit_message(self, context: MessageContext, message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None) -> bool:
+ """Edit an existing message - BaseIMClient implementation"""
+ bot = self.application.bot
+ chat_id = int(context.channel_id)
+
+ try:
+ if text and keyboard:
+ # Convert keyboard
+ tg_keyboard = []
+ for row in keyboard.buttons:
+ tg_row = []
+ for button in row:
+ tg_button = TGInlineKeyboardButton(
+ text=button.text,
+ callback_data=button.callback_data
+ )
+ tg_row.append(tg_button)
+ tg_keyboard.append(tg_row)
+
+ reply_markup = TGInlineKeyboardMarkup(tg_keyboard)
+
+ await bot.edit_message_text(
+ chat_id=chat_id,
+ message_id=int(message_id),
+ text=text,
+ reply_markup=reply_markup
+ )
+ elif text:
+ await bot.edit_message_text(
+ chat_id=chat_id,
+ message_id=int(message_id),
+ text=text
+ )
+ elif keyboard:
+ # Convert keyboard
+ tg_keyboard = []
+ for row in keyboard.buttons:
+ tg_row = []
+ for button in row:
+ tg_button = TGInlineKeyboardButton(
+ text=button.text,
+ callback_data=button.callback_data
+ )
+ tg_row.append(tg_button)
+ tg_keyboard.append(tg_row)
+
+ reply_markup = TGInlineKeyboardMarkup(tg_keyboard)
+
+ await bot.edit_message_reply_markup(
+ chat_id=chat_id,
+ message_id=int(message_id),
+ reply_markup=reply_markup
+ )
+
+ return True
+ except TelegramError as e:
+ logger.error(f"Error editing message: {e}")
+ return False
+
+ async def answer_callback(self, callback_id: str, text: Optional[str] = None,
+ show_alert: bool = False) -> bool:
+ """Answer a callback query - BaseIMClient implementation"""
+ # Get the stored callback query
+ if callback_id in self._callback_queries:
+ query = self._callback_queries[callback_id]
+ try:
+ await query.answer(text=text, show_alert=show_alert)
+ # Clean up
+ del self._callback_queries[callback_id]
+ return True
+ except TelegramError as e:
+ logger.error(f"Error answering callback: {e}")
+ return False
+ return False
+
+ def register_handlers(self):
+ """Register platform-specific handlers - BaseIMClient implementation"""
+ # This is already implemented as setup_handlers()
+ self.setup_handlers()
+
+ async def get_user_info(self, user_id: str) -> Dict[str, Any]:
+ """Get information about a user - BaseIMClient implementation"""
+ bot = self.application.bot
+
+ try:
+ user = await bot.get_chat(int(user_id))
+ return {
+ 'id': str(user.id),
+ 'username': user.username,
+ 'first_name': user.first_name,
+ 'last_name': user.last_name,
+ 'type': user.type
+ }
+ except TelegramError as e:
+ logger.error(f"Error getting user info: {e}")
+ raise
+
+ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
+ """Get information about a channel/chat - BaseIMClient implementation"""
+ bot = self.application.bot
+
+ try:
+ chat = await bot.get_chat(int(channel_id))
+ return {
+ 'id': str(chat.id),
+ 'title': chat.title,
+ 'type': chat.type,
+ 'username': chat.username
+ }
+ except TelegramError as e:
+ logger.error(f"Error getting channel info: {e}")
+ raise
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index e93c3bafe..790b95f51 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,4 +1,6 @@
claude-code-sdk>=0.0.19
python-telegram-bot>=20.0
python-dotenv>=1.0.0
-anyio>=4.0.0
\ No newline at end of file
+anyio>=4.0.0
+slack-sdk>=3.26.0
+aiohttp>=3.8.0
\ No newline at end of file
diff --git a/start.sh b/start.sh
index 585b15566..642ad901e 100755
--- a/start.sh
+++ b/start.sh
@@ -70,8 +70,7 @@ else
echo "ERROR: .env file not found!"
echo "Please create a .env file with required environment variables:"
echo " TELEGRAM_BOT_TOKEN=your_bot_token"
- echo " TARGET_CHAT_ID=your_chat_id (optional)"
- echo " ALLOWED_USERS=user_id1,user_id2 (optional)"
+ echo " TELEGRAM_TARGET_CHAT_ID=your_chat_id (optional)"
echo " CLAUDE_CWD=./_tmp (optional, default: ./_tmp)"
exit 1
fi