JerryCoder commited on
Commit
450abb5
·
verified ·
1 Parent(s): aa04cf4

Delete bot.py

Browse files
Files changed (1) hide show
  1. bot.py +0 -216
bot.py DELETED
@@ -1,216 +0,0 @@
1
- import os, io, sys, zipfile, base64, random, shutil, subprocess, tempfile
2
- from pathlib import Path
3
-
4
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, Bot
5
- from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
6
- from telegram.request import Request # <-- updated import
7
-
8
- from motor.motor_asyncio import AsyncIOMotorClient
9
- from config import BOT_TOKEN, ADMIN_ID, MONGO_URI, DB_NAME
10
-
11
- # --- MongoDB Setup ---
12
- mongo_client = AsyncIOMotorClient(MONGO_URI)
13
- db = mongo_client[DB_NAME]
14
- users_col = db["users"]
15
- bans_col = db["banned_users"]
16
- stats_col = db["stats"]
17
-
18
- async def init_stats():
19
- if not await stats_col.find_one({"_id":"encryption_count"}):
20
- await stats_col.insert_one({"_id":"encryption_count","count":0})
21
-
22
- # --- Helpers ---
23
- def make_zip_bytes(filename: str, content: bytes) -> bytes:
24
- bio = io.BytesIO()
25
- with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
26
- zf.writestr(filename, content)
27
- return bio.getvalue()
28
-
29
- def rand_bytes(n): return os.urandom(n)
30
- def bytes_to_c_array_literal(b: bytes) -> str:
31
- return ",".join(str(x) for x in b)
32
-
33
- def xor_string(s: str, key: int = None) -> str:
34
- if key is None: key = random.randint(1,255)
35
- arr = [ord(c)^key for c in s]
36
- return f"(lambda s:''.join(chr(B^{key}) for B in s))([{','.join(str(x) for x in arr)}])"
37
-
38
- def generate_junk_data(min_kb=50,max_kb=70):
39
- junk_size = random.randint(min_kb*1024,max_kb*1024)
40
- chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_()-./,;:!?"
41
- return ''.join(random.choice(chars) for _ in range(junk_size))
42
-
43
- # --- C Template ---
44
- C_TEMPLATE = """/*KEY_BYTES*/""" # Replace with actual C template
45
- SETUP_PY = """# Your setup.py content"""
46
-
47
- def compile_c_extension(build_dir: Path):
48
- (build_dir/"setup.py").write_text(SETUP_PY)
49
- proc = subprocess.run([sys.executable,"setup.py","build_ext","--inplace"],
50
- cwd=str(build_dir), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=30)
51
- candidates = list(build_dir.glob("aes_helper*.so")) + list(build_dir.glob("build/lib.*/*.so"))
52
- if not candidates:
53
- raise RuntimeError("Compile fail:\n"+proc.stdout.decode())
54
- return candidates[0]
55
-
56
- def build_wrapper(j_b64, so_b64, so_filename):
57
- lines = [
58
- "wulcan = '.WulcanPy'",
59
- "import os as O, sys as S, base64 as B, tempfile as T",
60
- f"WL='{j_b64}'",
61
- f"M={repr(so_b64)}",
62
- f"D=O.path.join(T.gettempdir(),{xor_string('ninja_tmp')});O.makedirs(D,exist_ok=True)",
63
- f"P=O.path.join(D,{xor_string(so_filename)})",
64
- "open(P,'wb').write(B.b64decode(M))",
65
- "import importlib.machinery as L, importlib.util as U",
66
- "loader=L.ExtensionFileLoader('aes_helper',P);spec=U.spec_from_loader(loader.name,loader);mod=U.module_from_spec(spec);loader.exec_module(mod)",
67
- "import sys, io, zipfile, runpy",
68
- "try:",
69
- "\tc=B.b64decode(WL);z=mod.decrypt(c)",
70
- "\tt=T.mkdtemp(prefix='nin_');zipfile.ZipFile(io.BytesIO(z)).extractall(t)",
71
- "\tS.path.insert(0,t)",
72
- "\te=[f for f in O.listdir(t) if f.endswith('.py')][0]",
73
- "\tep=O.path.join(t,e)",
74
- "\tS.argv=[ep]+S.argv[1:]",
75
- "\trunpy.run_path(ep,run_name='__main__')",
76
- "except Exception as E: print('ninja_error',E)",
77
- "finally: O.remove(P) if O.path.exists(P) else None",
78
- f"JUNK={repr(generate_junk_data())}"
79
- ]
80
- return "\n".join(lines)
81
-
82
- # --- Process File ---
83
- async def process_file(input_file: Path, update: Update, context: ContextTypes.DEFAULT_TYPE):
84
- user = update.effective_user
85
- tmpdir = Path(tempfile.mkdtemp())
86
- tmp_file = tmpdir/input_file.name
87
- tmp_file.write_bytes(input_file.read_bytes())
88
- py_bytes = tmp_file.read_bytes()
89
- zip_b = make_zip_bytes(input_file.name, py_bytes)
90
- key, iv = rand_bytes(32), rand_bytes(16)
91
- c_src = C_TEMPLATE.replace("/*KEY_BYTES*/", bytes_to_c_array_literal(key)).replace("/*IV_BYTES*/", bytes_to_c_array_literal(iv))
92
- (tmpdir/"aes_helper.c").write_text(c_src)
93
- so_path = compile_c_extension(tmpdir)
94
- import importlib.util
95
- spec = importlib.util.spec_from_file_location("aes_helper",so_path)
96
- mod = importlib.util.module_from_spec(spec)
97
- spec.loader.exec_module(mod)
98
- cipher = mod.encrypt(zip_b)
99
- cipher_b64 = base64.b64encode(cipher).decode()
100
- so_b64 = base64.b64encode(so_path.read_bytes()).decode()
101
- wrapper = build_wrapper(cipher_b64, so_b64, so_path.name)
102
- out_name = input_file.stem+"_enc.py"
103
- out_path = tmpdir/out_name
104
- out_path.write_text(wrapper)
105
- with open(out_path,'rb') as f:
106
- await update.message.reply_document(document=f,filename=out_name,caption=f"✅ File encoded: {out_name}")
107
- await stats_col.update_one({"_id":"encryption_count"},{"$inc":{"count":1}})
108
- await context.bot.send_message(chat_id=ADMIN_ID, text=f'{{"status":"bot_started","user":"{user.full_name}","file":"{input_file.name}"}}')
109
- shutil.rmtree(tmpdir, ignore_errors=True)
110
-
111
- # --- Handlers ---
112
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
113
- user = update.effective_user
114
- if not await users_col.find_one({"user_id":user.id}):
115
- await users_col.insert_one({"user_id":user.id,"name":user.full_name,"username":user.username or "None","language":user.language_code or "Unknown"})
116
- await context.bot.send_message(chat_id=ADMIN_ID, text=f'{{"status":"bot_started","user":"{user.full_name}"}}')
117
- keyboard=[[InlineKeyboardButton("▶ Join Channel",url="https://t.me/kuttuxd17")]]
118
- await update.message.reply_text("Welcome to Secure File Encryptor Bot!",reply_markup=InlineKeyboardMarkup(keyboard))
119
-
120
- async def encode(update: Update, context: ContextTypes.DEFAULT_TYPE):
121
- user = update.effective_user
122
- if await bans_col.find_one({"user_id":user.id}):
123
- await update.message.reply_text("You are banned.")
124
- return
125
- await update.message.reply_text("Please upload a .py file.")
126
-
127
- async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
128
- user = update.effective_user
129
- if await bans_col.find_one({"user_id":user.id}):
130
- await update.message.reply_text("You are banned.")
131
- return
132
- document = update.message.document
133
- if not document.file_name.endswith(".py"):
134
- await update.message.reply_text("Upload .py file only.")
135
- return
136
- file = await document.get_file()
137
- tmpdir = Path(tempfile.mkdtemp())
138
- input_path = tmpdir/document.file_name
139
- await file.download_to_drive(str(input_path))
140
- await process_file(input_path, update, context)
141
-
142
- # --- Admin Commands ---
143
- async def total_users(update: Update, context: ContextTypes.DEFAULT_TYPE):
144
- if update.effective_user.id != ADMIN_ID:
145
- await update.message.reply_text("Unauthorized")
146
- return
147
- count = await users_col.count_documents({})
148
- await update.message.reply_text(f"Total users: {count}")
149
-
150
- async def total_enc(update: Update, context: ContextTypes.DEFAULT_TYPE):
151
- if update.effective_user.id != ADMIN_ID:
152
- await update.message.reply_text("Unauthorized")
153
- return
154
- stats = await stats_col.find_one({"_id":"encryption_count"})
155
- await update.message.reply_text(f"Total encryptions: {stats['count'] if stats else 0}")
156
-
157
- async def broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
158
- if update.effective_user.id != ADMIN_ID:
159
- await update.message.reply_text("Unauthorized")
160
- return
161
- msg=" ".join(context.args)
162
- users=users_col.find({})
163
- count=0
164
- async for u in users:
165
- try: await context.bot.send_message(chat_id=u['user_id'], text=msg); count+=1
166
- except: pass
167
- await update.message.reply_text(f"Broadcast sent to {count} users")
168
-
169
- async def ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
170
- if update.effective_user.id != ADMIN_ID: return
171
- try: user_id=int(context.args[0]); await bans_col.update_one({"user_id":user_id},{"$set":{"user_id":user_id}},upsert=True); await update.message.reply_text(f"Banned {user_id}")
172
- except: await update.message.reply_text("Provide user ID")
173
-
174
- async def unban(update: Update, context: ContextTypes.DEFAULT_TYPE):
175
- if update.effective_user.id != ADMIN_ID: return
176
- try: user_id=int(context.args[0]); await bans_col.delete_one({"user_id":user_id}); await update.message.reply_text(f"Unbanned {user_id}")
177
- except: await update.message.reply_text("Provide user ID")
178
-
179
- # --- Main ---
180
- async def main():
181
- await init_stats()
182
-
183
- # --- Telegram Bot with proxy ---
184
- # Use your Vercel JS proxy
185
- PROXY_URL = "https://jerryproxy.vercel.app/api/proxy?url="
186
- request = Request(proxy_url=PROXY_URL)
187
-
188
- app = Application.builder().token(BOT_TOKEN).request(request).build()
189
-
190
- # --- Handlers ---
191
- app.add_handler(CommandHandler("start", start))
192
- app.add_handler(CommandHandler("encode", encode))
193
- app.add_handler(MessageHandler(filters.Document.ALL, handle_document))
194
- app.add_handler(CommandHandler("totalusers", total_users))
195
- app.add_handler(CommandHandler("totalenc", total_enc))
196
- app.add_handler(CommandHandler("broadcast", broadcast))
197
- app.add_handler(CommandHandler("ban", ban))
198
- app.add_handler(CommandHandler("unban", unban))
199
-
200
- # --- Send bot_started safely ---
201
- import asyncio
202
- asyncio.create_task(bot.send_message(chat_id=ADMIN_ID, text='{"status":"bot_started"}'))
203
-
204
- # --- Use webhook for Vercel ---
205
- WEBHOOK_URL = f"https://jerryproxy.vercel.app/api/webhook/{BOT_TOKEN}"
206
- await app.run_webhook(
207
- listen="0.0.0.0",
208
- port=int(os.environ.get("PORT", 3000)),
209
- url_path=BOT_TOKEN,
210
- webhook_url=WEBHOOK_URL
211
- )
212
-
213
- # --- Run Bot ---
214
- if __name__ == "__main__":
215
- import asyncio
216
- asyncio.run(main())