JerryCoder commited on
Commit
f36a3d8
·
verified ·
1 Parent(s): d789619

Create bot.py

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