JerryCoder commited on
Commit
cb7ab5d
·
verified ·
1 Parent(s): 1211132

Delete bot.py

Browse files
Files changed (1) hide show
  1. bot.py +0 -201
bot.py DELETED
@@ -1,201 +0,0 @@
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
- import asyncio
6
-
7
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
8
- from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
9
- from motor.motor_asyncio import AsyncIOMotorClient
10
- from config import BOT_TOKEN, ADMIN_ID, MONGO_URI, DB_NAME
11
-
12
- # --- MongoDB Setup ---
13
- mongo_client = AsyncIOMotorClient(MONGO_URI)
14
- db = mongo_client[DB_NAME]
15
- users_col = db["users"]
16
- bans_col = db["banned_users"]
17
- stats_col = db["stats"]
18
-
19
- async def init_stats():
20
- if not await stats_col.find_one({"_id": "encryption_count"}):
21
- await stats_col.insert_one({"_id": "encryption_count", "count": 0})
22
-
23
- # --- Helpers ---
24
- def make_zip_bytes(filename: str, content: bytes) -> bytes:
25
- bio = io.BytesIO()
26
- with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
27
- zf.writestr(filename, content)
28
- return bio.getvalue()
29
-
30
- def rand_bytes(n): return os.urandom(n)
31
- def bytes_to_c_array_literal(b: bytes) -> str: 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*/"""
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.encrypt(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))
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({
116
- "user_id": user.id,
117
- "name": user.full_name,
118
- "username": user.username or "None",
119
- "language": user.language_code or "Unknown"
120
- })
121
- await context.bot.send_message(chat_id=ADMIN_ID, text=f'{{"status":"bot_started","user":"{user.full_name}"}}')
122
- keyboard = [[InlineKeyboardButton("▶ Join Channel", url="https://t.me/kuttuxd17")]]
123
- await update.message.reply_text("Welcome to Secure File Encryptor Bot!", reply_markup=InlineKeyboardMarkup(keyboard))
124
-
125
- async def encode(update: Update, context: ContextTypes.DEFAULT_TYPE):
126
- user = update.effective_user
127
- if await bans_col.find_one({"user_id": user.id}):
128
- await update.message.reply_text("You are banned.")
129
- return
130
- await update.message.reply_text("Please upload a .py file.")
131
-
132
- async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
133
- user = update.effective_user
134
- if await bans_col.find_one({"user_id": user.id}):
135
- await update.message.reply_text("You are banned.")
136
- return
137
- document = update.message.document
138
- if not document.file_name.endswith(".py"):
139
- await update.message.reply_text("Upload .py file only.")
140
- return
141
- file = await document.get_file()
142
- tmpdir = Path(tempfile.mkdtemp())
143
- input_path = tmpdir/document.file_name
144
- await file.download_to_drive(str(input_path))
145
- await process_file(input_path, update, context)
146
-
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
174
- WEBHOOK_URL = f"https://huggingface.co/spaces/JerryCoder/kuttuxd/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
- # --- FastAPI App for JSON Status ---
183
- hf_app = FastAPI()
184
-
185
- @hf_app.get("/")
186
- async def root():
187
- return JSONResponse(content={"status": "success", "bot": "running"})
188
-
189
- if __name__ == "__main__":
190
- # Check if loop is already running (Hugging Face Spaces does this)
191
- try:
192
- loop = asyncio.get_running_loop()
193
- except RuntimeError:
194
- loop = None
195
-
196
- if loop and loop.is_running():
197
- # Already running loop: create task directly
198
- asyncio.create_task(main())
199
- else:
200
- # Not running: run normally
201
- asyncio.run(main())