File size: 9,511 Bytes
b28ce06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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")