2024-08-19 11:31:06 -05:00
|
|
|
import os
|
2024-08-19 11:35:29 -05:00
|
|
|
import logging
|
2024-08-20 12:37:35 -05:00
|
|
|
import sys
|
2024-08-20 14:11:19 -05:00
|
|
|
import asyncio
|
2024-08-20 14:21:41 -05:00
|
|
|
import time
|
2025-06-02 16:41:02 -05:00
|
|
|
from typing import TypedDict, Union, TypeAlias, List # Added List for type hint
|
2024-08-19 11:31:06 -05:00
|
|
|
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
|
|
|
|
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler
|
2024-08-20 16:52:09 -05:00
|
|
|
from browse_command import browse_command, button_callback
|
2025-06-03 13:04:42 -05:00
|
|
|
from inference_bot import InferenceBot
|
2024-08-19 11:31:06 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
class MessageHandlerLogicResult(TypedDict):
|
|
|
|
|
success: bool
|
|
|
|
|
response_text: Union[str, None]
|
|
|
|
|
error_message: Union[str, None]
|
|
|
|
|
|
|
|
|
|
LogicResult: TypeAlias = MessageHandlerLogicResult
|
|
|
|
|
|
2024-08-19 11:31:06 -05:00
|
|
|
class TelegramHelper:
|
2025-06-02 14:55:30 -05:00
|
|
|
HTML_QUOTE_BLOCK_START = '<blockquote expandable><b>Thinking...</b>'
|
|
|
|
|
HTML_QUOTE_BLOCK_END = '</blockquote>'
|
2025-06-02 16:40:24 -05:00
|
|
|
CHUNK_MESSAGE_SLEEP_DURATION = 0.1
|
2025-06-02 14:55:30 -05:00
|
|
|
|
2025-06-03 13:04:42 -05:00
|
|
|
def __init__(self, bot : InferenceBot,
|
2025-06-02 16:40:24 -05:00
|
|
|
chunk_message_sleep_duration: float | None = None):
|
2024-08-19 11:31:06 -05:00
|
|
|
self.bot = bot
|
2024-08-19 11:35:29 -05:00
|
|
|
self.telegram_bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
|
2024-08-20 14:21:41 -05:00
|
|
|
self.start_time = time.time()
|
2025-06-02 16:40:24 -05:00
|
|
|
self.chunk_message_sleep_duration = chunk_message_sleep_duration if chunk_message_sleep_duration is not None else self.CHUNK_MESSAGE_SLEEP_DURATION
|
2024-08-19 11:31:06 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def _start_logic(self) -> str:
|
2024-08-19 11:31:06 -05:00
|
|
|
await self.bot.start()
|
2025-06-02 16:36:51 -05:00
|
|
|
return "Hello! I'm your AI assistant. How can I help you today?"
|
2024-08-19 11:31:06 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
2025-06-02 16:36:51 -05:00
|
|
|
response_message = await self._start_logic()
|
|
|
|
|
await update.message.reply_text(response_message)
|
|
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def _clear_logic(self, user_id: int) -> str:
|
2025-06-02 15:23:20 -05:00
|
|
|
self.bot.clear_conversation_history(user_id)
|
2025-06-02 16:36:51 -05:00
|
|
|
return "Conversation history cleared. Let's start fresh!"
|
|
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def clear(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
2025-06-02 16:36:51 -05:00
|
|
|
user_id = update.effective_user.id
|
2025-06-02 16:38:11 -05:00
|
|
|
response_message = await self._clear_logic(user_id)
|
|
|
|
|
await update.message.reply_text(response_message)
|
2025-06-02 16:36:51 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def _status_logic(self) -> str:
|
2025-06-02 16:36:51 -05:00
|
|
|
return await self.bot.get_bot_status()
|
2024-08-19 11:31:06 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def status(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
2025-06-02 16:36:51 -05:00
|
|
|
response_message = await self._status_logic()
|
|
|
|
|
await update.message.reply_text(response_message)
|
2024-08-19 11:31:06 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def _switch_logic(self) -> str:
|
2024-08-19 11:35:29 -05:00
|
|
|
if hasattr(self.bot, 'switch_model'):
|
2025-06-02 16:36:51 -05:00
|
|
|
return await self.bot.switch_model()
|
2024-08-19 11:35:29 -05:00
|
|
|
else:
|
2025-06-02 16:36:51 -05:00
|
|
|
return "Model switching is not supported for this bot."
|
|
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def switch(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
2025-06-02 16:36:51 -05:00
|
|
|
response_message = await self._switch_logic()
|
|
|
|
|
await update.message.reply_text(response_message)
|
2024-08-19 11:31:06 -05:00
|
|
|
|
|
|
|
|
async def update_status_message(self, context: ContextTypes.DEFAULT_TYPE, chat_id: int, message_id: int, status: str):
|
|
|
|
|
keyboard = [
|
|
|
|
|
[InlineKeyboardButton("Abort", callback_data='abort')]
|
|
|
|
|
]
|
|
|
|
|
reply_markup = InlineKeyboardMarkup(keyboard)
|
|
|
|
|
await context.bot.edit_message_text(
|
|
|
|
|
chat_id=chat_id,
|
|
|
|
|
message_id=message_id,
|
|
|
|
|
text=f"Current status: {status}",
|
|
|
|
|
reply_markup=reply_markup
|
|
|
|
|
)
|
|
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def _handle_message_logic(self, user_id: int, user_message: str) -> LogicResult:
|
2024-08-19 11:35:29 -05:00
|
|
|
try:
|
2025-06-02 16:40:24 -05:00
|
|
|
response = await self.bot.handle_message(user_id, user_message)
|
|
|
|
|
processed_response = response.replace("<think>", self.HTML_QUOTE_BLOCK_START).replace("</think>", self.HTML_QUOTE_BLOCK_END)
|
|
|
|
|
return LogicResult(success=True, response_text=processed_response, error_message=None)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logging.error(f"Error in _handle_message_logic for user {user_id}: {str(e)}")
|
|
|
|
|
return LogicResult(success=False, response_text=None, error_message=str(e))
|
2024-08-19 11:35:29 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
|
|
|
user_id = update.effective_user.id
|
|
|
|
|
user_message = update.message.text
|
|
|
|
|
chat_id = update.effective_chat.id
|
|
|
|
|
status_message_obj = None
|
2024-08-19 11:35:29 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
try:
|
|
|
|
|
status_message_obj = await update.message.reply_text(
|
|
|
|
|
"Processing your request...",
|
|
|
|
|
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Abort", callback_data='abort')]])
|
|
|
|
|
)
|
2025-06-02 16:36:51 -05:00
|
|
|
self.bot.set_processing_status(user_id, status_message_obj.message_id)
|
2024-08-19 11:35:29 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
logic_result = await self._handle_message_logic(user_id, user_message)
|
2024-08-19 11:35:29 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
if status_message_obj:
|
|
|
|
|
try:
|
|
|
|
|
await context.bot.delete_message(chat_id=chat_id, message_id=status_message_obj.message_id)
|
|
|
|
|
except Exception as e_del:
|
|
|
|
|
logging.warning(f"Failed to delete status message: {e_del}")
|
2025-06-02 15:23:20 -05:00
|
|
|
self.bot.clear_processing_status(user_id)
|
2025-06-02 14:55:30 -05:00
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
if logic_result["success"]:
|
|
|
|
|
response_text = logic_result["response_text"]
|
|
|
|
|
if response_text:
|
|
|
|
|
if len(response_text) > 4096:
|
|
|
|
|
chunks = [response_text[i:i + 4096] for i in range(0, len(response_text), 4096)]
|
|
|
|
|
for chunk in chunks:
|
|
|
|
|
await update.message.reply_text(chunk)
|
|
|
|
|
await asyncio.sleep(self.chunk_message_sleep_duration)
|
|
|
|
|
else:
|
|
|
|
|
await update.message.reply_text(response_text)
|
|
|
|
|
else:
|
|
|
|
|
logging.warning("Successful logic result but no response text.")
|
|
|
|
|
await update.message.reply_text("Something went unexpectedly well, but I have nothing to say.")
|
2025-06-02 14:55:30 -05:00
|
|
|
else:
|
2025-06-02 16:40:24 -05:00
|
|
|
await update.message.reply_text("Sorry, an error occurred while processing your request.")
|
2024-08-19 11:35:29 -05:00
|
|
|
|
|
|
|
|
except Exception as e:
|
2025-06-02 16:40:24 -05:00
|
|
|
logging.error(f"Outer error in handle_message for user {user_id}: {str(e)}")
|
|
|
|
|
if status_message_obj and self.bot.processing_status.get(user_id):
|
|
|
|
|
self.bot.clear_processing_status(user_id)
|
|
|
|
|
try:
|
|
|
|
|
await update.message.reply_text("Sorry, an unexpected error occurred with the bot.")
|
|
|
|
|
except Exception as e_reply:
|
|
|
|
|
logging.error(f"Failed to send error reply: {e_reply}")
|
|
|
|
|
|
|
|
|
|
async def _abort_processing_logic(self, user_id: int) -> str:
|
2025-06-02 16:38:11 -05:00
|
|
|
return await self.bot.abort_processing(user_id)
|
|
|
|
|
|
2025-06-02 16:40:24 -05:00
|
|
|
async def abort_processing(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
2024-08-19 11:35:29 -05:00
|
|
|
query = update.callback_query
|
2025-06-02 16:40:24 -05:00
|
|
|
await query.answer()
|
2024-08-19 11:35:29 -05:00
|
|
|
user_id = query.from_user.id
|
2025-06-02 16:40:24 -05:00
|
|
|
response_text = await self._abort_processing_logic(user_id)
|
|
|
|
|
await query.edit_message_text(text=response_text)
|
2024-08-19 11:35:29 -05:00
|
|
|
|
2024-08-20 16:52:09 -05:00
|
|
|
async def browse(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
2024-08-21 13:26:34 -05:00
|
|
|
await browse_command(update, context, self.bot)
|
2024-08-20 16:52:09 -05:00
|
|
|
|
2024-08-19 11:31:06 -05:00
|
|
|
def run(self):
|
2025-06-03 13:04:42 -05:00
|
|
|
application = Application.builder().token(self.telegram_bot_token).build()
|
2024-08-19 11:31:06 -05:00
|
|
|
|
|
|
|
|
application.add_handler(CommandHandler("start", self.start))
|
|
|
|
|
application.add_handler(CommandHandler("clear", self.clear))
|
2024-08-19 11:35:29 -05:00
|
|
|
application.add_handler(CommandHandler("switch", self.switch))
|
2024-08-19 11:31:06 -05:00
|
|
|
application.add_handler(CommandHandler("status", self.status))
|
2024-08-20 16:52:09 -05:00
|
|
|
application.add_handler(CommandHandler("browse", self.browse))
|
2025-06-02 15:23:20 -05:00
|
|
|
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))
|
2024-08-19 11:31:06 -05:00
|
|
|
application.add_handler(CallbackQueryHandler(self.abort_processing, pattern='^abort$'))
|
2024-08-20 16:52:09 -05:00
|
|
|
application.add_handler(CallbackQueryHandler(button_callback, pattern='^(browse|file):'))
|
2025-06-02 14:55:30 -05:00
|
|
|
|
2024-08-19 11:35:29 -05:00
|
|
|
logging.info("Bot is running...")
|
2025-06-02 14:55:30 -05:00
|
|
|
application.run_polling()
|