JerryCoder commited on
Commit
f8530df
·
verified ·
1 Parent(s): 852d7d2

Create bot.py

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