Update app.py
Browse files
app.py
CHANGED
|
@@ -1,187 +1,26 @@
|
|
| 1 |
-
import os,
|
| 2 |
-
from
|
| 3 |
-
|
| 4 |
-
import aiohttp
|
| 5 |
-
from aiohttp import web
|
| 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, raw
|
| 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 |
-
SPACE_URL = "https://cxops-push.hf.space"
|
| 35 |
-
|
| 36 |
-
HF_REPO_ID = "Cxops/Bzxv"
|
| 37 |
-
HF_REPO_TYPE = "dataset"
|
| 38 |
-
HF_BRANCH = "main"
|
| 39 |
-
MIN_FREE_DISK = 45 * 1024**3
|
| 40 |
-
SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024
|
| 41 |
-
PROGRESS_INTERVAL = 3
|
| 42 |
-
KEEPALIVE_INTERVAL = 300
|
| 43 |
-
|
| 44 |
-
# ---------- ENCRYPTION ----------
|
| 45 |
-
SALT = b"huggingbot_salt_2025"
|
| 46 |
-
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=SALT,
|
| 47 |
-
iterations=100_000, backend=default_backend())
|
| 48 |
-
key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
|
| 49 |
-
fernet = Fernet(key)
|
| 50 |
-
|
| 51 |
-
def encrypt(data: str) -> str:
|
| 52 |
-
return base64.urlsafe_b64encode(fernet.encrypt(data.encode())).decode().rstrip("=")
|
| 53 |
-
|
| 54 |
-
def decrypt(token: str) -> str:
|
| 55 |
-
pad = 4 - len(token) % 4
|
| 56 |
-
if pad != 4:
|
| 57 |
-
token += "=" * pad
|
| 58 |
-
return fernet.decrypt(base64.urlsafe_b64decode(token)).decode()
|
| 59 |
-
|
| 60 |
-
def get_user_folder(user_id: int) -> str:
|
| 61 |
-
return encrypt(str(user_id))
|
| 62 |
-
|
| 63 |
-
# ---------- HUGGING FACE ----------
|
| 64 |
-
hf_api = HfApi(token=HF_TOKEN)
|
| 65 |
-
|
| 66 |
-
def hf_read_json(path: str) -> Optional[dict]:
|
| 67 |
-
try:
|
| 68 |
-
return json.loads(hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH))
|
| 69 |
-
except EntryNotFoundError:
|
| 70 |
-
return None
|
| 71 |
-
except Exception as e:
|
| 72 |
-
logger.error(f"hf_read_json error: {e}")
|
| 73 |
-
return None
|
| 74 |
-
|
| 75 |
-
def hf_write_json(path: str, data: dict):
|
| 76 |
-
hf_api.upload_file(
|
| 77 |
-
path_or_fileobj=json.dumps(data, indent=2).encode(),
|
| 78 |
-
path_in_repo=path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
|
| 79 |
-
commit_message=f"update {path}"
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
def hf_delete_file(path: str):
|
| 83 |
-
try:
|
| 84 |
-
hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
|
| 85 |
-
commit_message=f"delete {path}")
|
| 86 |
-
except Exception as e:
|
| 87 |
-
logger.error(f"hf_delete_file error: {e}")
|
| 88 |
|
| 89 |
-
def hf_file_size(path: str) -> Optional[int]:
|
| 90 |
-
try:
|
| 91 |
-
return hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE).size
|
| 92 |
-
except EntryNotFoundError:
|
| 93 |
-
return None
|
| 94 |
-
except Exception as e:
|
| 95 |
-
logger.error(f"hf_file_size error: {e}")
|
| 96 |
-
return None
|
| 97 |
-
|
| 98 |
-
def free_disk_gb() -> float:
|
| 99 |
-
return shutil.disk_usage("/").free / (1024**3)
|
| 100 |
-
|
| 101 |
-
def enough_disk(needed: int = 0) -> bool:
|
| 102 |
-
return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
|
| 103 |
-
|
| 104 |
-
# ---------- BOT CLIENT ----------
|
| 105 |
app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
|
| 106 |
|
| 107 |
-
# ---------- GLOBAL STATE ----------
|
| 108 |
-
active_progress: Dict[int, dict] = {}
|
| 109 |
-
op_queue = asyncio.Queue()
|
| 110 |
-
pending_uploads: Dict[int, dict] = {}
|
| 111 |
-
|
| 112 |
-
# ---------- RAW UPDATE LOGGER ----------
|
| 113 |
-
@app.on_raw_update()
|
| 114 |
-
async def raw_logger(client, update, users, chats):
|
| 115 |
-
logger.info(f"RAW UPDATE: {update}")
|
| 116 |
-
|
| 117 |
-
# ---------- DIAGNOSTIC CATCH-ALL (non-blocking) ----------
|
| 118 |
-
@app.on_message(group=1)
|
| 119 |
-
async def debug_all(client, msg: Message):
|
| 120 |
-
logger.info(f"MSG from {msg.from_user.id}: {msg.text or msg.caption or '<no text>'} (chat={msg.chat.id})")
|
| 121 |
-
|
| 122 |
-
# ---------- COMMANDS ----------
|
| 123 |
@app.on_message(filters.command("start"))
|
| 124 |
-
async def
|
| 125 |
-
|
| 126 |
-
await msg.reply("👋 Welcome! Send any file to upload.")
|
| 127 |
|
| 128 |
-
@app.on_message(
|
| 129 |
-
async def
|
| 130 |
-
await msg.reply("
|
| 131 |
|
| 132 |
-
@app.on_message(filters.command("files"))
|
| 133 |
-
async def list_files(_, msg: Message):
|
| 134 |
-
user_id = msg.from_user.id
|
| 135 |
-
meta = hf_read_json(f"{get_user_folder(user_id)}/meta.json")
|
| 136 |
-
if not meta:
|
| 137 |
-
await msg.reply("📭 No files yet.")
|
| 138 |
-
return
|
| 139 |
-
kb = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")] for enc, name in meta.items()]
|
| 140 |
-
kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
|
| 141 |
-
await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(kb))
|
| 142 |
-
|
| 143 |
-
# ---------- KEEP‑ALIVE ----------
|
| 144 |
-
async def keep_alive():
|
| 145 |
-
async def handler(request):
|
| 146 |
-
return web.Response(text="Alive")
|
| 147 |
-
web_app = web.Application()
|
| 148 |
-
web_app.router.add_get("/", handler)
|
| 149 |
-
runner = web.AppRunner(web_app)
|
| 150 |
-
await runner.setup()
|
| 151 |
-
await web.TCPSite(runner, "0.0.0.0", 7860).start()
|
| 152 |
-
logger.info(f"Keep‑alive on :7860, pinging {SPACE_URL}")
|
| 153 |
-
|
| 154 |
-
async def pinger():
|
| 155 |
-
await asyncio.sleep(10)
|
| 156 |
-
while True:
|
| 157 |
-
try:
|
| 158 |
-
async with aiohttp.ClientSession() as s:
|
| 159 |
-
async with s.get(SPACE_URL) as resp:
|
| 160 |
-
logger.info(f"Ping {SPACE_URL} → {resp.status}")
|
| 161 |
-
except Exception as e:
|
| 162 |
-
logger.error(f"Ping failed: {e}")
|
| 163 |
-
await asyncio.sleep(KEEPALIVE_INTERVAL)
|
| 164 |
-
asyncio.create_task(pinger())
|
| 165 |
-
|
| 166 |
-
# ---------- MAIN ----------
|
| 167 |
async def main():
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
await app.start()
|
| 174 |
-
logger.info("Bot online – waiting for messages.")
|
| 175 |
-
break
|
| 176 |
-
except FloodWait as e:
|
| 177 |
-
w = e.value
|
| 178 |
-
logger.warning(f"FloodWait {w}s – waiting...")
|
| 179 |
-
await asyncio.sleep(w)
|
| 180 |
-
except Exception as e:
|
| 181 |
-
logger.exception(f"Start error: {e}")
|
| 182 |
-
await asyncio.sleep(30)
|
| 183 |
-
|
| 184 |
-
# idle forever
|
| 185 |
await asyncio.Event().wait()
|
| 186 |
|
| 187 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
import os, asyncio
|
| 2 |
+
from pyrogram import Client, filters
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
BOT_TOKEN = os.environ["BOT_TOKEN"]
|
| 5 |
API_ID = int(os.environ["API_ID"])
|
| 6 |
API_HASH = os.environ["API_HASH"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
@app.on_message(filters.command("start"))
|
| 11 |
+
async def start(_, msg):
|
| 12 |
+
await msg.reply("Bot works! Send any file to upload.")
|
|
|
|
| 13 |
|
| 14 |
+
@app.on_message()
|
| 15 |
+
async def echo(_, msg):
|
| 16 |
+
await msg.reply(f"Echo: {msg.text}")
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
async def main():
|
| 19 |
+
# Force a fresh session
|
| 20 |
+
if os.path.exists("bot.session"):
|
| 21 |
+
os.remove("bot.session")
|
| 22 |
+
await app.start()
|
| 23 |
+
print("Bot is ready. Send /start.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
await asyncio.Event().wait()
|
| 25 |
|
| 26 |
if __name__ == "__main__":
|