Cxops commited on
Commit
c5bd3a7
·
verified ·
1 Parent(s): ed40b04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -304
app.py CHANGED
@@ -1,321 +1,224 @@
1
- import os, json, math, time, base64, shutil, asyncio, logging, tempfile
2
- from typing import Dict, Optional
3
- from pathlib import Path
4
-
5
- import aiohttp # Only for downloads from Hugging Face – not for keep-alive
6
- from cryptography.fernet import Fernet
7
- from cryptography.hazmat.primitives import hashes
8
- from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
9
- from cryptography.hazmat.backends import default_backend
10
- from pyrogram import Client, filters
11
- from pyrogram.types import (
12
- Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  )
14
- from pyrogram.errors import MessageNotModified, FloodWait
15
- from huggingface_hub import HfApi, upload_file, hf_hub_url
16
- from huggingface_hub.utils import EntryNotFoundError
17
-
18
- # ---------- LOGGING ----------
19
- logging.basicConfig(level=logging.WARNING, format="%(asctime)s [%(levelname)s] %(message)s")
20
- logger = logging.getLogger("bot")
21
- logger.setLevel(logging.INFO)
22
-
23
- # ---------- CONFIG ----------
24
- for var in ["BOT_TOKEN", "API_ID", "API_HASH", "HF_TOKEN", "SECRET_KEY"]:
25
- if var not in os.environ:
26
- logger.error(f"Missing {var}")
27
- exit(1)
28
-
29
- BOT_TOKEN = os.environ["BOT_TOKEN"]
30
- API_ID = int(os.environ["API_ID"])
31
- API_HASH = os.environ["API_HASH"]
32
- HF_TOKEN = os.environ["HF_TOKEN"]
33
- SECRET_KEY = os.environ["SECRET_KEY"]
34
-
35
- HF_REPO_ID = "Cxops/Bzxv"
36
- HF_REPO_TYPE = "dataset"
37
- HF_BRANCH = "main"
38
- MIN_FREE_DISK = 45 * 1024**3
39
- SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024
40
- PROGRESS_INTERVAL = 3
41
-
42
- # ---------- ENCRYPTION ----------
43
- SALT = b"huggingbot_salt_2025"
44
- kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=SALT,
45
- iterations=100_000, backend=default_backend())
46
- key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
47
- fernet = Fernet(key)
48
-
49
- def encrypt(data: str) -> str:
50
- return base64.urlsafe_b64encode(fernet.encrypt(data.encode())).decode().rstrip("=")
51
-
52
- def decrypt(token: str) -> str:
53
- pad = 4 - len(token) % 4
54
- if pad != 4:
55
- token += "=" * pad
56
- return fernet.decrypt(base64.urlsafe_b64decode(token)).decode()
57
-
58
- def get_user_folder(user_id: int) -> str:
59
- return encrypt(str(user_id))
60
-
61
- # ---------- HUGGING FACE ----------
62
- hf_api = HfApi(token=HF_TOKEN)
63
-
64
- def hf_read_json(path: str) -> Optional[dict]:
65
- try:
66
- return json.loads(hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH))
67
- except EntryNotFoundError:
68
- return None
69
- except Exception as e:
70
- logger.error(f"hf_read_json error: {e}")
71
- return None
72
-
73
- def hf_write_json(path: str, data: dict):
74
- hf_api.upload_file(
75
- path_or_fileobj=json.dumps(data, indent=2).encode(),
76
- path_in_repo=path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
77
- commit_message=f"update {path}"
78
  )
79
 
