Refactor telegram_helper.py: Apply constants, remove unused git import, and prepare for processing_status encapsulation.

This commit is contained in:
cyclop-bot
2025-06-02 14:55:30 -05:00
parent f23812822e
commit a7d2c98c97
+26 -26
View File
@@ -3,16 +3,21 @@ import logging
import sys import sys
import asyncio import asyncio
import time import time
import git
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler
from browse_command import browse_command, button_callback from browse_command import browse_command, button_callback
class TelegramHelper: class TelegramHelper:
# --- Constants for configurable paths and magic strings ---
REBOOT_CLAUDE_FILE = '.reboot_claude'
REBOOT_FILE = '.doreboot'
CLAUDE_REBOOT_TARGET = 'claude'
HTML_QUOTE_BLOCK_START = '<blockquote expandable><b>Thinking...</b>'
HTML_QUOTE_BLOCK_END = '</blockquote>'
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.telegram_bot_token = os.getenv('TELEGRAM_BOT_TOKEN') self.telegram_bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
self.repo = git.Repo(".")
self.start_time = time.time() self.start_time = time.time()
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@ -23,11 +28,11 @@ class TelegramHelper:
async def clear(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def clear(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.effective_user.id user_id = update.effective_user.id
await self.bot.clear(user_id) await self.bot.clear_conversation_history(user_id)
await update.message.reply_text("Conversation history cleared. Let's start fresh!") await update.message.reply_text("Conversation history cleared. Let's start fresh!")
async def status(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def status(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
status_message = await self.bot.status() status_message = await self.bot.get_bot_status()
await update.message.reply_text(status_message) await update.message.reply_text(status_message)
async def switch(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def switch(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@ -56,23 +61,22 @@ class TelegramHelper:
logging.info(f"Message from user {user_id}: {user_message}") logging.info(f"Message from user {user_id}: {user_message}")
status_message = await update.message.reply_text("Processing your request...", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Abort", callback_data='abort')]])) status_message = await update.message.reply_text("Processing your request...", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Abort", callback_data='abort')]]))\
self.bot.processing_status[user_id] = {"processing": True, "message_id": status_message.message_id} await self.bot.set_processing_status(user_id, status_message.message_id)
response = await self.bot.handle_message(user_id, user_message) response = await self.bot.handle_message(user_id, user_message)
await context.bot.delete_message(chat_id=update.effective_chat.id, message_id=status_message.message_id) await context.bot.delete_message(chat_id=update.effective_chat.id, message_id=status_message.message_id)
del self.bot.processing_status[user_id] await self.bot.clear_processing_status(user_id)
response = response.replace("<think>", "<blockquote expandable><b>Thinking...</b>").replace("</think>", "</blockquote>")
# Return response as html message response = response.replace("<think>", self.HTML_QUOTE_BLOCK_START).replace("</think>", self.HTML_QUOTE_BLOCK_END)
if len(response) > 4096: if len(response) > 4096:
# If the response is too long, split it into chunks
chunks = [response[i:i + 4096] for i in range(0, len(response), 4096)] chunks = [response[i:i + 4096] for i in range(0, len(response), 4096)]
for chunk in chunks: for chunk in chunks:
await update.message.reply_text(chunk) await update.message.reply_text(chunk)
# Add a small delay to avoid flooding
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
else: else:
await update.message.reply_text(response) await update.message.reply_text(response)
except Exception as e: except Exception as e:
@@ -82,27 +86,27 @@ class TelegramHelper:
async def abort_processing(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def abort_processing(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
query = update.callback_query query = update.callback_query
await query.answer() await query.answer()
user_id = query.from_user.id user_id = query.from_user.id
result = await self.bot.abort_processing(user_id) result = await self.bot.abort_processing(user_id)
await query.edit_message_text(text=result) await query.edit_message_text(text=result)
async def reboot(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def reboot(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_message = update.message.text.split() # Split the message to check for 'claude' user_message = update.message.text.split()
if len(user_message) > 1 and user_message[1].lower() == 'claude': if len(user_message) > 1 and user_message[1].lower() == self.CLAUDE_REBOOT_TARGET:
open('./.reboot_claude', 'w').close() # Create an empty file open(self.REBOOT_CLAUDE_FILE, 'w').close()
if update: if update:
await update.message.reply_text("Rebooting the bot...") await update.message.reply_text("Rebooting the bot...")
logging.info("Received reboot command. Exiting process...") logging.info("Received reboot command. Exiting process...")
reboot_file_path = "./.doreboot" reboot_file_path = self.REBOOT_FILE
if not os.path.exists(reboot_file_path): if not os.path.exists(reboot_file_path):
with open(reboot_file_path, 'w') as f: with open(reboot_file_path, 'w') as f:
f.write(str(update.effective_chat.id) if update else "") f.write(str(update.effective_chat.id) if update else "")
sys.exit(0) sys.exit(0)
async def check_doreboot_file(self, application: Application): async def check_doreboot_file(self, application: Application):
reboot_file_path = "./.doreboot" reboot_file_path = self.REBOOT_FILE
if os.path.exists(reboot_file_path): if os.path.exists(reboot_file_path):
with open(reboot_file_path, 'r') as f: with open(reboot_file_path, 'r') as f:
chat_id = f.read().strip() chat_id = f.read().strip()
@@ -122,16 +126,12 @@ class TelegramHelper:
application.add_handler(CommandHandler("status", self.status)) application.add_handler(CommandHandler("status", self.status))
application.add_handler(CommandHandler("reboot", self.reboot)) application.add_handler(CommandHandler("reboot", self.reboot))
application.add_handler(CommandHandler("browse", self.browse)) application.add_handler(CommandHandler("browse", self.browse))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))\
application.add_handler(CallbackQueryHandler(self.abort_processing, pattern='^abort$')) application.add_handler(CallbackQueryHandler(self.abort_processing, pattern='^abort$'))
application.add_handler(CallbackQueryHandler(button_callback, pattern='^(browse|file):')) application.add_handler(CallbackQueryHandler(button_callback, pattern='^(browse|file):'))
logging.info("Bot is running...") logging.info("Bot is running...")
# Check for .doreboot file and send message if it exists
asyncio.get_event_loop().create_task(self.check_doreboot_file(application)) asyncio.get_event_loop().create_task(self.check_doreboot_file(application))
# Commenting out the commit checking task application.run_polling()
# asyncio.get_event_loop().create_task(self.check_for_new_commits())
application.run_polling()