Spaces:
Runtime error

dpadhan commited on
Commit
a7b6c44
·
verified ·
1 Parent(s): c416349

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +43 -149
bot.py CHANGED
@@ -1,159 +1,53 @@
1
- import os
2
- import asyncio
3
- import sqlite3
4
- from pyrogram import Client, filters, errors
5
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
6
 
7
- # --- CONFIGURATION ---
8
- API_ID = int(os.environ.get("API_ID", 0))
9
- API_HASH = os.environ.get("API_HASH", "")
10
- BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
11
 
12
- # --- DATABASE SETUP ---
13
- DB_PATH = "bot_data.db"
 
 
 
 
14
 
15
- def init_db():
16
- conn = sqlite3.connect(DB_PATH)
17
- cursor = conn.cursor()
18
- cursor.execute('''CREATE TABLE IF NOT EXISTS config
19
- (id INTEGER PRIMARY KEY, source_ids TEXT, dest_id INTEGER, order_pref TEXT)''')
20
- conn.commit()
21
- conn.close()
22
-
23
- def get_config():
24
- conn = sqlite3.connect(DB_PATH)
25
- cursor = conn.cursor()
26
- cursor.execute("SELECT source_ids, dest_id, order_pref FROM config WHERE id = 1")
27
- res = cursor.fetchone()
28
- conn.close()
29
- return res
30
-
31
- init_db()
32
-
33
- # --- UI UTILS ---
34
- def generate_progress_bar(current, total):
35
- percentage = (current / total) * 100 if total > 0 else 0
36
- blocks = int(current / total * 15) if total > 0 else 0
37
- bar = "🔘" * blocks + "⚪" * (15 - blocks)
38
- return f"{bar} {percentage:.1f}%"
39
-
40
- # --- BOT CLIENT ---
41
- app = Client("forwarder_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
42
-
43
- @app.on_message(filters.command("start"))
44
- async def start(client, message):
45
- boot_text = (
46
- "<code>[ ⚡ ] CLONE_OS TERMINAL v2.0</code>\n"
47
- "<code>[ OK ] MOUNTING DATABASE...</code>\n"
48
- "<code>[ OK ] ESTABLISHING CONNECTION...</code>\n\n"
49
- "<b>SYSTEM ONLINE. SELECT A MODULE:</b>"
50
- )
51
- buttons = InlineKeyboardMarkup([
52
- [InlineKeyboardButton("⚙️ CONFIGURE", callback_data="setup_info"),
53
- InlineKeyboardButton("▶️ EXECUTE CLONE", callback_data="start_clone")],
54
- [InlineKeyboardButton("🔍 SYS_STATUS", callback_data="check_status"),
55
- InlineKeyboardButton("🧹 PURGE_DB", callback_data="clear_db")]
56
- ])
57
- await message.reply_text(boot_text, reply_markup=buttons)
58
-
59
- @app.on_callback_query()
60
- async def handle_callbacks(client, callback_query):
61
- data = callback_query.data
62
-
63
- if data == "setup_info":
64
- await callback_query.message.edit_text(
65
- "<code>[ REQUEST ]: INPUT_CONFIG</code>\n\n"
66
- "Format: <code>SOURCES | DEST | ORDER</code>\n"
67
- "Example: <code>-1001, -1002 | -1003 | old</code>\n\n"
68
- "<i>Waiting for user input...</i>",
69
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 CANCEL", callback_data="back")]])
70
- )
71
-
72
- elif data == "check_status":
73
- conf = get_config()
74
- if not conf:
75
- await callback_query.answer("❌ NO CONFIGURATION FOUND", show_alert=True)
76
- else:
77
- status = (
78
- "<code>[ DASHBOARD ]</code>\n"
79
- f"📡 <b>SOURCES:</b> <code>{conf[0]}</code>\n"
80
- f"🎯 <b>DESTINATION:</b> <code>{conf[1]}</code>\n"
81
- f"📑 <b>ORDERING:</b> <code>{conf[2].upper()}</code>\n"
82
- )
83
- await callback_query.message.edit_text(status, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 BACK", callback_data="back")]]))
84
-
85
- elif data == "start_clone":
86
- await start_forwarding(client, callback_query.message)
87
-
88
- elif data == "clear_db":
89
- conn = sqlite3.connect(DB_PATH)
90
- conn.cursor().execute("DELETE FROM config")
91
- conn.commit()
92
- conn.close()
93
- await callback_query.answer("🗑 DATABASE PURGED", show_alert=True)
94
- await start(client, callback_query.message)
95
-
96
- elif data == "back":
97
- await start(client, callback_query.message)
98
-
99
- @app.on_message(filters.regex(r"^-?\d+.*\|.*-?\d+.*\|.*"))
100
- async def handle_setup_input(client, message):
101
  try:
102
- parts = message.text.split("|")
103
- sources, dest, order = parts[0].strip(), int(parts[1].strip()), parts[2].strip().lower()
 
104
 
105
- conn = sqlite3.connect(DB_PATH)
106
- conn.cursor().execute("INSERT OR REPLACE INTO config (id, source_ids, dest_id, order_pref) VALUES (1, ?, ?, ?)",
107
- (sources, dest, order))
108
- conn.commit()
109
- conn.close()
110
- await message.reply_text("<code>[ SUCCESS ]: DATA_SYNC_COMPLETE</code>\nClick /start to run.")
111
- except Exception as e:
112
- await message.reply_text(f"<code>[ ERROR ]: {e}</code>")
 
 
 
 
 
 
 
 
 
113
 
114
- async def start_forwarding(client, message):
115
- conf = get_config()
116
- if not conf:
117
- return await message.edit_text("<code>[ FAILURE ]: RUN_SETUP_FIRST</code>")
118
-
119
- source_ids = [int(i.strip()) for i in conf[0].split(",")]
120
- dest_id = conf[1]
121
- reverse = True if conf[2] == "old" else False
122
 
123
- await message.edit_text("<code>[ 🚀 ] INITIATING CLONE SEQUENCE...</code>")
124
- await asyncio.sleep(1)
 
125
 
126
- for s_id in source_ids:
127
- try:
128
- total_msgs = await client.get_chat_history_count(s_id)
129
- curr = 0
130
-
131
- async for msg in client.get_chat_history(s_id, reverse=reverse):
132
- if msg.service: continue
133
-
134
- try:
135
- await msg.copy(dest_id)
136
- curr += 1
137
-
138
- if curr % 5 == 0 or curr == total_msgs:
139
- bar = generate_progress_bar(curr, total_msgs)
140
- ui = (
141
- f"<code>[ ACTIVE_PROCESS ]</code>\n"
142
- f"📡 <b>SOURCE:</b> <code>{s_id}</code>\n"
143
- f"📦 <b>FILES:</b> <code>{curr} / {total_msgs}</code>\n\n"
144
- f"<code>{bar}</code>"
145
- )
146
- await message.edit_text(ui)
147
-
148
- await asyncio.sleep(1.2)
149
- except errors.FloodWait as e:
150
- await asyncio.sleep(e.value)
151
- except Exception:
152
- continue
153
- except Exception as e:
154
- await message.reply_text(f"<code>[ ERROR ]: CHAT_{s_id}_UNREACHABLE\n{e}</code>")
155
 
156
- await message.edit_text("<code>[ COMPLETED ]: ALL_TASKS_DONE</code>\n/start to return to menu.")
 
157
 
158
- print("Terminal Bot Started...")
159
- app.run()
 
1
+ import time
2
+ import speedtest
3
+ from telegram import Update
4
+ from telegram.ext import Application, CommandHandler, ContextTypes
 
5
 
6
+ # Configuration
7
+ TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
 
 
8
 
9
+ async def ping(update: Update, context: ContextTypes.DEFAULT_TYPE):
10
+ # 1. Calculate Bot Latency
11
+ start_time = time.time()
12
+ message = await update.message.reply_text("⚡ Checking system speeds...")
13
+ end_time = time.time()
14
+ bot_latency = (end_time - start_time) * 1000
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  try:
17
+ # 2. Run Speedtest
18
+ st = speedtest.Speedtest()
19
+ st.get_best_server()
20
 
21
+ # Perform tests
22
+ download_speed = st.download() / 1_000_000 # Convert to Mbps
23
+ upload_speed = st.upload() / 1_000_000 # Convert to Mbps
24
+ server_info = st.results.server
25
+ network_ping = st.results.ping
26
+
27
+ # 3. Format the Response
28
+ response = (
29
+ "🏓 **Ping Results**\n\n"
30
+ f"⏱ **Bot Latency:** {bot_latency:.2f}ms\n"
31
+ f"⬇️ **Download:** {download_speed:.2f} Mbps\n"
32
+ f"⬆️ **Upload:** {upload_speed:.2f} Mbps\n"
33
+ f"📡 **Ping:** {network_ping:.2f} ms\n"
34
+ f"🌐 **Server:** {server_info['name']}"
35
+ )
36
+
37
+ await message.edit_text(response, parse_mode='Markdown')
38
 
39
+ except Exception as e:
40
+ await message.edit_text(f"❌ Error fetching speeds: {e}")
 
 
 
 
 
 
41
 
42
+ def main():
43
+ # Build the application
44
+ application = Application.builder().token(TOKEN).build()
45
 
46
+ # Add the /ping command handler
47
+ application.add_handler(CommandHandler("ping", ping))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ print("Bot is running...")
50
+ application.run_polling()
51
 
52
+ if __name__ == '__main__':
53
+ main()