80
- def hf_delete_file(path: str):
81
- try:
82
- hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
83
- commit_message=f"delete {path}")
84
- except Exception as e:
85
- logger.error(f"hf_delete_file error: {e}")
86
-
87
- def hf_file_size(path: str) -> Optional[int]:
88
- try:
89
- return hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE).size
90
- except EntryNotFoundError:
91
- return None
92
- except Exception as e:
93
- logger.error(f"hf_file_size error: {e}")
94
- return None
95
-
96
- def free_disk_gb() -> float:
97
- return shutil.disk_usage("/").free / (1024**3)
98
-
99
- def enough_disk(needed: int = 0) -> bool:
100
- return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
101
-
102
- # ---------- BOT CLIENT ----------
103
- # Force fresh session
104
- for f in Path(".").glob("bot.session*"):
105
- f.unlink()
106
-
107
- app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
108
-
109
- # ---------- GLOBAL STATE ----------
110
- active_progress: Dict[int, dict] = {}
111
- op_queue = asyncio.Queue()
112
- pending_uploads: Dict[int, dict] = {}
113
-
114
- # ---------- HELPERS ----------
115
- def make_progress_bar(percent: float, width: int = 10) -> str:
116
- filled = int(width * percent / 100)
117
- return "█" * filled + "░" * (width - filled)
118
-
119
- def format_bytes(size: int) -> str:
120
- if size == 0:
121
- return "0 B"
122
- units = ["B", "KB", "MB", "GB", "TB"]
123
- i = int(math.floor(math.log(size, 1024)))
124
- return f"{round(size / (1024**i), 1)} {units[i]}"
125
-
126
- async def progress_updater():
127
  while True:
128
- await asyncio.sleep(PROGRESS_INTERVAL)
129
- for msg_id, info in list(active_progress.items()):
130
- try:
131
- chat_id = info["chat_id"]
132
- filename = info["filename"]
133
- current = info.get("current", 0)
134
- total = info.get("total", 0)
135
- start_time = info.get("start_time", time.time())
136
- op_type = info.get("op_type", "")
137
- elapsed = max(time.time() - start_time, 1)
138
- speed = current / elapsed if current > 0 else 0
139
- if total > 0:
140
- percent = (current / total) * 100
141
- text = (f"**{op_type}** `{filename}`\n"
142
- f"{make_progress_bar(percent)} {percent:.1f}%\n"
143
- f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
144
- f"⚡ {format_bytes(speed)}/s")
145
- else:
146
- text = f"**{op_type}** `{filename}`\n⏳ Processing..."
147
- keyboard = None
148
- if info["state"] in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
149
- keyboard = InlineKeyboardMarkup([[
150
- InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")
151
- ]])
152
- await app.edit_message_text(chat_id, msg_id, text, reply_markup=keyboard)
153
- except MessageNotModified:
154
- pass
155
- except Exception as e:
156
- logger.error(f"progress_updater error: {e}")
157
-
158
- # ---------- UPLOAD / DOWNLOAD (complete, same as before) ----------
159
- async def handle_upload(op): ... # (full function as provided in previous message)
160
- async def handle_download(op): ... # (full function)
161
- async def download_from_url(...): ... # (full function)
162
- async def download_range(...): ... # (full function)
163
- # ** IMPORTANT: Paste the complete functions from the last full code. I'm not repeating them to keep this response compact. **
164
-
165
- # ---------- TELEGRAM HANDLERS ----------
166
  @app.on_message(filters.command("start"))
167
- async def start_cmd(_, msg):
168
- logger.info(f"/start from {msg.from_user.id}")
169
- await msg.reply("👋 Welcome! Send any file to upload, /files to list, /help for help.")
170
-
171
- @app.on_message(filters.command("help"))
172
- async def help_cmd(_, msg):
173
- await msg.reply(
174
- "**Commands:**\n/start – Start\n/files – Your files\n/help – This help\n\n"
175
- "Send any file to upload it. Use /files to download back."
176
- )
177
 
