nexus3rd commited on
Commit
3d736e4
·
1 Parent(s): 2e7aac9
Files changed (1) hide show
  1. bot.py +2 -298
bot.py CHANGED
@@ -1,309 +1,13 @@
1
- from pyrogram import Client, filters
2
- from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery, Message
3
- from typing import Optional
4
- import threading
5
- import asyncio
6
- import os
7
- import math
8
- import aiohttp
9
- import time
10
- from datetime import datetime, timezone
11
- import pytz
12
- from dotenv import load_dotenv
13
- import requests
14
- from fastapi import HTTPException
15
- try:
16
- import re2 as re
17
- except ImportError:
18
- import re
19
-
20
- load_dotenv()
21
-
22
- api_id = os.getenv("API_ID")
23
- api_hash = os.getenv("API_HASH")
24
- bot_token = os.getenv("BOT_TOKEN")
25
- default_api_key = os.getenv("NGROK_API_KEY")
26
-
27
- bot = Client("my_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)
28
-
29
- user_ids = set()
30
- notified_tunnels = set()
31
- user_api_keys = {}
32
-
33
- def is_valid_ngrok_api_key(api_key: str) -> bool:
34
- return bool(re.match(r"^2w[a-zA-Z0-9_]{22,48}$", api_key))
35
-
36
- def fetch_ngrok_data(user_id):
37
- api_key = user_api_keys.get(user_id, default_api_key)
38
- if not api_key:
39
- raise Exception("Ngrok API key not found.")
40
-
41
- headers = {
42
- "Authorization": f"Bearer {api_key}",
43
- "Ngrok-Version": "2"
44
- }
45
-
46
- try:
47
- response = requests.get("https://api.ngrok.com/tunnels", headers=headers)
48
- response.raise_for_status()
49
- return response.json().get("tunnels", [])
50
- except requests.RequestException as e:
51
- raise Exception(f"Error fetching Ngrok data: {str(e)}")
52
-
53
- def get_ngrok_tunnels(user_id):
54
- tunnels = fetch_ngrok_data(user_id)
55
- endpoints = [tunnel.get("public_url", "").replace("tcp://", "")
56
- for tunnel in tunnels if tunnel.get("proto") == "tcp"]
57
- return endpoints
58
-
59
- def get_ngrok_runtime(user_id):
60
- try:
61
- tunnels = fetch_ngrok_data(user_id)
62
- tcp_tunnel = next((tunnel for tunnel in tunnels if tunnel["proto"] == "tcp"), None)
63
-
64
- if not tcp_tunnel:
65
- return "❌ No active TCP tunnels found"
66
-
67
- start_time = datetime.fromisoformat(tcp_tunnel["started_at"].replace("Z", "+00:00")).astimezone(timezone.utc)
68
- current_time = datetime.now(timezone.utc)
69
- elapsed_time = current_time - start_time
70
-
71
- elapsed_hours, remainder = divmod(elapsed_time.total_seconds(), 3600)
72
- elapsed_minutes, _ = divmod(remainder, 60)
73
-
74
- runtime_message = f"🟢 Ngrok TCP tunnel running for {int(elapsed_hours)}h {int(elapsed_minutes)}m" if elapsed_hours > 0 else f"🟢 Ngrok TCP tunnel running for {int(elapsed_minutes)} minutes"
75
-
76
- endpoints = get_ngrok_tunnels(user_id)
77
- if endpoints:
78
- endpoint_message = "\n".join(endpoints)
79
- else:
80
- endpoint_message = "No TCP endpoints available."
81
-
82
- return f"{runtime_message}\n\n<b>Endpoints:</b>\n<code>{endpoint_message}</code>"
83
-
84
- except Exception as e:
85
- return f"Error retrieving TCP endpoints: {str(e)}"
86
-
87
- @bot.on_callback_query(filters.regex("get_tcp"))
88
- async def on_callback_query(client, callback_query):
89
- try:
90
- endpoints = get_ngrok_tunnels()
91
- if endpoints:
92
- await callback_query.message.edit_text("\n".join(endpoints), reply_markup=None)
93
- else:
94
- await callback_query.message.edit_text("No TCP endpoints available.", reply_markup=None)
95
- except Exception as e:
96
- await callback_query.answer(f"Error retrieving TCP endpoints: {str(e)}", show_alert=True)
97
-
98
- @bot.on_message(filters.command("start"))
99
- async def start(client: Client, message: Message):
100
- user_id = message.from_user.id
101
-
102
- buttons = InlineKeyboardMarkup(
103
- [
104
- [
105
- InlineKeyboardButton("🔄 Refresh", callback_data=f"refresh_ngrok|{user_id}|{message.id}"),
106
- InlineKeyboardButton("❌ Close", callback_data=f"close_ngrok|{user_id}|{message.id}")
107
- ],
108
- [InlineKeyboardButton("Set API", callback_data=f"set_api|{user_id}|{message.id}")
109
- ]
110
- ]
111
- )
112
-
113
- status = get_ngrok_runtime(user_id)
114
- await message.reply(f"**Ngrok Status Monitor**\n\n{status}", reply_markup=buttons)
115
-
116
- async def check_for_new_tcp_tunnels(client: Client, user_id):
117
- """Check for new TCP tunnels and notify if a new one is detected."""
118
- try:
119
- tunnels = fetch_ngrok_data(user_id)
120
- for tunnel in tunnels:
121
- if tunnel.get("proto") == "tcp":
122
- public_url = tunnel.get("public_url", "")
123
- if public_url not in notified_tunnels:
124
- notified_tunnels.add(public_url)
125
- await client.send_message(
126
- chat_id=user_id,
127
- text=f"New TCP Tunnel Detected: {public_url}"
128
- )
129
- except Exception as e:
130
- print(f"Error checking tunnels: {e}")
131
-
132
- async def monitor_tunnels(client: Client, user_id):
133
- """Monitor tunnels continuously for new ones."""
134
- while True:
135
- await check_for_new_tcp_tunnels(client, user_id)
136
- await asyncio.sleep(60) # Adjust this interval as needed
137
-
138
- @bot.on_callback_query(filters.regex(r"^set_api\|(\d+)\|(\d+)$"))
139
- async def set_api_callback(client: Client, callback_query: CallbackQuery):
140
- user_id = int(callback_query.matches[0].group(1))
141
- prompt_message = await callback_query.message.reply("Please send your Ngrok API key as a reply to this message.")
142
- await callback_query.answer()
143
-
144
- @bot.on_message(filters.reply & filters.create(lambda _, __, message: message.reply_to_message and message.reply_to_message.id == prompt_message.id))
145
- async def capture_api_key(client: Client, message: Message):
146
- api_key = message.text.strip()
147
- if is_valid_ngrok_api_key(api_key):
148
- user_api_keys[user_id] = api_key
149
- await message.reply("Ngrok API key set successfully!")
150
- await prompt_message.delete()
151
- # Start monitoring tunnels after setting the API key
152
- asyncio.create_task(monitor_tunnels(client, user_id))
153
- else:
154
- await message.reply("Invalid API key format. Please try again with a valid Ngrok API key.")
155
-
156
- @bot.on_callback_query(filters.regex(r"^refresh_ngrok\|(\d+)\|(\d+)$"))
157
- async def refresh_ngrok(client: Client, callback_query: CallbackQuery):
158
- user_id = int(callback_query.matches[0].group(1))
159
- new_status = get_ngrok_runtime(user_id)
160
- current_text = callback_query.message.text
161
-
162
- if new_status != current_text:
163
- try:
164
- await callback_query.message.edit_text(
165
- f"<b>Ngrok Tunnel</b>\n\n{new_status}",
166
- reply_markup=callback_query.message.reply_markup
167
- )
168
- except Exception as e:
169
- print(f"Error while editing message: {e}")
170
- else:
171
- print("No changes detected; skipping message edit.")
172
-
173
- await callback_query.answer("Status updated!", show_alert=False)
174
-
175
- @bot.on_callback_query(filters.regex(r"^close_ngrok\|(\d+)\|(\d+)$"))
176
- async def close_ngrok(client: Client, callback_query: CallbackQuery):
177
- try:
178
- user_id, original_message_id = map(int, callback_query.data.split("|")[1:])
179
- await callback_query.message.delete()
180
- await client.delete_messages(chat_id=callback_query.message.chat.id, message_ids=original_message_id)
181
- except Exception as e:
182
- print(f"Error while deleting message: {e}")
183
-
184
- await callback_query.answer("Message closed!", show_alert=False)
185
-
186
- def get_progress_bar_string(pct) -> str:
187
- if isinstance(pct, int):
188
- pct = float(pct)
189
- elif not isinstance(pct, float):
190
- pct = float(pct.strip("%"))
191
- p = min(max(pct, 0), 100)
192
- cFull = int(p // 8)
193
- p_str = "■" * cFull
194
- p_str += "□" * (12 - cFull)
195
- return f"[{p_str}]"
196
-
197
- def format_size(size_bytes) -> str:
198
- """Convert bytes to a human-readable format."""
199
- if size_bytes == 0:
200
- return "0B"
201
- size_name = ("B", "KB", "MB", "GB", "TB")
202
- i = int(math.floor(math.log(size_bytes, 1024)))
203
- p = math.pow(1024, i)
204
- s = round(size_bytes / p, 2)
205
- return f"{s} {size_name[i]}"
206
-
207
- # Function to extract tweet IDs
208
- def extract_tweet_ids(text: str) -> Optional[list[str]]:
209
- """Extract tweet IDs from message."""
210
- # For t.co links
211
- unshortened_links = ''
212
- for link in re.findall(r"t\.co\/[a-zA-Z0-9]+", text):
213
- try:
214
- unshortened_link = requests.get('https://' + link).url
215
- unshortened_links += '\n' + unshortened_link
216
- except:
217
- pass
218
-
219
- # Parse IDs from received text
220
- tweet_ids = re.findall(r"(?:twitter|x)\.com/.{1,15}/(?:web|status(?:es)?)/([0-9]{1,20})", text + unshortened_links)
221
- tweet_ids = list(dict.fromkeys(tweet_ids))
222
- return tweet_ids or None
223
-
224
- # Function to scrape media
225
- def scrape_media(tweet_id: int) -> list[dict]:
226
- r = requests.get(f'https://api.vxtwitter.com/Twitter/status/{tweet_id}')
227
- r.raise_for_status()
228
- try:
229
- return r.json()['media_extended']
230
- except requests.exceptions.JSONDecodeError:
231
- if match := re.search(r'<meta content="(.*?)" property="og:description" />', r.text):
232
- raise Exception(f'API returned error: {html.unescape(match.group(1))}')
233
- raise
234
-
235
- async def get_media_size(media_url: str) -> int:
236
- """Get the content length of the media."""
237
- async with aiohttp.ClientSession() as session:
238
- async with session.head(media_url) as resp:
239
- content_length = resp.headers.get('CONTENT-LENGTH')
240
- if content_length is not None:
241
- return int(content_length)
242
- else:
243
- return -1 # Indicate that the size is unknown
244
-
245
- async def simulate_download_progress(media_info: dict, message: Message):
246
- # Use aiohttp to get the actual size of the media
247
- total_size = await get_media_size(media_info['url'])
248
-
249
- for progress in range(0, 101, 10):
250
- progress_bar = get_progress_bar_string(progress)
251
- if total_size > 0:
252
- size_readable = format_size(total_size * (progress / 100))
253
- progress_text = f"{progress_bar} {progress}% ({size_readable})"
254
- else:
255
- progress_text = f"{progress_bar} {progress}% (Size unknown)"
256
-
257
- await message.edit_text(f"Downloading: {progress_text}")
258
- await asyncio.sleep(0.5)
259
-
260
- # Function to reply with media
261
- async def reply_media(client: Client, chat_id: int, tweet_media: list):
262
- """Reply to message with supported media."""
263
- photos = [media for media in tweet_media if media["type"] == "image"]
264
- gifs = [media for media in tweet_media if media["type"] == "gif"]
265
- videos = [media for media in tweet_media if media["type"] == "video"]
266
-
267
- message = await client.send_message(chat_id, "Starting download...") # Send initial message
268
-
269
- if photos:
270
- await simulate_download_progress(photos[0], message)
271
- await client.send_photo(chat_id, photos[0]['url'])
272
- if gifs:
273
- await simulate_download_progress(gifs[0], message)
274
- await client.send_animation(chat_id, gifs[0]['url'])
275
- elif videos:
276
- await simulate_download_progress(videos[0], message)
277
- await client.send_video(chat_id, videos[0]['url'])
278
-
279
- await message.delete() # Delete the progress message after completion
280
-
281
- @bot.on_message(filters.command("Twitter"))
282
- async def download_twitter_media(client: Client, message: Message):
283
- tweet_ids = extract_tweet_ids(message.text)
284
- if not tweet_ids:
285
- await message.reply_text("No tweet IDs found!")
286
- return
287
-
288
- for tweet_id in tweet_ids:
289
- try:
290
- tweet_media = scrape_media(tweet_id)
291
- await reply_media(client, message.chat.id, tweet_media)
292
- except Exception as e:
293
- await message.reply_text(f"Failed to scrape media: {e}")
294
-
295
-
296
  def start_bot():
297
- # Create a new event loop for the thread
298
  loop = asyncio.new_event_loop()
299
  asyncio.set_event_loop(loop)
300
 
301
- # Define the main function to run with the bot
302
  async def main():
303
  async with bot:
 
 
304
  await asyncio.Future() # Run forever
305
 
306
- # Run the bot with the event loop
307
  loop.run_until_complete(main())
308
 
309
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def start_bot():
 
2
  loop = asyncio.new_event_loop()
3
  asyncio.set_event_loop(loop)
4
 
 
5
  async def main():
6
  async with bot:
7
+ # Perform initial check for TCP tunnels on startup
8
+ await initial_tunnel_check(bot)
9
  await asyncio.Future() # Run forever
10
 
 
11
  loop.run_until_complete(main())
12
 
13
  if __name__ == "__main__":