from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery import logging import os from ngrok_api import NgrokAPI # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Store user states for API key setting user_states = {} def setup_handlers(bot: Client): """Setup command handlers for the bot""" @bot.on_message(filters.command("start")) async def start_command(client, message): """Handle /start command""" try: user_name = message.from_user.first_name if message.from_user.first_name else "User" welcome_text = f"Hello {user_name}! 👋\n\nWelcome to the FastAPI Telegram Bot with Ngrok integration!\n\n" welcome_text += "**Available Commands:**\n" welcome_text += "• `/ngrok` - Check ngrok tunnels and edges\n" welcome_text += "• `/setapi` - Set your ngrok API key\n" welcome_text += "• Any text message will be echoed back\n\n" welcome_text += "Get started by setting your ngrok API key with `/setapi`" await message.reply_text(welcome_text) logger.info(f"Handled /start command from user: {message.from_user.id}") except Exception as e: logger.error(f"Error in start_command handler: {e}") await message.reply_text("Sorry, something went wrong. Please try again later.") @bot.on_message(filters.command("ngrok")) async def ngrok_command(client, message): """Handle /ngrok command to show tunnel information""" try: user_id = message.from_user.id # Check if user has API key set ngrok_api_key = os.environ.get(f"NGROK_API_KEY_{user_id}") if not ngrok_api_key: keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("Set API Key", callback_data="set_api_key")] ]) await message.reply_text( "❌ **Ngrok API Key not configured**\n\n" "Please set your ngrok API key first to use this feature.\n" "You can get your API key from: https://dashboard.ngrok.com/get-started/your-authtoken", reply_markup=keyboard ) return # Show loading message loading_msg = await message.reply_text("🔄 Fetching ngrok information...") # Initialize ngrok API ngrok = NgrokAPI(ngrok_api_key) # Fetch data tunnels = await ngrok.get_tunnels() edges = await ngrok.get_edges() endpoints = await ngrok.get_endpoints() # Format and send response info_text = ngrok.format_tunnel_info(tunnels, edges, endpoints) keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("🔄 Refresh", callback_data="refresh_ngrok")], [InlineKeyboardButton("⚙️ Change API Key", callback_data="set_api_key")] ]) await loading_msg.edit_text(info_text, reply_markup=keyboard) logger.info(f"Handled /ngrok command from user: {user_id}") except Exception as e: logger.error(f"Error in ngrok_command handler: {e}") await message.reply_text("❌ Error fetching ngrok information. Please check your API key and try again.") @bot.on_message(filters.command("setapi")) async def setapi_command(client, message): """Handle /setapi command to set ngrok API key""" try: user_id = message.from_user.id user_states[user_id] = "waiting_for_api_key" await message.reply_text( "🔑 **Set Ngrok API Key**\n\n" "Please reply to this message with your ngrok API key.\n\n" "You can find your API key at:\n" "https://dashboard.ngrok.com/get-started/your-authtoken\n\n" "⚠️ **Security Note:** Your API key will be stored securely and only used for ngrok API calls." ) logger.info(f"User {user_id} initiated API key setup") except Exception as e: logger.error(f"Error in setapi_command handler: {e}") await message.reply_text("Sorry, something went wrong. Please try again later.") @bot.on_callback_query() async def callback_handler(client, callback_query: CallbackQuery): """Handle callback queries from inline keyboards""" try: data = callback_query.data user_id = callback_query.from_user.id if data == "set_api_key": user_states[user_id] = "waiting_for_api_key" await callback_query.message.reply_text( "🔑 **Set Ngrok API Key**\n\n" "Please reply to this message with your ngrok API key.\n\n" "You can find your API key at:\n" "https://dashboard.ngrok.com/get-started/your-authtoken\n\n" "⚠️ **Security Note:** Your API key will be stored securely and only used for ngrok API calls." ) await callback_query.answer("Please send your API key") elif data == "refresh_ngrok": # Check if user has API key set ngrok_api_key = os.environ.get(f"NGROK_API_KEY_{user_id}") if not ngrok_api_key: await callback_query.answer("❌ API key not configured", show_alert=True) return await callback_query.answer("🔄 Refreshing...") # Initialize ngrok API and fetch data ngrok = NgrokAPI(ngrok_api_key) tunnels = await ngrok.get_tunnels() edges = await ngrok.get_edges() endpoints = await ngrok.get_endpoints() # Format and update message info_text = ngrok.format_tunnel_info(tunnels, edges, endpoints) keyboard = InlineKeyboardMarkup([ [InlineKeyboardButton("🔄 Refresh", callback_data="refresh_ngrok")], [InlineKeyboardButton("⚙️ Change API Key", callback_data="set_api_key")] ]) # Always try to edit the message since we now include timestamp to make it unique try: await callback_query.message.edit_text(info_text, reply_markup=keyboard) await callback_query.answer("✅ Refreshed") except Exception as edit_error: # If edit still fails, delete the old message and send a new one logger.warning(f"Failed to edit message, replacing with new one: {edit_error}") try: await callback_query.message.delete() except: pass # Ignore delete errors await callback_query.message.reply_text(info_text, reply_markup=keyboard) await callback_query.answer("✅ Updated") except Exception as e: logger.error(f"Error in callback_handler: {e}") await callback_query.answer("❌ Error occurred", show_alert=True) @bot.on_message(filters.text & ~filters.command(["start", "ngrok", "setapi"])) async def text_message_handler(client, message): """Handle text messages - either API key input or echo""" try: user_id = message.from_user.id # Check if user is setting API key if user_states.get(user_id) == "waiting_for_api_key": api_key = message.text.strip() # Basic validation if len(api_key) < 10: await message.reply_text("❌ Invalid API key format. Please try again.") return # Store API key (in production, use secure storage) os.environ[f"NGROK_API_KEY_{user_id}"] = api_key user_states.pop(user_id, None) await message.reply_text( "✅ **API Key Set Successfully!**\n\n" "You can now use `/ngrok` to check your tunnels and edges.\n\n" "🔒 Your API key is stored securely and will only be used for ngrok API calls." ) logger.info(f"API key set for user: {user_id}") return # Echo message if not setting API key await message.reply_text(f"Echo: {message.text}") logger.info(f"Echoed message to user: {user_id}") except Exception as e: logger.error(f"Error in text_message_handler: {e}") await message.reply_text("Sorry, I couldn't process your message.") logger.info("Command handlers setup completed")