178
- @app.on_message(filters.command("files"))
179
- async def list_files(_, msg):
180
- user_id = msg.from_user.id
181
- meta = hf_read_json(f"{get_user_folder(user_id)}/meta.json")
182
- if not meta:
183
- await msg.reply("📭 No files yet.")
184
- return
185
- kb = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")] for enc, name in meta.items()]
186
- kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
187
- await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(kb))
188
-
189
- @app.on_callback_query(filters.regex("^files_refresh$"))
190
- async def refresh_files(_, query):
191
- await query.answer("Refreshing…")
192
- await list_files(_, query.message)
193
- await query.message.delete()
194
-
195
- @app.on_callback_query(filters.regex("^dl_(.+)"))
196
- async def download_file_cb(_, query):
197
- enc = query.data.split("_", 1)[1]
198
- user_id = query.from_user.id
199
- folder = get_user_folder(user_id)
200
- meta = hf_read_json(f"{folder}/meta.json")
201
- if not meta or enc not in meta:
202
- await query.answer("File not found", show_alert=True); return
203
- orig_name = meta[enc]
204
- size = hf_file_size(f"{folder}/{enc}")
205
- await query.answer("Starting download…")
206
- st = await query.message.reply(f"⏳ Preparing download: `{orig_name}`…")
207
- cancel_ev = asyncio.Event()
208
- active_progress[st.id] = {
209
- "chat_id": st.chat.id, "filename": orig_name,
210
- "current": 0, "total": 0, "start_time": time.time(),
211
- "cancel_event": cancel_ev, "op_type": "Download", "state": "starting"
212
- }
213
- await op_queue.put({
214
- "type": "download", "user_id": user_id, "chat_id": st.chat.id,
215
- "folder": folder, "enc_fname": enc, "orig_name": orig_name,
216
- "file_size": size, "status_msg_id": st.id, "cancel_event": cancel_ev
217
- })
218
-
219
- @app.on_callback_query(filters.regex("^cancel_op_(\\d+)$"))
220
- async def cancel_op(_, query):
221
- msg_id = int(query.data.split("_")[2])
222
- info = active_progress.get(msg_id)
223
- if info and "cancel_event" in info:
224
- info["cancel_event"].set()
225
- await query.answer("Cancelling…")
226
- else:
227
- await query.answer("Nothing to cancel", show_alert=True)
228
-
229
- @app.on_message(filters.media)
230
- async def media_handler(_, msg):
231
- logger.info(f"Media from {msg.from_user.id}")
232
- file_id = None; file_name = "file"; file_size = 0
233
- if msg.document:
234
- file_id = msg.document.file_id; file_name = msg.document.file_name or "doc"; file_size = msg.document.file_size
235
- elif msg.video:
236
- file_id = msg.video.file_id; file_name = msg.video.file_name or "video.mp4"; file_size = msg.video.file_size
237
- elif msg.audio:
238
- file_id = msg.audio.file_id; file_name = msg.audio.file_name or "audio.mp3"; file_size = msg.audio.file_size
239
- elif msg.photo:
240
- file_id = msg.photo.file_id; file_name = f"photo_{msg.photo.file_unique_id}.jpg"; file_size = msg.photo.file_size or 0
241
- elif msg.voice:
242
- file_id = msg.voice.file_id; file_name = f"voice_{msg.voice.file_unique_id}.ogg"; file_size = msg.voice.file_size
243
- elif msg.video_note:
244
- file_id = msg.video_note.file_id; file_name = f"vn_{msg.video_note.file_unique_id}.mp4"; file_size = msg.video_note.file_size
245
- elif msg.sticker:
246
- file_id = msg.sticker.file_id; file_name = f"sticker_{msg.sticker.file_unique_id}.webp"; file_size = msg.sticker.file_size
247
- else:
248
  return
249
- if not file_id: return
250
- prompt = await msg.reply(
251
- f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\nDo you want to upload?",
252
- reply_markup=InlineKeyboardMarkup([[
253
- InlineKeyboardButton("✅ Upload", callback_data=f"upload_{msg.id}"),
254
- InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{msg.id}")
255
- ]]),
256
- quote=True,
257
  )
258
- pending_uploads[prompt.id] = {
259
- "file_id": file_id, "file_name": file_name,
260
- "file_size": file_size, "user_id": msg.from_user.id,
 
 
 
 
 
261
  }
262
 
263
- @app.on_callback_query(filters.regex("^upload_(\\d+)$"))
264
- async def confirm_upload(_, query):
265
- info = pending_uploads.pop(query.message.id, None)
266
- if not info:
267
- await query.answer("Expired", show_alert=True); return
268
- await query.answer()
269
- await query.message.delete()
270
- st = await query.message.reply(f"⏳ Uploading `{info['file_name']}`…")
271
- cancel_ev = asyncio.Event()
272
- await op_queue.put({
273
- "type": "upload", "user_id": info["user_id"], "chat_id": query.message.chat.id,
274
- "file_id": info["file_id"], "file_name": info["file_name"],
275
- "status_msg_id": st.id, "cancel_event": cancel_ev,
276
- })
277
-
278
- @app.on_callback_query(filters.regex("^cancel_prompt_(\\d+)$"))
279
- async def cancel_prompt(_, query):
280
- pending_uploads.pop(query.message.id, None)
281
- await query.answer("Cancelled.")
282
- await query.message.delete()
283
-
284
- # ---------- WORKER ----------
285
- async def worker():
286
- while True:
287
- op = await op_queue.get()
288
- try:
289
- if op["type"] == "upload":
290
- await handle_upload(op)
291
- else:
292
- await handle_download(op)
293
- except Exception as e:
294
- logger.exception(f"Worker error: {e}")
295
- finally:
296
- op_queue.task_done()
 
 
 
