Fyaz Mohammed commited on
Commit
68fdacf
·
unverified ·
1 Parent(s): 8b5c293

New /speedtest admin command: run network speed tests, view live progress, and share results as images or text.

README.md CHANGED
@@ -241,6 +241,7 @@ Copy `config_sample.env` to `config.env` and fill in your values.
241
  | `/log` | Send bot logs. |
242
  | `/restart` | Restart the bot. |
243
  | `/shell` | Execute a shell command. |
 
244
  | `/users` | Show total number of users. |
245
  | `/authorize` | Permanently authorize a user to use the bot (bypasses token system). |
246
  | `/deauthorize` | Remove permanent authorization from a user. |
@@ -268,6 +269,7 @@ listauth - [Admin] List authorized
268
  log - [Admin] Send bot logs
269
  restart - [Admin] Restart the bot
270
  shell - [Admin] Execute shell command
 
271
  ```
272
 
273
  </details>
@@ -312,6 +314,16 @@ Thunder implements a sophisticated multi-tier rate limiting system designed for
312
  - **Queue Size Limits**: Configurable maximum queue size.
313
  - **Flood Protection**: Built-in protection against Telegram flood waits.
314
 
 
 
 
 
 
 
 
 
 
 
315
  ## Production Deployment Guide
316
 
317
  ### Custom Domain & FQDN System
 
241
  | `/log` | Send bot logs. |
242
  | `/restart` | Restart the bot. |
243
  | `/shell` | Execute a shell command. |
244
+ | `/speedtest` | Run network speed test and display comprehensive results. |
245
  | `/users` | Show total number of users. |
246
  | `/authorize` | Permanently authorize a user to use the bot (bypasses token system). |
247
  | `/deauthorize` | Remove permanent authorization from a user. |
 
269
  log - [Admin] Send bot logs
270
  restart - [Admin] Restart the bot
271
  shell - [Admin] Execute shell command
272
+ speedtest - [Admin] Run network speed test
273
  ```
274
 
275
  </details>
 
314
  - **Queue Size Limits**: Configurable maximum queue size.
315
  - **Flood Protection**: Built-in protection against Telegram flood waits.
316
 
317
+ ### Network Speed Testing
318
+
319
+ Monitor server performance with built-in speed testing:
320
+
321
+ ```bash
322
+ /speedtest
323
+ ```
324
+
325
+ Features include download/upload speeds, latency measurements, and shareable result images for performance monitoring.
326
+
327
  ## Production Deployment Guide
328
 
329
  ### Custom Domain & FQDN System
Thunder/__init__.py CHANGED
@@ -3,4 +3,4 @@
3
  import time
4
 
5
  StartTime = time.time()
6
- __version__ = "1.9.5"
 
3
  import time
4
 
5
  StartTime = time.time()
6
+ __version__ = "1.9.6"
Thunder/bot/plugins/admin.py CHANGED
@@ -35,6 +35,7 @@ from Thunder.utils.messages import (
35
  MSG_NO_AUTH_USERS, MSG_RESTARTING, MSG_SHELL_ERROR,
36
  MSG_SHELL_EXECUTING, MSG_SHELL_NO_OUTPUT, MSG_SHELL_OUTPUT,
37
  MSG_SHELL_OUTPUT_STDERR, MSG_SHELL_OUTPUT_STDOUT, MSG_SHELL_USAGE,
 
38
  MSG_STATUS_ERROR, MSG_SYSTEM_STATS, MSG_SYSTEM_STATUS,
39
  MSG_UNBAN_USAGE, MSG_USER_BANNED_NOTIFICATION,
40
  MSG_USER_NOT_IN_BAN_LIST, MSG_USER_UNBANNED_NOTIFICATION,
@@ -42,6 +43,7 @@ from Thunder.utils.messages import (
42
  )
43
  from Thunder.utils.time_format import get_readable_time
44
  from Thunder.utils.tokens import authorize, deauthorize, list_allowed
 
45
  from Thunder.vars import Var
46
 
47
  owner_filter = filters.private & filters.user(Var.OWNER_ID)
@@ -195,7 +197,6 @@ async def deauthorize_command(client: Client, message: Message):
195
  await reply(message, text=MSG_INVALID_USER_ID)
196
  except Exception as e:
197
  logger.error(f"Error in deauthorize_command: {e}", exc_info=True)
198
-
199
  await reply(message, text=MSG_ERROR_GENERIC)
200
 
201
 
@@ -353,3 +354,60 @@ async def run_shell_command(client: Client, message: Message):
353
  message,
354
  text=MSG_SHELL_ERROR.format(error=html.escape(str(e))),
355
  parse_mode=ParseMode.HTML)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  MSG_NO_AUTH_USERS, MSG_RESTARTING, MSG_SHELL_ERROR,
