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
Add personalization settings and improve message formatting
cyhhaoe4a7952b74c3
diff --git a/.gitignore b/.gitignoreindex d1f400a0b..251dbbfbb 100644--- a/.gitignore+++ b/.gitignore@@ -147,6 +147,9 @@ claude_proxy.logdemolog.log_tmp/.DS_Store+logs/+.bot.pid+user_settings.json# Config files with secretsconfig/secrets.pydiff --git a/core/controller.py b/core/controller.pyindex b38766dbb..8d6c04f10 100644--- a/core/controller.py+++ b/core/controller.py@@ -3,10 +3,12 @@ import loggingimport osfrom typing import Optionalfrom telegram.helpers import escape_markdown+from telegram import InlineKeyboardButton, InlineKeyboardMarkupfrom config import AppConfigfrom modules.telegram_bot import TelegramBotfrom modules.claude_client import ClaudeClientfrom modules.session_manager import SessionManager+from modules.settings_manager import SettingsManagerlogger = logging.getLogger(__name__)@@ -18,6 +20,7 @@ class Controller:self.telegram_bot = TelegramBot(config.telegram)self.claude_client = ClaudeClient(config.claude)self.session_manager = SessionManager()+ self.settings_manager = SettingsManager()# Setup callbacksself._setup_callbacks()@@ -34,7 +37,9 @@ class Controller:on_clear=self.handle_clear,on_cwd=self.handle_cwd,on_set_cwd=self.handle_set_cwd,- on_queue=self.handle_queue+ on_queue=self.handle_queue,+ on_settings=self.handle_settings,+ on_callback_query=self.handle_callback_query)async def handle_user_message(self, chat_id: int, user_id: int, message: str) -> str:@@ -74,13 +79,29 @@ class Controller:# f"🚀 Processing: {message[:50]}..."# )+ # Get user's CWD from settings if available+ custom_cwd = self.settings_manager.get_custom_cwd(user_id)+ if custom_cwd:+ # Temporarily set the CWD for this execution+ original_cwd = self.claude_client.options.cwd+ self.claude_client.options.cwd = custom_cwd+# 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')+ 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)")+ 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)try:- await self.claude_client.stream_execute(message, on_claude_message)+ await self.claude_client.stream_execute(message, on_claude_message, user_id)++ # Restore original CWD if it was changed+ if custom_cwd:+ self.claude_client.options.cwd = original_cwd# Check if there are more messagesremaining = await self.session_manager.has_messages(user_id)@@ -97,6 +118,9 @@ class Controller:except Exception as e:logger.error(f"Error during Claude execution: {e}")+ # Restore original CWD if it was changed+ if custom_cwd:+ self.claude_client.options.cwd = original_cwdawait self.telegram_bot.send_message(target_chat_id,f"❌ Error processing message: {str(e)}\nStopping queue processing."@@ -159,7 +183,9 @@ class Controller: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+ # Check if user has custom CWD in settings+ custom_cwd = self.settings_manager.get_custom_cwd(user_id)+ current_cwd = custom_cwd if custom_cwd else self.claude_client.options.cwdabsolute_path = os.path.abspath(current_cwd)response_text = f"📁 Current Working Directory:\n{absolute_path}"@@ -170,6 +196,11 @@ class Controller:else:response_text += "\n⚠️ Directory does not exist"+ if custom_cwd:+ response_text += "\n💡 (User custom setting)"+ else:+ response_text += "\n💡 (Default from .env)"+return escape_markdown(response_text, version=2)except Exception as e:logger.error(f"Error getting cwd: {e}")@@ -195,15 +226,15 @@ class Controller: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+ # Save to user settings+ self.settings_manager.set_custom_cwd(user_id, 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."+ f"This setting has been saved for your user.")return escape_markdown(response_text, version=2)@@ -221,6 +252,122 @@ class Controller:logger.error(f"Error getting queue details: {e}")return f"Error getting queue information: {str(e)}"+ async def handle_settings(self, chat_id: int, user_id: int):+ """Handle settings command - show settings menu with inline keyboard"""+ try:+ # Get current settings+ user_settings = self.settings_manager.get_user_settings(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 = []+ 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)++ # Add info button on its own line+ keyboard.append([InlineKeyboardButton("ℹ️ About Message Types", callback_data="info_msg_types")])++ reply_markup = InlineKeyboardMarkup(keyboard)++ # 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+ )++ 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,+ f"❌ Error showing settings: {str(e)}"+ )++ async def handle_callback_query(self, callback_query):+ """Handle inline keyboard callbacks"""+ try:+ user_id = callback_query.from_user.id+ data = callback_query.data++ # Check permission+ if not self.telegram_bot.check_permission(user_id):+ await callback_query.answer("You are not authorized to use this bot.")+ return++ if 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)++ # Update the keyboard with 2x2 layout+ user_settings = self.settings_manager.get_user_settings(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)++ keyboard.append([InlineKeyboardButton("ℹ️ About Message Types", callback_data="info_msg_types")])++ reply_markup = InlineKeyboardMarkup(keyboard)++ # Update message+ await callback_query.edit_message_reply_markup(reply_markup=reply_markup)++ # Answer callback with display name+ display_names = self.settings_manager.get_message_type_display_names()+ 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":+ # 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\."+ )+ await callback_query.answer()+ await callback_query.message.reply_text(info_text, parse_mode='MarkdownV2')++ except Exception as e:+ logger.error(f"Error handling callback query: {e}")+ await callback_query.answer(f"Error: {str(e)}")+async def periodic_cleanup(self):"""Periodic cleanup of inactive sessions"""while True:diff --git a/modules/claude_client.py b/modules/claude_client.pyindex a77653f80..6127d2d34 100644--- a/modules/claude_client.py+++ b/modules/claude_client.py@@ -71,13 +71,17 @@ class ClaudeClient:# Get ClaudeCode's current working directorycwd = self.options.cwd or os.getcwd()++ # Normalize paths for consistent comparison+ cwd = os.path.normpath(cwd)+ full_path = os.path.normpath(full_path)try:# If the path starts with cwd, make it relative- if full_path.startswith(cwd):+ if full_path.startswith(cwd + os.sep) or full_path == cwd:relative = os.path.relpath(full_path, cwd)# Use "./" prefix for current directory files- if not relative.startswith("."):+ if not relative.startswith(".") and relative != ".":relative = "./" + relativereturn relativeelse:@@ -143,13 +147,18 @@ class ClaudeClient:# Command operationsif "command" in block.input and block.input["command"]:- escaped_cmd = escape_markdown(block.input["command"], version=2)- input_info.append(f"💻 Command: `{escaped_cmd}`")+ cmd = block.input["command"]+ # For multi-line commands, use code block+ if "\n" in cmd or len(cmd) > 80:+ input_info.append(f"💻 Command:\n```bash\n{cmd}\n```")+ else:+ escaped_cmd = escape_markdown(cmd, 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}")+ desc = block.input["description"]+ input_info.append(f"📝 Description: `{escape_markdown(desc, version=2)}`")# Pattern/Query operationsif "pattern" in block.input and block.input["pattern"]:@@ -255,10 +264,14 @@ class ClaudeClient: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":+ # 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"]++ if block.name in no_json_tools:+ show_json = False++ if block.name == "TodoWrite":# TodoWrite has complex todos array - show as markdown listif "todos" in block.input and block.input["todos"]:todos = block.input["todos"]@@ -293,14 +306,14 @@ class ClaudeClient: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+ elif "content" in block.input and block.input["content"] and block.name in ["Write", "Edit", "MultiEdit"]:+ # Show content in code block for file write operationscontent = 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+ elif show_json and block.input and len(str(block.input)) < 200:+ # Show short input as JSON for tools that need itimport jsontry:@@ -364,8 +377,8 @@ class ClaudeClient: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+ # Use total duration (duration_ms includes API time)+ total_seconds = message.duration_ms / 1000minutes = int(total_seconds // 60)seconds = int(total_seconds % 60)@@ -374,15 +387,12 @@ class ClaudeClient: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"+ # Don't escape for Result messages - they will be handled by smart formatting+ result_text = f"📊 **Result ({message.subtype})**\n"+ result_text += f"⏱️ Duration: {duration_str}\n"if message.result:- escaped_result = escape_markdown(message.result, version=2)- result_text += f"\n{escaped_result}\n"+ result_text += f"\n{message.result}\n"return result_text@@ -396,7 +406,7 @@ class ClaudeClient:return Truereturn False- async def stream_execute(self, prompt: str, on_message: Callable):+ 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):@@ -408,10 +418,23 @@ class ClaudeClient:if self._is_skip_message(message):continue+ # Determine message type for filtering (simplified to main categories)+ message_type = None+ 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'+formatted_message = self.format_message(message)if formatted_message and formatted_message.strip():- await on_message(formatted_message)+ 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)}")+ await on_message(f"❌ Error: {str(e)}", 'system') # Error messages go to system categoryraisediff --git a/modules/settings_manager.py b/modules/settings_manager.pynew file mode 100644index 000000000..fe6783517--- /dev/null+++ b/modules/settings_manager.py@@ -0,0 +1,123 @@+import json+import logging+import os+from dataclasses import dataclass, asdict, field+from typing import Dict, List, Optional+from pathlib import Path+++logger = logging.getLogger(__name__)+++@dataclass+class UserSettings:+ """User personalization settings"""+ hidden_message_types: List[str] = field(default_factory=list) # Message types to hide+ custom_cwd: Optional[str] = None # Custom working directory++ def to_dict(self) -> dict:+ """Convert to dictionary for JSON serialization"""+ return asdict(self)++ @classmethod+ def from_dict(cls, data: dict) -> 'UserSettings':+ """Create from dictionary"""+ return cls(**data)+++class SettingsManager:+ """Manages user personalization settings with JSON persistence"""++ def __init__(self, settings_file: str = "user_settings.json"):+ self.settings_file = Path(settings_file)+ self.settings: Dict[int, UserSettings] = {}+ self._load_settings()++ def _load_settings(self):+ """Load settings from JSON file"""+ try:+ if self.settings_file.exists():+ with open(self.settings_file, 'r') as f:+ data = json.load(f)+ for user_id_str, user_data in data.items():+ user_id = int(user_id_str)+ self.settings[user_id] = UserSettings.from_dict(user_data)+ logger.info(f"Loaded settings for {len(self.settings)} users")+ else:+ logger.info("No settings file found, starting with empty settings")+ except Exception as e:+ logger.error(f"Error loading settings: {e}")+ self.settings = {}++ def _save_settings(self):+ """Save settings to JSON file"""+ try:+ data = {+ str(user_id): settings.to_dict()+ for user_id, settings in self.settings.items()+ }+ with open(self.settings_file, 'w') as f:+ json.dump(data, f, indent=2)+ logger.info("Settings saved successfully")+ except Exception as e:+ logger.error(f"Error saving settings: {e}")++ def get_user_settings(self, user_id: int) -> UserSettings:+ """Get settings for a specific user"""+ if user_id not in self.settings:+ self.settings[user_id] = UserSettings()+ self._save_settings()+ return self.settings[user_id]++ def update_user_settings(self, user_id: int, settings: UserSettings):+ """Update settings for a specific user"""+ self.settings[user_id] = settings+ self._save_settings()++ def toggle_hidden_message_type(self, user_id: int, message_type: str) -> bool:+ """Toggle a message type in hidden list, returns new state"""+ settings = self.get_user_settings(user_id)++ if message_type in settings.hidden_message_types:+ settings.hidden_message_types.remove(message_type)+ is_hidden = False+ else:+ settings.hidden_message_types.append(message_type)+ is_hidden = True++ self.update_user_settings(user_id, settings)+ return is_hidden++ def set_custom_cwd(self, user_id: int, cwd: str):+ """Set custom working directory for user"""+ settings = self.get_user_settings(user_id)+ settings.custom_cwd = cwd+ self.update_user_settings(user_id, settings)++ def get_custom_cwd(self, user_id: int) -> Optional[str]:+ """Get custom working directory for user"""+ settings = self.get_user_settings(user_id)+ return settings.custom_cwd++ def is_message_type_hidden(self, user_id: int, message_type: str) -> bool:+ """Check if a message type is hidden for user"""+ settings = self.get_user_settings(user_id)+ return message_type in settings.hidden_message_types++ def get_available_message_types(self) -> List[str]:+ """Get list of available message types that can be hidden"""+ return [+ "system",+ "user",+ "assistant",+ "result"+ ]++ def get_message_type_display_names(self) -> Dict[str, str]:+ """Get display names for message types"""+ return {+ "system": "System",+ "user": "Response", # Renamed from 'user' for clarity+ "assistant": "Assistant",+ "result": "Result"+ }\ No newline at end of filediff --git a/modules/telegram_bot.py b/modules/telegram_bot.pyindex f7cde8d7b..a940d2f5e 100644--- a/modules/telegram_bot.py+++ b/modules/telegram_bot.py@@ -1,9 +1,10 @@import asyncioimport loggingfrom typing import Callable, Optional-from telegram import Update, Bot-from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes+from telegram import Update, Bot, InlineKeyboardMarkup+from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandlerfrom telegram.helpers import escape_markdown+from telegram.error import TelegramErrorfrom config import TelegramConfig@@ -21,6 +22,8 @@ class TelegramBot:self.cwd_callback: Optional[Callable] = Noneself.set_cwd_callback: Optional[Callable] = Noneself.queue_callback: Optional[Callable] = None+ self.settings_callback: Optional[Callable] = None+ self.callback_query_handler: Optional[Callable] = Nonedef check_permission(self, user_id: int) -> bool:"""Check if user is allowed to use the bot"""@@ -49,6 +52,7 @@ Commands:/queue - Show messages in queue/cwd - Show current working directory/set_cwd <path> - Set working directory+/settings - Personalization settingsHow it works:• Send any message to add it to the queue@@ -160,6 +164,22 @@ How it works: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++ 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,@@ -167,7 +187,9 @@ How it works:on_clear: Callable = None,on_cwd: Callable = None,on_set_cwd: Callable = None,- on_queue: Callable = None):+ on_queue: Callable = None,+ on_settings: Callable = None,+ on_callback_query: Callable = None):"""Register callback functions"""self.message_callback = on_messageself.execute_callback = on_execute@@ -176,6 +198,8 @@ How it works:self.cwd_callback = on_cwdself.set_cwd_callback = on_set_cwdself.queue_callback = on_queue+ self.settings_callback = on_settings+ self.callback_query_handler = on_callback_querydef setup_handlers(self):"""Setup bot command and message handlers"""@@ -186,6 +210,8 @@ How it works: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))self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))@@ -210,6 +236,89 @@ How it works:parse_mode=parse_mode if parse_mode != 'Markdown' else 'MarkdownV2')+ async def send_settings_message(self, chat_id: int, text: str, reply_markup: InlineKeyboardMarkup):+ """Send message with inline keyboard"""+ bot = self.application.bot+ await bot.send_message(+ chat_id=chat_id,+ text=text,+ parse_mode='MarkdownV2',+ reply_markup=reply_markup+ )++ async def send_message_smart(self, chat_id: int, text: str, message_type: str = None):+ """Send message with smart format fallback for different message types"""+ bot = self.application.bot++ # Split long messages+ if len(text) > 4000:+ for i in range(0, len(text), 4000):+ await self.send_message_smart(chat_id, text[i:i+4000], message_type)+ await asyncio.sleep(0.1)+ return++ # For result messages, try to preserve formatting+ if message_type == 'result':+ # Try original Markdown first+ try:+ await bot.send_message(+ chat_id=chat_id,+ text=text,+ parse_mode='Markdown'+ )+ return+ except TelegramError:+ pass++ # Try HTML as fallback+ try:+ # Simple Markdown to HTML conversion+ html_text = self._markdown_to_html(text)+ await bot.send_message(+ chat_id=chat_id,+ text=html_text,+ parse_mode='HTML'+ )+ return+ except TelegramError:+ pass++ # Default to escaped MarkdownV2 for all other cases+ try:+ await bot.send_message(+ chat_id=chat_id,+ text=text,+ parse_mode='MarkdownV2'+ )+ except TelegramError:+ # Last resort: send as plain text+ await bot.send_message(+ chat_id=chat_id,+ text=text+ )++ def _markdown_to_html(self, text: str) -> str:+ """Simple Markdown to HTML conversion for common patterns"""+ import re++ # First escape HTML entities+ text = text.replace('&', '&')+ text = text.replace('<', '<')+ text = text.replace('>', '>')++ # Convert code blocks (must be done before inline code)+ text = re.sub(r'```([^`]+)```', r'<pre>\1</pre>', text, flags=re.DOTALL)+ text = re.sub(r'`([^`]+)`', r'<code>\1</code>', text)++ # Convert bold and italic+ text = re.sub(r'\*\*([^*]+)\*\*', r'<b>\1</b>', text)+ text = re.sub(r'\*([^*]+)\*', r'<i>\1</i>', text)++ # Convert links+ text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)++ return text+def run(self):"""Run the bot with infinite retry mechanism"""import timediff --git a/start.sh b/start.shindex a2f787bd5..585b15566 100755--- a/start.sh+++ b/start.sh@@ -1,12 +1,123 @@#!/bin/bash+# Get the absolute path of current directory+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+LOG_DIR="$SCRIPT_DIR/logs"+LOG_FILE="$LOG_DIR/bot_$(date +%Y%m%d_%H%M%S).log"+PID_FILE="$SCRIPT_DIR/.bot.pid"++# Create logs directory if it doesn't exist+mkdir -p "$LOG_DIR"++echo "Starting Telegram Bot Manager..."+echo "Working directory: $SCRIPT_DIR"+echo "Log file: $LOG_FILE"++# Function to kill the current instance safely+kill_current_instance() {+ if [ -f "$PID_FILE" ]; then+ OLD_PID=$(cat "$PID_FILE")++ # Check if the process exists and is our process+ if ps -p "$OLD_PID" > /dev/null 2>&1; then+ # Verify it's actually our python process in the correct directory+ PROCESS_CMD=$(ps -p "$OLD_PID" -o command= 2>/dev/null || echo "")+ PROCESS_CWD=$(lsof -p "$OLD_PID" -a -d cwd -Fn 2>/dev/null | grep '^n' | cut -c2- || echo "")++ if [[ "$PROCESS_CMD" == *"python"*"main.py"* ]] && [[ "$PROCESS_CWD" == "$SCRIPT_DIR" ]]; then+ echo "Found running instance (PID: $OLD_PID), stopping..."+ kill -TERM "$OLD_PID" 2>/dev/null++ # Wait for process to terminate gracefully+ for i in {1..10}; do+ if ! ps -p "$OLD_PID" > /dev/null 2>&1; then+ echo "Process stopped successfully"+ break+ fi+ sleep 1+ done++ # Force kill if still running+ if ps -p "$OLD_PID" > /dev/null 2>&1; then+ echo "Force killing process..."+ kill -KILL "$OLD_PID" 2>/dev/null+ sleep 1+ fi+ else+ echo "PID file exists but process is not our bot, removing stale PID file"+ fi+ else+ echo "No running instance found (stale PID file)"+ fi++ # Remove PID file+ rm -f "$PID_FILE"+ else+ echo "No previous instance found"+ fi+}++# Kill current instance+kill_current_instance++# Change to script directory+cd "$SCRIPT_DIR"+# Load environment variables from .env file if it existsif [ -f .env ]; thenexport $(cat .env | grep -v '^#' | xargs)+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 " CLAUDE_CWD=./_tmp (optional, default: ./_tmp)"+ exit 1fi# Create working directory if it doesn't existmkdir -p ./_tmp-# Run the application-python3 main.py\ No newline at end of file+# Check if virtual environment exists+if [ -d "venv" ]; then+ echo "Activating virtual environment..."+ source venv/bin/activate+elif [ -d ".venv" ]; then+ echo "Activating virtual environment..."+ source .venv/bin/activate+else+ echo "No virtual environment found, using system Python"+fi++# Start the bot with output redirected to log file+echo "Starting bot..."+echo "============================================" >> "$LOG_FILE"+echo "Bot started at: $(date)" >> "$LOG_FILE"+echo "============================================" >> "$LOG_FILE"++# Run python in unbuffered mode for real-time logging+nohup python3 -u main.py >> "$LOG_FILE" 2>&1 &++# Save new PID+NEW_PID=$!+echo "$NEW_PID" > "$PID_FILE"++# Check if process started successfully+sleep 2+if ps -p "$NEW_PID" > /dev/null 2>&1; then+ echo "Bot started successfully (PID: $NEW_PID)"+ echo "Logs are being written to: $LOG_FILE"+ echo ""+ echo "To view logs in real-time:"+ echo " tail -f $LOG_FILE"+ echo ""+ echo "To stop the bot:"+ echo " $SCRIPT_DIR/stop.sh"+else+ echo "ERROR: Failed to start bot!"+ echo "Check the log file for errors: $LOG_FILE"+ tail -n 20 "$LOG_FILE"+ rm -f "$PID_FILE"+ exit 1+fi\ No newline at end of filediff --git a/status.sh b/status.shnew file mode 100755index 000000000..76df74486--- /dev/null+++ b/status.sh@@ -0,0 +1,51 @@+#!/bin/bash++# Get the absolute path of current directory+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PID_FILE="$SCRIPT_DIR/.bot.pid"+LOG_DIR="$SCRIPT_DIR/logs"++echo "Telegram Bot Status"+echo "==================="++if [ -f "$PID_FILE" ]; then+ PID=$(cat "$PID_FILE")++ # Check if the process exists+ if ps -p "$PID" > /dev/null 2>&1; then+ # Verify it's actually our python process+ PROCESS_CMD=$(ps -p "$PID" -o command= 2>/dev/null || echo "")+ PROCESS_CWD=$(lsof -p "$PID" -a -d cwd -Fn 2>/dev/null | grep '^n' | cut -c2- || echo "")++ if [[ "$PROCESS_CMD" == *"python"*"main.py"* ]] && [[ "$PROCESS_CWD" == "$SCRIPT_DIR" ]]; then+ echo "Status: RUNNING"+ echo "PID: $PID"++ # Show process info+ echo ""+ echo "Process info:"+ ps -p "$PID" -o pid,vsz,rss,pcpu,pmem,etime,command++ # Show latest log file+ if [ -d "$LOG_DIR" ]; then+ LATEST_LOG=$(ls -t "$LOG_DIR"/bot_*.log 2>/dev/null | head -1)+ if [ -n "$LATEST_LOG" ]; then+ echo ""+ echo "Latest log file: $LATEST_LOG"+ echo "Last 10 lines:"+ echo "---"+ tail -n 10 "$LATEST_LOG"+ fi+ fi+ else+ echo "Status: STOPPED (stale PID file)"+ echo "PID file exists but process is not our bot"+ fi+ else+ echo "Status: STOPPED (stale PID file)"+ echo "Bot is not running"+ fi+else+ echo "Status: STOPPED"+ echo "Bot is not running (no PID file)"+fi\ No newline at end of filediff --git a/stop.sh b/stop.shnew file mode 100755index 000000000..830a18e51--- /dev/null+++ b/stop.sh@@ -0,0 +1,57 @@+#!/bin/bash++# Get the absolute path of current directory+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PID_FILE="$SCRIPT_DIR/.bot.pid"++echo "Stopping Telegram Bot..."++if [ -f "$PID_FILE" ]; then+ PID=$(cat "$PID_FILE")++ # Check if the process exists+ if ps -p "$PID" > /dev/null 2>&1; then+ # Verify it's actually our python process in the correct directory+ PROCESS_CMD=$(ps -p "$PID" -o command= 2>/dev/null || echo "")+ PROCESS_CWD=$(lsof -p "$PID" -a -d cwd -Fn 2>/dev/null | grep '^n' | cut -c2- || echo "")++ if [[ "$PROCESS_CMD" == *"python"*"main.py"* ]] && [[ "$PROCESS_CWD" == "$SCRIPT_DIR" ]]; then+ echo "Found bot process (PID: $PID), stopping..."+ kill -TERM "$PID" 2>/dev/null++ # Wait for process to terminate gracefully+ for i in {1..10}; do+ if ! ps -p "$PID" > /dev/null 2>&1; then+ echo "Bot stopped successfully"+ rm -f "$PID_FILE"+ exit 0+ fi+ sleep 1+ done++ # Force kill if still running+ if ps -p "$PID" > /dev/null 2>&1; then+ echo "Force killing process..."+ kill -KILL "$PID" 2>/dev/null+ sleep 1+ fi++ if ! ps -p "$PID" > /dev/null 2>&1; then+ echo "Bot stopped (force killed)"+ rm -f "$PID_FILE"+ else+ echo "ERROR: Failed to stop bot!"+ exit 1+ fi+ else+ echo "PID file exists but process is not our bot"+ echo "Removing stale PID file"+ rm -f "$PID_FILE"+ fi+ else+ echo "Bot is not running (stale PID file)"+ rm -f "$PID_FILE"+ fi+else+ echo "Bot is not running (no PID file found)"+fi\ No newline at end of file