297
 
298
- # ---------- MAIN (No internal keep-alive) ----------
299
- async def main():
300
- logger.info("Starting bot (no internal keep-alive)...")
301
- # Start worker & progress updater
302
  asyncio.create_task(worker())
303
- asyncio.create_task(progress_updater())
304
 
305
- while True:
306
- try:
307
- await app.start()
308
- logger.info("Bot is online. Use /start.")
309
- break
310
- except FloodWait as e:
311
- w = e.value
312
- logger.warning(f"FloodWait {w}s – waiting...")
313
- await asyncio.sleep(w)
314
- except Exception as e:
315
- logger.exception(f"Start error: {e}")
316
- await asyncio.sleep(30)
317
 
318
- await asyncio.Event().wait()
 
 
 
 
319
 
320
  if __name__ == "__main__":
321
  asyncio.run(main())
 
1
+ import os
2
+ import asyncio
3
+ import hashlib
4
+ import shutil
5
+ import aiohttp
6
+ import logging
7
+
8
+ from fastapi import FastAPI
9
+ import uvicorn
10
+
11
+ from pyrogram import Client, filters, idle
12
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
13
+ from huggingface_hub import HfApi
14
+
15
+ # ================= LOGGING =================
16
+ logging.basicConfig(level=logging.INFO)
17
+ log = logging.getLogger("bot")
18
+
19
+ # ================= CONFIG =================
20
+
21
+ BOT_TOKEN = os.getenv("BOT_TOKEN")
22
+ API_ID = int(os.getenv("API_ID"))
23
+ API_HASH = os.getenv("API_HASH")
24
+ HF_TOKEN = os.getenv("HF_TOKEN")
25
+
26
+ DATASET_REPO = "Cxops/Bzxv"
27
+ SPACE_URL = "https://cxops-push.hf.space"
28
+
29
+ BASE_DIR = "/data/files"
30
+ DB_PATH = "/data/map.db"
31
+
32
+ DISK_LIMIT_GB = 45
33
+
34
+ os.makedirs(BASE_DIR, exist_ok=True)
35
+
36
+ # ================= FASTAPI (PORT 7860) =================
37
+
38
+ web = FastAPI()
39
+
40
+ @web.get("/")
41
+ def home():
42
+ return {"status": "ok", "service": "telegram-bot"}
43
+
44
+ @web.get("/health")
45
+ def health():
46
+ free = shutil.disk_usage("/data").free
47
+ return {"ok": True, "free_bytes": free}
48
+
49
+ # ================= PYROGRAM =================
50
+
51
+ app = Client(
52
+ "hf_bot",
53
+ api_id=API_ID,
54
+ api_hash=API_HASH,
55
+ bot_token=BOT_TOKEN
56
  )