36
  MSG_SHELL_EXECUTING, MSG_SHELL_NO_OUTPUT, MSG_SHELL_OUTPUT,
37
  MSG_SHELL_OUTPUT_STDERR, MSG_SHELL_OUTPUT_STDOUT, MSG_SHELL_USAGE,
38
+ MSG_SPEEDTEST_ERROR, MSG_SPEEDTEST_INIT, MSG_SPEEDTEST_RESULT,
39
  MSG_STATUS_ERROR, MSG_SYSTEM_STATS, MSG_SYSTEM_STATUS,
40
  MSG_UNBAN_USAGE, MSG_USER_BANNED_NOTIFICATION,
41
  MSG_USER_NOT_IN_BAN_LIST, MSG_USER_UNBANNED_NOTIFICATION,
 
43
  )
44
  from Thunder.utils.time_format import get_readable_time
45
  from Thunder.utils.tokens import authorize, deauthorize, list_allowed
46
+ from Thunder.utils.speedtest import run_speedtest
47
  from Thunder.vars import Var
48
 
49
  owner_filter = filters.private & filters.user(Var.OWNER_ID)
 
197
  await reply(message, text=MSG_INVALID_USER_ID)
198
  except Exception as e:
199
  logger.error(f"Error in deauthorize_command: {e}", exc_info=True)
 
200
  await reply(message, text=MSG_ERROR_GENERIC)
201
 
202
 
 
354
  message,
355
  text=MSG_SHELL_ERROR.format(error=html.escape(str(e))),
356
  parse_mode=ParseMode.HTML)
357
+
358
+
359
+ @StreamBot.on_message(filters.command("speedtest") & owner_filter)
360
+ async def speedtest_command(client: Client, message: Message):
361
+ status_msg = await reply(message, text=MSG_SPEEDTEST_INIT)
362
+ try:
363
+ result_dict, image_url = await run_speedtest()
364
+ if result_dict is None:
365
+ await handle_flood_wait(status_msg.edit_text, MSG_SPEEDTEST_ERROR)
366
+ return
367
+
368
+ result_text = _format_speedtest_result(result_dict)
369
+ await _send_result(message, status_msg, result_text, image_url)
370
+ except Exception as e:
371
+ logger.error(f"Error in speedtest_command: {e}", exc_info=True)
372
+ try:
373
+ await handle_flood_wait(status_msg.edit_text, MSG_SPEEDTEST_ERROR)
374
+ except Exception:
375
+ await reply(message, text=MSG_SPEEDTEST_ERROR)
376
+
377
+
378
+ def _format_speedtest_result(result_dict: dict) -> str:
379
+ s, c = result_dict['server'], result_dict['client']
380
+ return MSG_SPEEDTEST_RESULT.format(
381
+ download_mbps=_fmt(result_dict['download_mbps']),
382
+ upload_mbps=_fmt(result_dict['upload_mbps']),
383
+ download_bps=humanbytes(result_dict['download_bps']),
384
+ upload_bps=humanbytes(result_dict['upload_bps']),
385
+ ping=_fmt(result_dict['ping']),
386
+ timestamp=result_dict['timestamp'],
387
+ bytes_sent=humanbytes(result_dict['bytes_sent']),
388
+ bytes_received=humanbytes(result_dict['bytes_received']),
389
+ server_name=s['name'],
390
+ server_country=f"{s['country']} ({s['cc']})",
391
+ server_sponsor=s['sponsor'],
392
+ server_latency=_fmt(s['latency']),
393
+ server_lat=_fmt(s['lat'], 4),
394
+ server_lon=_fmt(s['lon'], 4),
395
+ client_ip=c['ip'],
396
+ client_lat=_fmt(c['lat'], 4),
397
+ client_lon=_fmt(c['lon'], 4),
398
+ client_isp=c['isp'],
399
+ client_isprating=c['isprating'],
400
+ client_country=c['country']
401
+ )
402
+
403
+
404
+ async def _send_result(message: Message, status_msg: Message, result_text: str, image_url: str):
405
+ if image_url:
406
+ await handle_flood_wait(message.reply_photo, image_url, caption=result_text, parse_mode=ParseMode.MARKDOWN)
407
+ await handle_flood_wait(status_msg.delete)
408
+ else:
409
+ await handle_flood_wait(status_msg.edit_text, result_text, parse_mode=ParseMode.MARKDOWN)
410
+
411
+
412
+ def _fmt(value, decimals: int = 2) -> str:
413
+ return f"{float(value):.{decimals}f}"
Thunder/utils/commands.py CHANGED
@@ -20,6 +20,7 @@ def get_commands():
20
  "log": "(Admin) Send bot logs",
