nexus3rd commited on
Commit
f484b72
·
1 Parent(s): 3d736e4
Files changed (1) hide show
  1. bot.py +292 -0
bot.py CHANGED
@@ -1,3 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def start_bot():
2
  loop = asyncio.new_event_loop()
3
  asyncio.set_event_loop(loop)
 
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_active_tcp_tunnels(client: Client, user_id):
117
+ """Check for active 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"Active TCP Tunnel Detected on Startup: {public_url}"
128
+ )
129
+ except Exception as e:
130
+ print(f"Error checking tunnels: {e}")
131
+
132
+ async def initial_tunnel_check(client: Client):
133
+ """Perform an initial check for TCP tunnels when the bot starts."""
134
+ for user_id in user_api_keys:
135
+ await check_for_active_tcp_tunnels(client, user_id)
136
+
137
+ @bot.on_callback_query(filters.regex(r"^set_api\|(\d+)\|(\d+)$"))
138
+ async def set_api_callback(client: Client, callback_query: CallbackQuery):
139
+ user_id = int(callback_query.matches[0].group(1))
140
+ prompt_message = await callback_query.message.reply("Please send your Ngrok API key as a reply to this message.")
141
+ await callback_query.answer()
142
+
143
+ @bot.on_message(filters.reply & filters.create(lambda _, __, message: message.reply_to_message and message.reply_to_message.id == prompt_message.id))
144
+ async def capture_api_key(client: Client, message: Message):
145
+ api_key = message.text.strip()
146
+ if is_valid_ngrok_api_key(api_key):
147
+ user_api_keys[user_id] = api_key
148
+ await message.reply("Ngrok API key set successfully!")
149
+ await prompt_message.delete()
150
+ else:
151
+ await message.reply("Invalid API key format. Please try again with a valid Ngrok API key.")
152
+
153
+ @bot.on_callback_query(filters.regex(r"^refresh_ngrok\|(\d+)\|(\d+)$"))
154
+ async def refresh_ngrok(client: Client, callback_query: CallbackQuery):
155
+ user_id = int(callback_query.matches[0].group(1))
156
+ new_status = get_ngrok_runtime(user_id)
157
+ current_text = callback_query.message.text
158
+
159
+ if new_status != current_text:
160
+ try:
161
+ await callback_query.message.edit_text(
162
+ f"<b>Ngrok Tunnel</b>\n\n{new_status}",
163
+ reply_markup=callback_query.message.reply_markup
164
+ )
165
+ except Exception as e:
166
+ print(f"Error while editing message: {e}")
167
+ else:
168
+ print("No changes detected; skipping message edit.")
169
+
170
+ await callback_query.answer("Status updated!", show_alert=False)
171
+
172
+ @bot.on_callback_query(filters.regex(r"^close_ngrok\|(\d+)\|(\d+)$"))
173
+ async def close_ngrok(client: Client, callback_query: CallbackQuery):
174
+ try:
175
+ user_id, original_message_id = map(int, callback_query.data.split("|")[1:])
176
+ await callback_query.message.delete()
177
+ await client.delete_messages(chat_id=callback_query.message.chat.id, message_ids=original_message_id)
178
+ except Exception as e:
179
+ print(f"Error while deleting message: {e}")
180
+
181
+ await callback_query.answer("Message closed!", show_alert=False)
182
+
183
+ def get_progress_bar_string(pct) -> str:
184
+ if isinstance(pct, int):
185
+ pct = float(pct)
186
+ elif not isinstance(pct, float):
187
+ pct = float(pct.strip("%"))
188
+ p = min(max(pct, 0), 100)
189
+ cFull = int(p // 8)
190
+ p_str = "■" * cFull
191
+ p_str += "□" * (12 - cFull)
192
+ return f"[{p_str}]"
193
+
194
+ def format_size(size_bytes) -> str:
195
+ """Convert bytes to a human-readable format."""
196
+ if size_bytes == 0:
197
+ return "0B"
198
+ size_name = ("B", "KB", "MB", "GB", "TB")
199
+ i = int(math.floor(math.log(size_bytes, 1024)))
200
+ p = math.pow(1024, i)
201
+ s = round(size_bytes / p, 2)
202
+ return f"{s} {size_name[i]}"
203
+
204
+ # Function to extract tweet IDs
205
+ def extract_tweet_ids(text: str) -> Optional[list[str]]:
206
+ """Extract tweet IDs from message."""
207
+ # For t.co links
208
+ unshortened_links = ''
209
+ for link in re.findall(r"t\.co\/[a-zA-Z0-9]+", text):
210
+ try:
211
+ unshortened_link = requests.get('https://' + link).url
212
+ unshortened_links += '\n' + unshortened_link
213
+ except:
214
+ pass
215
+
216
+ # Parse IDs from received text
217
+ tweet_ids = re.findall(r"(?:twitter|x)\.com/.{1,15}/(?:web|status(?:es)?)/([0-9]{1,20})", text + unshortened_links)
218
+ tweet_ids = list(dict.fromkeys(tweet_ids))
219
+ return tweet_ids or None
220
+
221
+ # Function to scrape media
222
+ def scrape_media(tweet_id: int) -> list[dict]:
223
+ r = requests.get(f'https://api.vxtwitter.com/Twitter/status/{tweet_id}')
224
+ r.raise_for_status()
225
+ try:
226
+ return r.json()['media_extended']
227
+ except requests.exceptions.JSONDecodeError:
228
+ if match := re.search(r'<meta content="(.*?)" property="og:description" />', r.text):
229
+ raise Exception(f'API returned error: {html.unescape(match.group(1))}')
230
+ raise
231
+
232
+ async def get_media_size(media_url: str) -> int:
233
+ """Get the content length of the media."""
234
+ async with aiohttp.ClientSession() as session:
235
+ async with session.head(media_url) as resp:
236
+ content_length = resp.headers.get('CONTENT-LENGTH')
237
+ if content_length is not None:
238
+ return int(content_length)
239
+ else:
240
+ return -1 # Indicate that the size is unknown
241
+
242
+ async def simulate_download_progress(media_info: dict, message: Message):
243
+ # Use aiohttp to get the actual size of the media
244
+ total_size = await get_media_size(media_info['url'])
245
+
246
+ for progress in range(0, 101, 10):
247
+ progress_bar = get_progress_bar_string(progress)
248
+ if total_size > 0:
249
+ size_readable = format_size(total_size * (progress / 100))
250
+ progress_text = f"{progress_bar} {progress}% ({size_readable})"
251
+ else:
252
+ progress_text = f"{progress_bar} {progress}% (Size unknown)"
253
+
254
+ await message.edit_text(f"Downloading: {progress_text}")
255
+ await asyncio.sleep(0.5)
256
+
257
+ # Function to reply with media
258
+ async def reply_media(client: Client, chat_id: int, tweet_media: list):
259
+ """Reply to message with supported media."""
260
+ photos = [media for media in tweet_media if media["type"] == "image"]
261
+ gifs = [media for media in tweet_media if media["type"] == "gif"]
262
+ videos = [media for media in tweet_media if media["type"] == "video"]
263
+
264
+ message = await client.send_message(chat_id, "Starting download...") # Send initial message
265
+
266
+ if photos:
267
+ await simulate_download_progress(photos[0], message)
268
+ await client.send_photo(chat_id, photos[0]['url'])
269
+ if gifs:
270
+ await simulate_download_progress(gifs[0], message)
271
+ await client.send_animation(chat_id, gifs[0]['url'])
272
+ elif videos:
273
+ await simulate_download_progress(videos[0], message)
274
+ await client.send_video(chat_id, videos[0]['url'])
275
+
276
+ await message.delete() # Delete the progress message after completion
277
+
278
+ @bot.on_message(filters.command("Twitter"))
279
+ async def download_twitter_media(client: Client, message: Message):
280
+ tweet_ids = extract_tweet_ids(message.text)
281
+ if not tweet_ids:
282
+ await message.reply_text("No tweet IDs found!")
283
+ return
284
+
285
+ for tweet_id in tweet_ids:
286
+ try:
287
+ tweet_media = scrape_media(tweet_id)
288
+ await reply_media(client, message.chat.id, tweet_media)
289
+ except Exception as e:
290
+ await message.reply_text(f"Failed to scrape media: {e}")
291
+
292
+
293
  def start_bot():
294
  loop = asyncio.new_event_loop()
295
  asyncio.set_event_loop(loop)