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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
Initial commit: Claude Proxy Telegram Bot
cyhhao6f3230d630ec
diff --git a/.env.example b/.env.examplenew file mode 100644index 000000000..9d91c93e1--- /dev/null+++ b/.env.example@@ -0,0 +1,20 @@+# Telegram Configuration+TELEGRAM_BOT_TOKEN=your_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=++# Optional: Comma-separated list of allowed Telegram user IDs+# Leave empty to allow all users+ALLOWED_USERS=++# Claude Configuration+CLAUDE_PERMISSION_MODE=bypassPermissions+CLAUDE_CWD=./_tmp+CLAUDE_CONTINUE_CONVERSATION=true+# Optional: Custom system prompt+CLAUDE_SYSTEM_PROMPT=++# Application Configuration+LOG_LEVEL=INFO\ No newline at end of filediff --git a/.gitignore b/.gitignorenew file mode 100644index 000000000..d1f400a0b--- /dev/null+++ b/.gitignore@@ -0,0 +1,163 @@+# Byte-compiled / optimized / DLL files+__pycache__/+*.py[cod]+*$py.class++# C extensions+*.so++# Distribution / packaging+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+share/python-wheels/+*.egg-info/+.installed.cfg+*.egg+MANIFEST++# PyInstaller+*.manifest+*.spec++# Installer logs+pip-log.txt+pip-delete-this-directory.txt++# Unit test / coverage reports+htmlcov/+.tox/+.nox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+*.py,cover+.hypothesis/+.pytest_cache/+cover/++# Translations+*.mo+*.pot++# Django stuff:+*.log+local_settings.py+db.sqlite3+db.sqlite3-journal++# Flask stuff:+instance/+.webassets-cache++# Scrapy stuff:+.scrapy++# Sphinx documentation+docs/_build/++# PyBuilder+.pybuilder/+target/++# Jupyter Notebook+.ipynb_checkpoints++# IPython+profile_default/+ipython_config.py++# pyenv+.python-version++# pipenv+Pipfile.lock++# poetry+poetry.lock++# pdm+.pdm.toml++# PEP 582+__pypackages__/++# Celery stuff+celerybeat-schedule+celerybeat.pid++# SageMath parsed files+*.sage.py++# Environments+.env+.venv+env/+venv/+ENV/+env.bak/+venv.bak/++# Spyder project settings+.spyderproject+.spyproject++# Rope project settings+.ropeproject++# mkdocs documentation+/site++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# Pyre type checker+.pyre/++# pytype static type analyzer+.pytype/++# Cython debug symbols+cython_debug/++# PyCharm+.idea/++# VSCode+.vscode/++# Project specific+*.log+claude_proxy.log+demolog.log+_tmp/+.DS_Store++# Config files with secrets+config/secrets.py+config/local_settings.py++# Session data+sessions/+*.session++# Temporary files+*.tmp+*.bak+*.swp+*~\ No newline at end of filediff --git a/README.md b/README.mdnew file mode 100644index 000000000..d7062c884--- /dev/null+++ b/README.md@@ -0,0 +1,98 @@+# Claude Proxy - Telegram Bot for Remote Claude Code Control++A modular system for controlling Claude Code through Telegram Bot.++## Quick Start++1. Install dependencies:+```bash+pip install -r requirements.txt+```++2. Create `.env` file from template:+```bash+cp .env.example .env+# Edit .env with your Telegram bot token+```++3. Run the bot:+```bash+./start.sh+# or+python main.py+```++## Configuration++### Environment Variables++- `TELEGRAM_BOT_TOKEN` (required): Your Telegram bot token from @BotFather+- `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`+- `CLAUDE_CWD`: Working directory for Claude Code (default: `./_tmp`)+- `LOG_LEVEL`: Logging level (default: `INFO`)++## Architecture++```+claude-proxy/+├── config/+│ └── 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+├── 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+```++## 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+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 filediff --git a/config/__init__.py b/config/__init__.pynew file mode 100644index 000000000..f714213a5--- /dev/null+++ b/config/__init__.py@@ -0,0 +1,3 @@+from .settings import AppConfig, TelegramConfig, ClaudeConfig++__all__ = ['AppConfig', 'TelegramConfig', 'ClaudeConfig']\ No newline at end of filediff --git a/config/settings.py b/config/settings.pynew file mode 100644index 000000000..e61d399e7--- /dev/null+++ b/config/settings.py@@ -0,0 +1,58 @@+import os+from dataclasses import dataclass+from typing import Optional+++@dataclass+class TelegramConfig:+ 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':+ bot_token = os.getenv("TELEGRAM_BOT_TOKEN")+ if not bot_token:+ raise ValueError("TELEGRAM_BOT_TOKEN environment variable is required")++ target_chat_id = None+ target_chat_id_str = os.getenv("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)+++@dataclass+class ClaudeConfig:+ permission_mode: str = "bypassPermissions"+ cwd: str = "./_tmp"+ continue_conversation: bool = True+ system_prompt: Optional[str] = None++ @classmethod+ def from_env(cls) -> 'ClaudeConfig':+ return cls(+ permission_mode=os.getenv("CLAUDE_PERMISSION_MODE", "bypassPermissions"),+ cwd=os.getenv("CLAUDE_CWD", "./_tmp"),+ continue_conversation=os.getenv("CLAUDE_CONTINUE_CONVERSATION", "true").lower() == "true",+ system_prompt=os.getenv("CLAUDE_SYSTEM_PROMPT")+ )+++@dataclass+class AppConfig:+ telegram: TelegramConfig+ claude: ClaudeConfig+ log_level: str = "INFO"++ @classmethod+ def from_env(cls) -> 'AppConfig':+ return cls(+ telegram=TelegramConfig.from_env(),+ claude=ClaudeConfig.from_env(),+ log_level=os.getenv("LOG_LEVEL", "INFO")+ )\ No newline at end of filediff --git a/core/__init__.py b/core/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/core/controller.py b/core/controller.pynew file mode 100644index 000000000..b38766dbb--- /dev/null+++ b/core/controller.py@@ -0,0 +1,245 @@+import asyncio+import logging+import os+from typing import Optional+from telegram.helpers import escape_markdown+from config import AppConfig+from modules.telegram_bot import TelegramBot+from modules.claude_client import ClaudeClient+from modules.session_manager import SessionManager+++logger = logging.getLogger(__name__)+++class Controller:+ def __init__(self, config: AppConfig):+ self.config = config+ self.telegram_bot = TelegramBot(config.telegram)+ self.claude_client = ClaudeClient(config.claude)+ self.session_manager = SessionManager()++ # Setup callbacks+ self._setup_callbacks()++ # Background task for cleanup+ self.cleanup_task: Optional[asyncio.Task] = None++ def _setup_callbacks(self):+ """Setup callback connections between modules"""+ self.telegram_bot.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+ )++ async def handle_user_message(self, chat_id: int, user_id: int, message: str) -> 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")++ # 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))++ # Don't return any message - user doesn't want confirmation+ return None+ except Exception as e:+ logger.error(f"Error handling message: {e}")+ return "Error adding message to queue."++ async def process_user_queue(self, chat_id: int, user_id: int):+ """Process all messages in user's queue sequentially"""+ try:+ # Mark as executing+ await self.session_manager.set_executing(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++ while await self.session_manager.has_messages(user_id):+ # Get next message+ message = await self.session_manager.get_next_message(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]}..."+ # )++ # Execute with Claude+ async def on_claude_message(claude_msg: str):+ # Send Claude's formatted output with MarkdownV2 parsing+ await self.telegram_bot.send_message(target_chat_id, claude_msg, parse_mode='MarkdownV2')++ try:+ await self.claude_client.stream_execute(message, on_claude_message)++ # Check if there are more messages+ remaining = await self.session_manager.has_messages(user_id)+ if remaining:+ await self.telegram_bot.send_message(+ target_chat_id,+ f"✅ Completed. Processing next message..."+ )+ else:+ await self.telegram_bot.send_message(+ target_chat_id,+ "✅ All messages processed!"+ )++ except Exception as e:+ logger.error(f"Error during Claude execution: {e}")+ await self.telegram_bot.send_message(+ target_chat_id,+ f"❌ Error processing message: {str(e)}\nStopping queue processing."+ )+ break++ # Small delay between messages+ await asyncio.sleep(1)++ 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,+ f"❌ Unexpected error: {str(e)}"+ )+ finally:+ await self.session_manager.set_executing(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++ if await self.session_manager.is_executing(user_id):+ await self.telegram_bot.send_message(+ target_chat_id,+ "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,+ "No messages in queue."+ )+ return++ # Start processing+ asyncio.create_task(self.process_user_queue(chat_id, user_id))++ async def handle_status(self, chat_id: int, user_id: int) -> str:+ """Handle status command"""+ try:+ status = await self.session_manager.get_status(user_id)+ return status+ except Exception as e:+ logger.error(f"Error getting status: {e}")+ return "Error getting status."++ async def handle_clear(self, chat_id: int, user_id: int) -> str:+ """Handle clear command"""+ try:+ response = await self.session_manager.clear_queue(user_id)+ logger.info(f"User {user_id} cleared queue")+ return response+ except Exception as e:+ logger.error(f"Error clearing queue: {e}")+ return "Error clearing queue."++ async def handle_cwd(self, chat_id: int, user_id: int) -> str:+ """Handle cwd command - show current working directory"""+ try:+ current_cwd = self.claude_client.options.cwd+ absolute_path = os.path.abspath(current_cwd)++ response_text = f"📁 Current Working Directory:\n{absolute_path}"++ # Check if directory exists+ if os.path.exists(absolute_path):+ response_text += "\n✅ Directory exists"+ else:+ response_text += "\n⚠️ Directory does not exist"++ return escape_markdown(response_text, version=2)+ except Exception as e:+ logger.error(f"Error getting cwd: {e}")+ return f"Error getting working directory: {str(e)}"++ async def handle_set_cwd(self, chat_id: int, user_id: int, new_path: str) -> str:+ """Handle set_cwd command - change working directory"""+ try:+ # Expand user path and get absolute path+ expanded_path = os.path.expanduser(new_path)+ absolute_path = os.path.abspath(expanded_path)++ # Check if directory exists+ if not os.path.exists(absolute_path):+ # Try to create it+ try:+ 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)}"++ 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)++ # Update Claude client options+ self.claude_client.options.cwd = absolute_path++ logger.info(f"User {user_id} changed cwd to: {absolute_path}")++ response_text = (+ f"✅ Working directory changed to:\n"+ f"{absolute_path}\n\n"+ f"All Claude Code commands will now execute in this directory."+ )+ return escape_markdown(response_text, version=2)++ except Exception as e:+ logger.error(f"Error setting cwd: {e}")+ return f"❌ Error setting working directory: {str(e)}"++ async def handle_queue(self, chat_id: int, user_id: int) -> 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+ except Exception as e:+ logger.error(f"Error getting queue details: {e}")+ return f"Error getting queue information: {str(e)}"++ async def periodic_cleanup(self):+ """Periodic cleanup of inactive sessions"""+ while True:+ try:+ await asyncio.sleep(3600) # Run every hour+ removed = await self.session_manager.cleanup_inactive_sessions()+ if removed > 0:+ logger.info(f"Cleaned up {removed} inactive sessions")+ except Exception as e:+ logger.error(f"Error in periodic cleanup: {e}")++ def run(self):+ """Run the controller"""+ logger.info("Starting Claude Proxy Controller...")++ # 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 filediff --git a/demo.py b/demo.pynew file mode 100644index 000000000..7163f2a4f--- /dev/null+++ b/demo.py@@ -0,0 +1,25 @@+import time+import anyio+from claude_code_sdk import (+ query,+ ClaudeCodeOptions,+ AssistantMessage,+ TextBlock,+ UserMessage,+)+++async def main():+ options = ClaudeCodeOptions(+ permission_mode="bypassPermissions", cwd="./_tmp", continue_conversation=True+ )++ async for message in query(+ prompt="写一个 Hello World 的 python3 程序并运行它", options=options+ ):+ print(message)+ print()+++if __name__ == "__main__":+ anyio.run(main)diff --git a/main.py b/main.pynew file mode 100644index 000000000..1b995a142--- /dev/null+++ b/main.py@@ -0,0 +1,48 @@+#!/usr/bin/env python3+import os+import sys+import logging+from dotenv import load_dotenv+from config import AppConfig+from core.controller import Controller++# Load environment variables from .env file+load_dotenv()+++def setup_logging(level: str = "INFO"):+ """Setup logging configuration"""+ logging.basicConfig(+ level=getattr(logging, level.upper()),+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',+ handlers=[+ logging.StreamHandler(sys.stdout),+ logging.FileHandler('claude_proxy.log')+ ]+ )+++def main():+ """Main entry point"""+ try:+ # Load configuration+ config = AppConfig.from_env()++ # Setup logging+ setup_logging(config.log_level)+ logger = logging.getLogger(__name__)++ logger.info("Starting Claude Proxy...")+ logger.info(f"Working directory: {config.claude.cwd}")++ # Create and run controller+ controller = Controller(config)+ controller.run()++ except Exception as e:+ logging.error(f"Failed to start: {e}")+ sys.exit(1)+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/modules/__init__.py b/modules/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/modules/claude_client.py b/modules/claude_client.pynew file mode 100644index 000000000..a77653f80--- /dev/null+++ b/modules/claude_client.py@@ -0,0 +1,417 @@+import logging+from typing import Callable+from claude_code_sdk import (+ query,+ ClaudeCodeOptions,+ SystemMessage,+ AssistantMessage,+ UserMessage,+ ResultMessage,+ TextBlock,+ ToolUseBlock,+ ToolResultBlock,+)+from telegram.helpers import escape_markdown+from config import ClaudeConfig+++logger = logging.getLogger(__name__)+++class ClaudeClient:+ def __init__(self, config: ClaudeConfig):+ self.config = config+ self.options = ClaudeCodeOptions(+ permission_mode=config.permission_mode,+ cwd=config.cwd,+ continue_conversation=config.continue_conversation,+ system_prompt=config.system_prompt,+ )++ def format_message(self, message) -> str:+ """Format different types of messages according to specified rules"""+ try:+ if isinstance(message, SystemMessage):+ return self._format_system_message(message)+ elif isinstance(message, AssistantMessage):+ return self._format_assistant_message(message)+ elif isinstance(message, UserMessage):+ return self._format_user_message(message)+ elif isinstance(message, ResultMessage):+ return self._format_result_message(message)+ else:+ return escape_markdown(+ f"🤔 Unknown message type: {type(message)}", version=2+ )+ except Exception as e:+ logger.error(f"Error formatting message: {e}")+ return escape_markdown(f"❌ Error formatting message: {str(e)}", version=2)++ def _process_content_blocks(self, content_blocks) -> list:+ """Process content blocks (TextBlock, ToolUseBlock) and return formatted parts"""+ formatted_parts = []++ for block in content_blocks:+ if isinstance(block, TextBlock):+ # Escape text content for MarkdownV2+ escaped_text = escape_markdown(block.text, version=2)+ formatted_parts.append(escaped_text)+ elif isinstance(block, ToolUseBlock):+ tool_info = self._format_tool_use_block(block)+ formatted_parts.append(tool_info)+ elif isinstance(block, ToolResultBlock):+ result_info = self._format_tool_result_block(block)+ formatted_parts.append(result_info)++ return formatted_parts++ def _get_relative_path(self, full_path: str) -> str:+ """Convert absolute path to relative path based on ClaudeCode cwd"""+ import os++ # Get ClaudeCode's current working directory+ cwd = self.options.cwd or os.getcwd()++ try:+ # If the path starts with cwd, make it relative+ if full_path.startswith(cwd):+ relative = os.path.relpath(full_path, cwd)+ # Use "./" prefix for current directory files+ if not relative.startswith("."):+ relative = "./" + relative+ return relative+ else:+ # If not under cwd, just return the path as is+ return full_path+ except:+ # Fallback to original path if any error+ return full_path++ def _format_tool_use_block(self, block: ToolUseBlock) -> str:+ """Format ToolUseBlock with specific adaptations for different tools"""+ escaped_name = escape_markdown(block.name, version=2)++ # Get tool emoji and format based on tool type+ if block.name.startswith("mcp__"):+ # MCP tools - unified handling+ tool_category = block.name.split("__")[1] if "__" in block.name else "mcp"+ emoji_map = {+ "devmcp": "🔧",+ "db": "🗃️",+ "log": "📊",+ "ops": "⚡",+ "human": "👤",+ }+ emoji = emoji_map.get(tool_category, "🔧")+ tool_info = f"{emoji} *MCP Tool*: `{escaped_name}`"+ else:+ # System tools - specific handling+ tool_emoji_map = {+ "Task": "🤖",+ "Bash": "💻",+ "Glob": "🔍",+ "Grep": "🔎",+ "LS": "📂",+ "Read": "📖",+ "Edit": "✏️",+ "MultiEdit": "📝",+ "Write": "📄",+ "NotebookRead": "📓",+ "NotebookEdit": "📓",+ "WebFetch": "🌐",+ "WebSearch": "🔍",+ "TodoWrite": "✅",+ "ExitPlanMode": "🚪",+ }+ emoji = tool_emoji_map.get(block.name, "🔧")+ tool_info = f"{emoji} *Tool*: `{escaped_name}`"++ # Add specific input info based on tool type+ input_info = []++ # File operations+ if "file_path" in block.input and block.input["file_path"]:+ relative_path = self._get_relative_path(block.input["file_path"])+ escaped_path = escape_markdown(relative_path, version=2)+ input_info.append(f"📁 File: `{escaped_path}`")++ # Path operations (for LS, Glob, etc.)+ if "path" in block.input and block.input["path"]:+ relative_path = self._get_relative_path(block.input["path"])+ escaped_path = escape_markdown(relative_path, version=2)+ input_info.append(f"📂 Path: `{escaped_path}`")++ # Command operations+ if "command" in block.input and block.input["command"]:+ escaped_cmd = escape_markdown(block.input["command"], version=2)+ input_info.append(f"💻 Command: `{escaped_cmd}`")++ # Description (for Bash tool)+ if "description" in block.input and block.input["description"]:+ escaped_desc = escape_markdown(block.input["description"], version=2)+ input_info.append(f"📝 Description: {escaped_desc}")++ # Pattern/Query operations+ if "pattern" in block.input and block.input["pattern"]:+ escaped_pattern = escape_markdown(block.input["pattern"], version=2)+ input_info.append(f"🔍 Pattern: `{escaped_pattern}`")++ if "query" in block.input and block.input["query"]:+ query_str = str(block.input["query"])+ if len(query_str) > 50:+ escaped_query = escape_markdown(query_str[:50], version=2) + "\\.\\.\\."+ else:+ escaped_query = escape_markdown(query_str, version=2)+ input_info.append(f"🔍 Query: `{escaped_query}`")++ # WebFetch specific parameters+ if "url" in block.input and block.input["url"]:+ 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) + "\\.\\.\\."+ else:+ escaped_prompt = escape_markdown(prompt_str, version=2)+ input_info.append(f"📝 Prompt: {escaped_prompt}")++ # Edit/MultiEdit specific parameters+ if "old_string" in block.input and block.input["old_string"]:+ old_str = str(block.input["old_string"])+ if len(old_str) > 50:+ escaped_old = escape_markdown(old_str[:50], version=2) + "\\.\\.\\."+ 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:+ escaped_new = escape_markdown(new_str[:50], version=2) + "\\.\\.\\."+ else:+ escaped_new = escape_markdown(new_str, version=2)+ input_info.append(f"✏️ New: `{escaped_new}`")++ # MultiEdit edits array+ if "edits" in block.input and block.input["edits"]:+ edits_count = len(block.input["edits"])+ input_info.append(f"📝 Edits: {edits_count} changes")++ # 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)+ 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:+ escaped_plan = escape_markdown(plan_str[:100], version=2) + "\\.\\.\\."+ else:+ escaped_plan = escape_markdown(plan_str, version=2)+ input_info.append(f"📋 Plan: {escaped_plan}")++ # NotebookEdit parameters+ 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)+ 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}")++ # Grep parameters+ 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}`")++ if input_info:+ tool_info += "\n" + "\n".join(input_info)++ # Handle content specifically based on tool type+ if block.name == "Bash":+ # Bash tool already shows command and description, don't show additional JSON+ pass+ elif block.name == "TodoWrite":+ # TodoWrite has complex todos array - show as markdown list+ if "todos" in block.input and block.input["todos"]:+ todos = block.input["todos"]+ todos_count = len(todos)+ tool_info += f"\n📋 {todos_count} todo items:"++ for todo in todos: # Show all todos, don't limit to 5+ status = todo.get("status", "pending")+ status_emoji = {+ "pending": "⏳",+ "in_progress": "🔄",+ "completed": "✅",+ }.get(status, "⏳")+ priority_emoji = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(+ todo.get("priority", "medium"), "🟡"+ )+ content = todo.get("content", "No content")[+ :50+ ] # Truncate long content+ if len(todo.get("content", "")) > 50:+ content += "..."++ # Add strikethrough for completed items using MarkdownV2 format+ if status == "completed":+ # Use MarkdownV2 strikethrough format: ~text~+ escaped_content = f"~{escape_markdown(content, version=2)}~"+ tool_info += (+ f"\n• {status_emoji} {priority_emoji} {escaped_content}"+ )+ else:+ escaped_content = escape_markdown(content, version=2)+ tool_info += (+ f"\n• {status_emoji} {priority_emoji} {escaped_content}"+ )+ elif "content" in block.input and block.input["content"]:+ # Show content in code block for file operations+ content = str(block.input["content"])+ if len(content) > 300:+ content = content[:300] + "..."+ tool_info += f"\n```\n{content}\n```"+ elif block.input and len(str(block.input)) < 200:+ # Show short input as JSON for simple cases+ import json++ try:+ input_json = json.dumps(block.input, indent=2, ensure_ascii=False)+ tool_info += f"\n```json\n{input_json}\n```"+ except:+ # Fallback for non-serializable input+ tool_info += f"\n```\n{str(block.input)}\n```"++ return tool_info++ def _format_tool_result_block(self, block: ToolResultBlock) -> str:+ """Format ToolResultBlock"""+ if block.is_error:+ emoji = "❌"+ status = "Error"+ else:+ emoji = "✅"+ status = "Success"++ # Get tool use ID (shortened)+ tool_id = (+ block.tool_use_id[:8] + "..."+ if len(block.tool_use_id) > 8+ else block.tool_use_id+ )+ escaped_tool_id = escape_markdown(tool_id, version=2)++ result_info = f"{emoji} *Tool Result*"++ # Format content in code block+ if block.content:+ content = str(block.content)+ if len(content) > 500:+ # Truncate very long content+ content = content[:500] + "..."+ result_info += f"\n```\n{content}\n```"++ return result_info++ def _format_system_message(self, message: SystemMessage) -> str:+ """Format SystemMessage"""+ cwd = message.data.get("cwd", "Unknown")+ escaped_cwd = escape_markdown(cwd, version=2)+ escaped_subtype = escape_markdown(message.subtype, version=2)+ return f"🔧 *System {escaped_subtype}*\n📁 Working directory: `{escaped_cwd}`\n✨ Ready to work\\!"++ def _format_assistant_message(self, message: AssistantMessage) -> str:+ """Format AssistantMessage"""+ formatted_parts = ["🤖 *Assistant*"]+ content_parts = self._process_content_blocks(message.content)+ formatted_parts.extend(content_parts)+ return "\n\n".join(formatted_parts)++ def _format_user_message(self, message: UserMessage) -> str:+ """Format UserMessage"""+ formatted_parts = ["👤 *User*"]+ content_parts = self._process_content_blocks(message.content)+ formatted_parts.extend(content_parts)+ return "\n\n".join(formatted_parts)++ def _format_result_message(self, message: ResultMessage) -> str:+ """Format ResultMessage"""+ # Convert duration to readable format+ total_seconds = (message.duration_ms + message.duration_api_ms) / 1000+ minutes = int(total_seconds // 60)+ seconds = int(total_seconds % 60)++ if minutes > 0:+ duration_str = f"{minutes}m {seconds}s"+ else:+ duration_str = f"{seconds}s"++ escaped_subtype = escape_markdown(message.subtype, version=2)+ escaped_duration = escape_markdown(duration_str, version=2)++ result_text = f"📊 *Result \\({escaped_subtype}\\)*\n"+ result_text += f"⏱️ Duration: {escaped_duration}\n"++ if message.result:+ escaped_result = escape_markdown(message.result, version=2)+ result_text += f"\n{escaped_result}\n"++ return result_text++ def _is_skip_message(self, message) -> bool:+ """Check if the message should be skipped"""+ if isinstance(message, AssistantMessage):+ if not message.content:+ return True+ elif isinstance(message, UserMessage):+ if not message.content:+ return True+ return False++ async def stream_execute(self, prompt: str, on_message: Callable):+ """Execute query with streaming output"""+ try:+ async for message in query(prompt=prompt, options=self.options):+ # Format message according to type++ print(message)+ print()++ if self._is_skip_message(message):+ continue++ formatted_message = self.format_message(message)+ if formatted_message and formatted_message.strip():+ await on_message(formatted_message)+ except Exception as e:+ logger.error(f"Error in streaming execution: {e}")+ await on_message(f"❌ Error: {str(e)}")+ raisediff --git a/modules/session_manager.py b/modules/session_manager.pynew file mode 100644index 000000000..c4db01f50--- /dev/null+++ b/modules/session_manager.py@@ -0,0 +1,168 @@+import asyncio+import logging+from dataclasses import dataclass, field+from typing import Dict, List, Optional+from datetime import datetime+++logger = logging.getLogger(__name__)+++@dataclass+class UserSession:+ user_id: int+ chat_id: int+ message_queue: List[str] = field(default_factory=list)+ is_executing: bool = False+ created_at: datetime = field(default_factory=datetime.now)+ last_activity: datetime = field(default_factory=datetime.now)++ def add_message(self, message: str):+ """Add message to queue"""+ self.message_queue.append(message)+ self.last_activity = datetime.now()+++ def get_next_message(self) -> Optional[str]:+ """Get and remove the next message from queue"""+ if self.message_queue:+ message = self.message_queue.pop(0)+ self.last_activity = datetime.now()+ return message+ return None++ def clear_queue(self):+ """Clear message queue"""+ self.message_queue.clear()+ self.last_activity = datetime.now()++ def get_status(self) -> str:+ """Get session status summary"""+ status = f"📊 Session Status\n"+ status += f"━━━━━━━━━━━━━━━━\n"+ status += f"User ID: {self.user_id}\n"+ status += f"Messages in queue: {len(self.message_queue)}\n"+ status += f"Status: {'🟢 Processing' if self.is_executing else '⭕ Idle'}\n"+ status += f"Last activity: {self.last_activity.strftime('%Y-%m-%d %H:%M:%S')}"++ if self.message_queue:+ status += "\n\n📋 Queued messages:"+ for idx, msg in enumerate(self.message_queue, 1):+ preview = msg[:50] + "..." if len(msg) > 50 else msg+ status += f"\n{idx}. {preview}"+ elif self.is_executing:+ status += "\n\n⏳ Currently processing your message..."+ else:+ status += "\n\n💤 No messages in queue"++ return status+++class SessionManager:+ def __init__(self):+ self.sessions: Dict[int, UserSession] = {}+ self._lock = asyncio.Lock()++ async def get_or_create_session(self, user_id: int, chat_id: int) -> UserSession:+ """Get existing session or create new one"""+ async with self._lock:+ if user_id not in self.sessions:+ self.sessions[user_id] = UserSession(user_id=user_id, chat_id=chat_id)+ logger.info(f"Created new session for user {user_id}")++ return self.sessions[user_id]++ async def add_message(self, user_id: int, chat_id: int, message: str) -> str:+ """Add message to user's queue"""+ session = await self.get_or_create_session(user_id, chat_id)+ session.add_message(message)++ return f"Message added to queue. Total messages: {len(session.message_queue)}"++ async def get_next_message(self, user_id: int) -> Optional[str]:+ """Get next message from user's queue"""+ if user_id not in self.sessions:+ return None++ session = self.sessions[user_id]+ return session.get_next_message()++ async def has_messages(self, user_id: int) -> bool:+ """Check if user has messages in queue"""+ if user_id not in self.sessions:+ return False+ return len(self.sessions[user_id].message_queue) > 0++ async def get_queue_details(self, user_id: int) -> str:+ """Get detailed queue information for user"""+ if user_id not in self.sessions:+ return "No active session. Send a message to start."++ session = self.sessions[user_id]++ if not session.message_queue:+ if session.is_executing:+ return "📋 Queue is empty\n⏳ Currently executing a message..."+ else:+ return "📋 Queue is empty\n💤 No messages to process"++ queue_info = f"📋 Message Queue ({len(session.message_queue)} messages)\n"+ queue_info += f"Status: {'🟢 Processing' if session.is_executing else '⭕ Waiting'}\n\n"++ for idx, msg in enumerate(session.message_queue, 1):+ # Show first 100 characters of each message+ preview = msg[:100] + "..." if len(msg) > 100 else msg+ # Replace newlines with spaces for better display+ preview = preview.replace('\n', ' ').replace('\r', ' ')+ queue_info += f"{idx}. {preview}\n"++ return queue_info++ async def clear_queue(self, user_id: int) -> str:+ """Clear user's message queue"""+ if user_id not in self.sessions:+ return "No active session found."++ session = self.sessions[user_id]+ message_count = len(session.message_queue)+ session.clear_queue()++ return f"Cleared {message_count} messages from queue."++ async def get_status(self, user_id: int) -> str:+ """Get user's session status"""+ if user_id not in self.sessions:+ return "No active session. Send a message to start."++ session = self.sessions[user_id]+ return session.get_status()++ async def set_executing(self, user_id: int, is_executing: bool):+ """Set execution status for user session"""+ if user_id in self.sessions:+ async with self._lock:+ self.sessions[user_id].is_executing = is_executing+ self.sessions[user_id].last_activity = datetime.now()++ async def is_executing(self, user_id: int) -> bool:+ """Check if user has an active execution"""+ if user_id not in self.sessions:+ return False+ return self.sessions[user_id].is_executing++ async def cleanup_inactive_sessions(self, inactive_hours: int = 24):+ """Clean up inactive sessions"""+ async with self._lock:+ current_time = datetime.now()+ to_remove = []++ for user_id, session in self.sessions.items():+ time_diff = current_time - session.last_activity+ if time_diff.total_seconds() > inactive_hours * 3600:+ to_remove.append(user_id)++ for user_id in to_remove:+ del self.sessions[user_id]+ logger.info(f"Cleaned up inactive session for user {user_id}")++ return len(to_remove)\ No newline at end of filediff --git a/modules/telegram_bot.py b/modules/telegram_bot.pynew file mode 100644index 000000000..f7cde8d7b--- /dev/null+++ b/modules/telegram_bot.py@@ -0,0 +1,243 @@+import asyncio+import logging+from typing import Callable, Optional+from telegram import Update, Bot+from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes+from telegram.helpers import escape_markdown+from config import TelegramConfig+++logger = logging.getLogger(__name__)+++class TelegramBot:+ def __init__(self, config: TelegramConfig):+ self.config = 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++ 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++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)++ 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++ chat_id = update.effective_chat.id+ user_id = update.effective_user.id++ if self.execute_callback:+ await self.execute_callback(chat_id, user_id)++ 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++ 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++ 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++ if self.cwd_callback:+ response = await self.cwd_callback(chat_id, user_id)+ if response:+ await update.message.reply_text(response, parse_mode='MarkdownV2')++ 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):+ return++ chat_id = update.effective_chat.id+ user_id = update.effective_user.id++ # Extract path from command+ message_text = update.message.text+ parts = message_text.split(maxsplit=1)++ 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)++ 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):+ """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++ 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(+ MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_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'+ )++ def run(self):+ """Run the bot with infinite retry mechanism"""+ import time++ self.setup_handlers()++ retry_delay = 5 # seconds+ attempt = 1++ while True:+ try:+ logger.info(f"Starting Telegram bot (attempt {attempt})...")+ self.application.run_polling()+ break # If successful, break out of retry loop++ except KeyboardInterrupt:+ logger.info("Received keyboard interrupt, shutting down...")+ break++ except Exception as e:+ logger.error(f"Telegram bot failed (attempt {attempt}): {e}")+ logger.info(f"Retrying in {retry_delay} seconds...")++ try:+ time.sleep(retry_delay)+ except KeyboardInterrupt:+ logger.info("Received keyboard interrupt during retry wait, shutting down...")+ break++ retry_delay = min(retry_delay * 1.5, 60) # Exponential backoff, max 60s+ attempt += 1\ No newline at end of filediff --git a/requirements.txt b/requirements.txtnew file mode 100644index 000000000..e93c3bafe--- /dev/null+++ b/requirements.txt@@ -0,0 +1,4 @@+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 filediff --git a/start.sh b/start.shnew file mode 100755index 000000000..a2f787bd5--- /dev/null+++ b/start.sh@@ -0,0 +1,12 @@+#!/bin/bash++# Load environment variables from .env file if it exists+if [ -f .env ]; then+ export $(cat .env | grep -v '^#' | xargs)+fi++# Create working directory if it doesn't exist+mkdir -p ./_tmp++# Run the application+python3 main.py\ No newline at end of file