import os from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ContextTypes browse_command_bot = None async def browse_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: prompts_dir = "prompts" await navigate_to(prompts_dir, update.message.reply_text) async def navigate_to(directory: str, updateMethod) -> None: try: subdirs, files = await get_files_and_directories(directory) existing_buttons = [] if (directory != "prompts"): parent_directory = os.path.split(directory)[0] existing_buttons.append([InlineKeyboardButton("↩️ Back", callback_data=f"browse:{parent_directory}")]) reply_markup = await create_keyboard(subdirs, files, existing_buttons) await updateMethod("Browse files and directories:", reply_markup=reply_markup) except FileNotFoundError: await updateMethod(f"The {directory} directory does not exist.") except Exception as e: await updateMethod(f"An error occurred: {str(e)}") async def create_keyboard(subdirs, files, existing_buttons) -> InlineKeyboardMarkup: keyboard = existing_buttons for subdir in subdirs: keyboard.append([InlineKeyboardButton(subdir, callback_data=f"browse:{subdir}")]) for file in files: keyboard.append([InlineKeyboardButton(file, callback_data=f"file:{file}")]) return InlineKeyboardMarkup(keyboard) async def get_files_and_directories(directory: str) -> list: # Get all items in the prompts directory items = os.listdir(directory) # Separate and sort subdirectories and files subdirs = sorted([os.path.join(directory, item) for item in items if os.path.isdir(os.path.join(directory, item))]) files = sorted([os.path.join(directory, item) for item in items if os.path.isfile(os.path.join(directory, item))]) return subdirs, files # This function will need to be called when a button is pressed async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE, browse_command_bot) -> None: query = update.callback_query await query.answer() data = query.data if data.startswith("browse:"): # Handle subdirectory navigation (for future implementation) subdir = data.split(":")[1] await navigate_to(subdir, query.edit_message_text) elif data.startswith("file:"): # Handle file selection file_path = data.split(":")[1] os.environ['SYSTEM_PROMPT_PATH'] = file_path if hasattr(browse_command_bot, 'system_prompt_path'): browse_command_bot.system_prompt_path = file_path browse_command_bot.system_prompt = browse_command_bot.load_system_prompt() await query.edit_message_text(f"Selected: {file_path}. System prompt updated.")