57
+
58
+ hf = HfApi(token=HF_TOKEN)
59
+
60
+ # ================= UTILS =================
61
+
62
+ def hash_id(x: str):
63
+ return hashlib.sha256(x.encode()).hexdigest()[:16]
64
+
65
+ def folder(user_id, username):
66
+ return hash_id(f"{user_id}:{username}")
67
+
68
+ def user_dir(f):
69
+ path = os.path.join(BASE_DIR, f)
70
+ os.makedirs(path, exist_ok=True)
71
+ return path
72
+
73
+ def disk_ok():
74
+ free = shutil.disk_usage("/data").free
75
+ return free > (DISK_LIMIT_GB * 1024**3)
76
+
77
+ # ================= KEEPALIVE =================
78
+
79
+ async def keepalive():
80
+ while True:
81
+ try:
82
+ async with aiohttp.ClientSession() as s:
83
+ await s.get(SPACE_URL)
84
+ except Exception as e:
85
+ log.warning(f"keepalive failed: {e}")
86
+ await asyncio.sleep(300)
87
+
88
+ # ================= HF UPLOAD =================
89
+
90
+ async def upload_hf(local, remote):
91
+ loop = asyncio.get_event_loop()
92
+ await loop.run_in_executor(
93
+ None,
94
+ lambda: hf.upload_file(
95
+ path_or_fileobj=local,
96
+ path_in_repo=remote,
97
+ repo_id=DATASET_REPO,
98
+ repo_type="dataset"
99
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  )
101
 
102
+ # ================= QUEUE =================
103
+
104
+ queue = asyncio.Queue()
105
+
106
+ async def worker():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  while True:
108
+ job = await queue.get()
109
+
110
+ msg = job["msg"]
111
+ file_id = job["file_id"]
112
+ folder_name = job["folder"]
113
+ fake = job["fake"]
114
+
115
+ if not disk_ok():
116
+ await msg.reply("❌ Disk full. Try later.")
117
+ continue
118
+
119
+ status = await msg.reply("⬇ Downloading...")
120
+
121
+ path = await app.download_media(
122
+ file_id,
123
+ file_name=os.path.join(user_dir(folder_name), fake)
124
+ )
125
+
126
+ await status.edit("☁ Uploading to HuggingFace...")
127
+
128
+ await upload_hf(path, f"{folder_name}/{fake}")
129
+
130
+ try:
131
+ os.remove(path)
132
+ except:
133
+ pass
134
+
135
+ await status.edit("✅ Done")
136
+
137
+ # ================= HANDLERS =================
138
+
139
+ pending = {}
140
+
 
 
 
 
 
141
  @app.on_message(filters.command("start"))
142
+ async def start(_, msg):
143
+ await msg.reply("👋 Bot is working. Send me files.")
 
 
 
 
 
 
 
 
144
 
145
+ @app.on_message(filters.all)
146
+ async def debug(_, msg):
147
+ log.info(f"INCOMING: {msg.text} | {msg.from_user.id if msg.from_user else None}")
148
+
149
+ @app.on_message(filters.document | filters.video | filters.audio)
150
+ async def receive(_, msg):
151
+ user = msg.from_user
152
+ if not user:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  return
154
+
155
+ f = folder(user.id, user.username or str(user.id))
156
+
157
+ file_id = (
158
+ msg.document.file_id if msg.document else
159
+ msg.video.file_id if msg.video else
160
+ msg.audio.file_id
 
161
  )
162
+
163
+ fake = hash_id(file_id)
164
+
165
+ pending[user.id] = {
166
+ "file_id": file_id,
167
+ "folder": f,
168
+ "fake": fake,
169
+ "msg": msg
170
  }
171
 
172
+ kb = InlineKeyboardMarkup([
173
+ [
174
+ InlineKeyboardButton("⬆ Upload", callback_data="up"),
175
+ InlineKeyboardButton("❌ Cancel", callback_data="no")
176
+ ]
177
+ ])
178
+
179
+ await msg.reply("File received. Upload?", reply_markup=kb)
180
+
181
+ @app.on_callback_query()
182
+ async def cb(_, q):
183
+ uid = q.from_user.id
184
+
185
+ if q.data == "no":
186
+ pending.pop(uid, None)
187
+ return await q.message.edit("Cancelled")
188
+
189
+ if q.data == "up":
190
+ if uid in pending:
191
+ await queue.put(pending[uid])
192
+ pending.pop(uid)
193
+ await q.message.edit("Queued ✔")
194
+
195
+ # ================= STARTUP =================
196
+
197
+ async def run_web():
198
+ config = uvicorn.Config(web, host="0.0.0.0", port=7860, log_level="info")
199
+ server = uvicorn.Server(config)
200
+ await server.serve()
201
+
202
+ async def start_bot():
203
+ log.info("Starting Pyrogram bot...")
204
+
205
+ await app.start()
206
+
207
+ me = await app.get_me()
208
+ log.info(f"Bot connected as @{me.username}")
209
 
 
 
 
 
210
  asyncio.create_task(worker())
211
+ asyncio.create_task(keepalive())
212
 
213
+ log.info("Bot is now listening for messages...")
214
+
215
+ await idle()
 
 
 
 
 
 
 
 
 
216
 
217
+ async def main():
218
+ await asyncio.gather(
219
+ start_bot(),
220
+ run_web()
221
+ )
222
 
223
  if __name__ == "__main__":
224
  asyncio.run(main())