JerryCoder commited on
Commit
cc4e929
·
verified ·
1 Parent(s): 07a5efb

Delete bot.py

Browse files
Files changed (1) hide show
  1. bot.py +0 -185
bot.py DELETED
@@ -1,185 +0,0 @@
1
- import os, io, sys, zipfile, base64, random, shutil, subprocess, tempfile
2
- from pathlib import Path
3
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
4
- from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
5
- from telegram.request import Request # proper import for telegram v20+
6
- from motor.motor_asyncio import AsyncIOMotorClient
7
- from config import BOT_TOKEN, ADMIN_ID, MONGO_URI, DB_NAME
8
-
9
- # --- MongoDB Setup ---
10
- mongo_client = AsyncIOMotorClient(MONGO_URI)
11
- db = mongo_client[DB_NAME]
12
- users_col = db["users"]
13
- bans_col = db["banned_users"]
14
- stats_col = db["stats"]
15
-
16
- async def init_stats():
17
- if not await stats_col.find_one({"_id":"encryption_count"}):
18
- await stats_col.insert_one({"_id":"encryption_count","count":0})
19
-
20
- # --- Helpers ---
21
- def make_zip_bytes(filename: str, content: bytes) -> bytes:
22
- bio = io.BytesIO()
23
- with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
24
- zf.writestr(filename, content)
25
- return bio.getvalue()
26
-
27
- def rand_bytes(n): return os.urandom(n)
28
-
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 = """/*KEY_BYTES*/""" # Replace with actual C template
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)).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'{{"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
- # --- Admin Commands ---
147
- async def total_users(update: Update, context: ContextTypes.DEFAULT_TYPE):
148
- if update.effective_user.id != ADMIN_ID:
149
- await update.message.reply_text("Unauthorized")
150
- return
151
- count = await users_col.count_documents({})
152
- await update.message.reply_text(f"Total users: {count}")
153
-
154
- async def total_enc(update: Update, context: ContextTypes.DEFAULT_TYPE):
155
- if update.effective_user.id != ADMIN_ID:
156
- await update.message.reply_text("Unauthorized")
157
- return
158
- stats = await stats_col.find_one({"_id":"encryption_count"})
159
- await update.message.reply_text(f"Total encryptions: {stats['count'] if stats else 0}")
160
-
161
- # --- Main ---
162
- async def main():
163
- await init_stats()
164
- app = Application.builder().token(BOT_TOKEN).build()
165
-
166
- # Handlers
167
- app.add_handler(CommandHandler("start", start))
168
- app.add_handler(CommandHandler("encode", encode))
169
- app.add_handler(MessageHandler(filters.Document.ALL, handle_document))
170
- app.add_handler(CommandHandler("totalusers", total_users))
171
- app.add_handler(CommandHandler("totalenc", total_enc))
172
-
173
- # Hugging Face Space webhook URL
174
- WEBHOOK_URL = f"https://{os.environ['SPACE_DOMAIN']}/api/webhook/{BOT_TOKEN}"
175
- await app.run_webhook(
176
- listen="0.0.0.0",
177
- port=int(os.environ.get("PORT", 7860)),
178
- url_path=BOT_TOKEN,
179
- webhook_url=WEBHOOK_URL
180
- )
181
-
182
- # --- Run ---
183
- if __name__ == "__main__":
184
- import asyncio
185
- asyncio.run(main())