JerryCoder commited on
Commit
ec20bdf
·
verified ·
1 Parent(s): bc1b12b

Create bot.py

Browse files
Files changed (1) hide show
  1. bot.py +190 -0
bot.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, io, sys, zipfile, base64, random, shutil, subprocess, tempfile
2
+ from pathlib import Path
3
+ from fastapi import FastAPI
4
+ from starlette.responses import JSONResponse
5
+
6
+ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
7
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
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: 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 = """/*KEY_BYTES*/"""
44
+ SETUP_PY = """# Your setup.py content"""
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.encrypt(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))
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'{{"status":"bot_started","user":"{user.full_name}","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({
115
+ "user_id": user.id,
116
+ "name": user.full_name,
117
+ "username": user.username or "None",
118
+ "language": user.language_code or "Unknown"
119
+ })
120
+ await context.bot.send_message(chat_id=ADMIN_ID, text=f'{{"status":"bot_started","user":"{user.full_name}"}}')
121
+ keyboard = [[InlineKeyboardButton("▶ Join Channel", url="https://t.me/kuttuxd17")]]
122
+ await update.message.reply_text("Welcome to Secure File Encryptor Bot!", reply_markup=InlineKeyboardMarkup(keyboard))
123
+
124
+ async def encode(update: Update, context: ContextTypes.DEFAULT_TYPE):
125
+ user = update.effective_user
126
+ if await bans_col.find_one({"user_id": user.id}):
127
+ await update.message.reply_text("You are banned.")
128
+ return
129
+ await update.message.reply_text("Please upload a .py file.")
130
+
131
+ async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
132
+ user = update.effective_user
133
+ if await bans_col.find_one({"user_id": user.id}):
134
+ await update.message.reply_text("You are banned.")
135
+ return
136
+ document = update.message.document
137
+ if not document.file_name.endswith(".py"):
138
+ await update.message.reply_text("Upload .py file only.")
139
+ return
140
+ file = await document.get_file()
141
+ tmpdir = Path(tempfile.mkdtemp())
142
+ input_path = tmpdir/document.file_name
143
+ await file.download_to_drive(str(input_path))
144
+ await process_file(input_path, update, context)
145
+
146
+ async def total_users(update: Update, context: ContextTypes.DEFAULT_TYPE):
147
+ if update.effective_user.id != ADMIN_ID:
148
+ await update.message.reply_text("Unauthorized")
149
+ return
150
+ count = await users_col.count_documents({})
151
+ await update.message.reply_text(f"Total users: {count}")
152
+
153
+ async def total_enc(update: Update, context: ContextTypes.DEFAULT_TYPE):
154
+ if update.effective_user.id != ADMIN_ID:
155
+ await update.message.reply_text("Unauthorized")
156
+ return
157
+ stats = await stats_col.find_one({"_id":"encryption_count"})
158
+ await update.message.reply_text(f"Total encryptions: {stats['count'] if stats else 0}")
159
+
160
+ # --- Main ---
161
+ async def main():
162
+ await init_stats()
163
+ app = Application.builder().token(BOT_TOKEN).build()
164
+
165
+ # Handlers
166
+ app.add_handler(CommandHandler("start", start))
167
+ app.add_handler(CommandHandler("encode", encode))
168
+ app.add_handler(MessageHandler(filters.Document.ALL, handle_document))
169
+ app.add_handler(CommandHandler("totalusers", total_users))
170
+ app.add_handler(CommandHandler("totalenc", total_enc))
171
+
172
+ # Hugging Face Space webhook
173
+ WEBHOOK_URL = f"https://{os.environ['SPACE_DOMAIN']}/api/webhook/{BOT_TOKEN}"
174
+ await app.run_webhook(
175
+ listen="0.0.0.0",
176
+ port=int(os.environ.get("PORT", 7860)),
177
+ url_path=BOT_TOKEN,
178
+ webhook_url=WEBHOOK_URL
179
+ )
180
+
181
+ # --- FastAPI App for JSON Status ---
182
+ hf_app = FastAPI()
183
+
184
+ @hf_app.get("/")
185
+ async def root():
186
+ return JSONResponse(content={"status": "success", "bot": "running"})
187
+
188
+ if __name__ == "__main__":
189
+ import asyncio
190
+ asyncio.run(main())