21
  "restart": "(Admin) Restart the bot",
22
  "shell": "(Admin) Execute a shell command",
 
23
  "users": "(Admin) Show the total number of users",
24
  "authorize": "(Admin) Grant permanent access to a user",
25
  "deauthorize": "(Admin) Remove permanent access from a user",
@@ -34,4 +35,4 @@ async def set_commands():
34
  if commands:
35
  await StreamBot.set_bot_commands(commands)
36
  except Exception as e:
37
- logger.error(f"Failed to set bot commands: {e}", exc_info=True)
 
20
  "log": "(Admin) Send bot logs",
21
  "restart": "(Admin) Restart the bot",
22
  "shell": "(Admin) Execute a shell command",
23
+ "speedtest": "(Admin) Run network speed test",
24
  "users": "(Admin) Show the total number of users",
25
  "authorize": "(Admin) Grant permanent access to a user",
26
  "deauthorize": "(Admin) Remove permanent access from a user",
 
35
  if commands:
36
  await StreamBot.set_bot_commands(commands)
37
  except Exception as e:
38
+ logger.error(f"Failed to set bot commands: {e}", exc_info=True)
Thunder/utils/messages.py CHANGED
@@ -340,6 +340,32 @@ MSG_SYSTEM_STATUS = (
340
  "{workload_items}\n"
341
  "> ♻️ **Version:** `{version}`"
342
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  MSG_SYSTEM_STATS = (
344
  "📊 **System Statistics**\n\n"
345
  "> System Uptime: {sys_uptime}\n"
 
340
  "{workload_items}\n"
341
  "> ♻️ **Version:** `{version}`"
342
  )
343
+
344
+ # ------ Speedtest Messages ------
345
+ MSG_SPEEDTEST_INIT = "🚀 **Running Speed Test...** ⏳\n\n> Please wait while I test your connection speed."
346
+ MSG_SPEEDTEST_ERROR = "❌ **Speed Test Failed!**\n\n> Unable to complete the speed test. Please try again later."
347
+ MSG_SPEEDTEST_RESULT = (
348
+ "⚡ **Speed Test Results**\n\n"
349
+ "**SPEEDTEST INFO:**\n"
350
+ "> **Download:** `{download_mbps} Mbps` (`{download_bps} B/s`)\n"
351
+ "> **Upload:** `{upload_mbps} Mbps` (`{upload_bps} B/s`)\n"
352
+ "> **Ping:** `{ping} ms`\n"
353
+ "> **Timestamp:** `{timestamp}`\n"
354
+ "> **Data Sent:** `{bytes_sent}`\n"
355
+ "> **Data Received:** `{bytes_received}`\n\n"
356
+ "**SERVER INFO:**\n"
357
+ "> **Name:** `{server_name}`\n"
358
+ "> **Country:** `{server_country}`\n"
359
+ "> **Sponsor:** `{server_sponsor}`\n"
360
+ "> **Latency:** `{server_latency} ms`\n"
361
+ "> **Coordinates:** `{server_lat}, {server_lon}`\n\n"
362
+ "**CLIENT DETAILS:**\n"
363
+ "> **IP:** `{client_ip}`\n"
364
+ "> **Location:** `{client_lat}, {client_lon}`\n"
365
+ "> **ISP:** `{client_isp}`\n"
366
+ "> **ISP Rating:** `{client_isprating}`\n"
367
+ "> **Country:** `{client_country}`"
368
+ )
369
  MSG_SYSTEM_STATS = (
370
  "📊 **System Statistics**\n\n"
371
  "> System Uptime: {sys_uptime}\n"
Thunder/utils/speedtest.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Thunder/utils/speedtest.py
2
+
3
+ import asyncio
4
+ from typing import Optional, Tuple, Dict, Any
5
+
6
+ import speedtest
7
+ from Thunder.utils.logger import logger
8
+
9
+
10
+ async def run_speedtest() -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
11
+ try:
12
+ return await asyncio.to_thread(_perform_speedtest)
13
+ except Exception as e:
14
+ logger.error(f"Speedtest failed: {e}", exc_info=True)
15
+ return None, None
16
+
17
+
18
+ def _perform_speedtest() -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
19
+ try:
20
+ st = speedtest.Speedtest(timeout=15, secure=True)
21
+ st.get_best_server()
22
+ st.download()
23
+ st.upload(pre_allocate=False)
24
+
25
+ results = st.results.dict()
26
+ download_mbps = st.results.download / 1_000_000
27
+ upload_mbps = st.results.upload / 1_000_000
28
+
29
+ results['download_mbps'] = download_mbps
30
+ results['upload_mbps'] = upload_mbps
31
+ results['download_bps'] = st.results.download / 8
32
+ results['upload_bps'] = st.results.upload / 8
33
+
34
+ logger.info(f"Download: {download_mbps:.2f} Mbps | Upload: {upload_mbps:.2f} Mbps")
35
+
36
+ try:
37
+ return results, st.results.share()
38
+ except Exception:
39
+ return results, None
40
+
41
+ except Exception as e:
42
+ logger.error(f"Speedtest failed: {e}")
43
+ return None, None
config_sample.env CHANGED
@@ -24,7 +24,7 @@ OWNER_USERNAME="" # Example: "@YourUsername"
24
  DATABASE_URL="" # Example: "mongodb+srv://user:pass@host/db"
25
 
26
  # Deployment configuration
27
- FQDN="" # Your domain name (leave empty to use IP)
28
  HAS_SSL="False" # Set to "True" if using HTTPS
29
  PORT=8080 # Web server port
30
  NO_PORT="True" # Hide port in URLs ("True" or "False")
 
24
  DATABASE_URL="" # Example: "mongodb+srv://user:pass@host/db"
25
 
26
  # Deployment configuration
27
+ FQDN="" # Your domain name
28
  HAS_SSL="False" # Set to "True" if using HTTPS
29
  PORT=8080 # Web server port
30
  NO_PORT="True" # Hide port in URLs ("True" or "False")
requirements.txt CHANGED
@@ -5,5 +5,6 @@ kurigram==2.2.6
5
  motor
6
  psutil
7
  python-dotenv
 
8
  tgcrypto
9
  uvloop
 
5
  motor
6
  psutil
7
  python-dotenv
8
+ speedtest-cli
9
  tgcrypto
10
  uvloop