nvd commited on
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -15,14 +15,15 @@ from urllib.parse import unquote
|
|
| 15 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
-
# ---------- Import tokens ----------
|
| 19 |
try:
|
| 20 |
-
from config import BALE_BOT_TOKEN as BALE_TOKEN, GITHUB_TOKEN
|
| 21 |
-
logger.info("Tokens loaded from config.py")
|
| 22 |
except ImportError:
|
| 23 |
BALE_TOKEN = os.getenv("BALE_BOT_TOKEN")
|
| 24 |
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
if not BALE_TOKEN:
|
| 28 |
raise ValueError("β BALE_BOT_TOKEN not set!")
|
|
@@ -185,19 +186,41 @@ async def download_file(url, dest_path):
|
|
| 185 |
f.write(chunk)
|
| 186 |
logger.info(f"β
Downloaded file to {dest_path}")
|
| 187 |
|
| 188 |
-
# ----------
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
"""
|
| 191 |
-
|
| 192 |
"""
|
| 193 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
logger.info(f"π¦ Created ZIP: {zip_path}")
|
| 197 |
|
| 198 |
# ---------- Message / Callback handlers ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
async def handle_message(message: dict):
|
| 200 |
chat_id = message["chat"]["id"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
text = message.get("text", "").strip()
|
| 202 |
if "github.com/" in text and not text.startswith("/"):
|
| 203 |
await handle_on_demand(chat_id, text)
|
|
@@ -210,6 +233,8 @@ async def handle_message(message: dict):
|
|
| 210 |
)
|
| 211 |
|
| 212 |
async def handle_on_demand(chat_id: int, url: str):
|
|
|
|
|
|
|
| 213 |
owner, repo = parse_repo_url(url)
|
| 214 |
if not owner:
|
| 215 |
await send_message(chat_id, "That doesn't look like a valid GitHub URL.")
|
|
@@ -225,6 +250,8 @@ async def handle_on_demand(chat_id: int, url: str):
|
|
| 225 |
await send_message(chat_id, "No assets found in the latest release.")
|
| 226 |
|
| 227 |
async def handle_watch(chat_id: int, text: str):
|
|
|
|
|
|
|
| 228 |
parts = text.split(maxsplit=1)
|
| 229 |
if len(parts) < 2:
|
| 230 |
await send_message(chat_id, "Usage: /watch <github_repo_url>")
|
|
@@ -244,6 +271,10 @@ async def handle_watch(chat_id: int, text: str):
|
|
| 244 |
async def handle_callback(callback: dict):
|
| 245 |
callback_id = callback["id"]
|
| 246 |
chat_id = callback["message"]["chat"]["id"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
data = callback.get("data", "")
|
| 248 |
logger.info(f"π Callback received: data='{data}', chat_id={chat_id}")
|
| 249 |
|
|
@@ -259,13 +290,12 @@ async def handle_callback(callback: dict):
|
|
| 259 |
|
| 260 |
logger.info(f"β¬οΈ Requested asset: {original_filename}")
|
| 261 |
|
| 262 |
-
#
|
| 263 |
-
|
| 264 |
-
if
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
await send_message(chat_id, "π¦ Compressing APK into ZIP...")
|
| 269 |
else:
|
| 270 |
zip_filename = None
|
| 271 |
caption = "Here you go!"
|
|
@@ -280,13 +310,13 @@ async def handle_callback(callback: dict):
|
|
| 280 |
try:
|
| 281 |
await download_file(url, tmp_path)
|
| 282 |
|
| 283 |
-
if
|
| 284 |
-
#
|
| 285 |
zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + zip_filename)
|
| 286 |
zip_path = zip_tmp.name
|
| 287 |
zip_tmp.close()
|
| 288 |
-
|
| 289 |
-
# Remove original
|
| 290 |
os.unlink(tmp_path)
|
| 291 |
upload_path = zip_path
|
| 292 |
upload_filename = zip_filename
|
|
@@ -328,7 +358,7 @@ async def handle_callback(callback: dict):
|
|
| 328 |
await answer_callback(callback_id, "Failed.")
|
| 329 |
finally:
|
| 330 |
# Clean up all temp files
|
| 331 |
-
for path in [tmp_path, upload_path if
|
| 332 |
if path and os.path.exists(path):
|
| 333 |
try:
|
| 334 |
os.unlink(path)
|
|
@@ -355,12 +385,15 @@ async def poll_updates():
|
|
| 355 |
offset = update["update_id"] + 1
|
| 356 |
if "message" in update:
|
| 357 |
logger.info(f"π© Message from {update['message']['chat']['id']}: {update['message'].get('text', '[no text]')[:100]}")
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
| 359 |
elif "callback_query" in update:
|
| 360 |
try:
|
| 361 |
await handle_callback(update["callback_query"])
|
| 362 |
except Exception as e:
|
| 363 |
-
logger.error(f"
|
| 364 |
except Exception as e:
|
| 365 |
logger.error(f"Polling error: {e}", exc_info=True)
|
| 366 |
await asyncio.sleep(5)
|
|
@@ -386,6 +419,8 @@ async def release_poller():
|
|
| 386 |
continue
|
| 387 |
keyboard = build_inline_keyboard(release)
|
| 388 |
for cid in chat_ids:
|
|
|
|
|
|
|
| 389 |
try:
|
| 390 |
await send_message(int(cid), f"π New release for {owner}/{repo}: *{release['name']}*", reply_markup=keyboard)
|
| 391 |
logger.info(f"π Notified {cid} about {repo_url}")
|
|
|
|
| 15 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
+
# ---------- Import tokens and allowed users ----------
|
| 19 |
try:
|
| 20 |
+
from config import BALE_BOT_TOKEN as BALE_TOKEN, GITHUB_TOKEN, ALLOWED_USERS
|
| 21 |
+
logger.info("Tokens and allowed users loaded from config.py")
|
| 22 |
except ImportError:
|
| 23 |
BALE_TOKEN = os.getenv("BALE_BOT_TOKEN")
|
| 24 |
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
|
| 25 |
+
ALLOWED_USERS = [] # if not defined, bot will be open to everyone
|
| 26 |
+
logger.info("Tokens loaded from environment variables; no user restriction")
|
| 27 |
|
| 28 |
if not BALE_TOKEN:
|
| 29 |
raise ValueError("β BALE_BOT_TOKEN not set!")
|
|
|
|
| 186 |
f.write(chunk)
|
| 187 |
logger.info(f"β
Downloaded file to {dest_path}")
|
| 188 |
|
| 189 |
+
# ---------- Compression helper ----------
|
| 190 |
+
COMPRESSED_EXTENSIONS = {
|
| 191 |
+
'.zip', '.gz', '.tgz', '.tar.gz', '.rar', '.7z',
|
| 192 |
+
'.bz2', '.xz', '.tar', '.tar.bz2', '.tar.xz', '.zst', '.lz'
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
def is_compressed(filename: str) -> bool:
|
| 196 |
+
"""Return True if the filename already indicates a compressed archive."""
|
| 197 |
+
lower = filename.lower()
|
| 198 |
+
for ext in COMPRESSED_EXTENSIONS:
|
| 199 |
+
if lower.endswith(ext):
|
| 200 |
+
return True
|
| 201 |
+
return False
|
| 202 |
+
|
| 203 |
+
def compress_to_zip(file_path: str, original_filename: str, zip_path: str):
|
| 204 |
"""
|
| 205 |
+
Create a ZIP archive containing the file (preserving its original name).
|
| 206 |
"""
|
| 207 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 208 |
+
zf.write(file_path, arcname=original_filename)
|
| 209 |
+
logger.info(f"π¦ Compressed to ZIP: {zip_path}")
|
|
|
|
| 210 |
|
| 211 |
# ---------- Message / Callback handlers ----------
|
| 212 |
+
def is_authorized(chat_id: int) -> bool:
|
| 213 |
+
"""Return True if the user is allowed to interact with the bot."""
|
| 214 |
+
if not ALLOWED_USERS: # empty list = no restrictions
|
| 215 |
+
return True
|
| 216 |
+
return chat_id in ALLOWED_USERS
|
| 217 |
+
|
| 218 |
async def handle_message(message: dict):
|
| 219 |
chat_id = message["chat"]["id"]
|
| 220 |
+
if not is_authorized(chat_id):
|
| 221 |
+
await send_message(chat_id, "β You are not authorized to use this bot.")
|
| 222 |
+
return
|
| 223 |
+
|
| 224 |
text = message.get("text", "").strip()
|
| 225 |
if "github.com/" in text and not text.startswith("/"):
|
| 226 |
await handle_on_demand(chat_id, text)
|
|
|
|
| 233 |
)
|
| 234 |
|
| 235 |
async def handle_on_demand(chat_id: int, url: str):
|
| 236 |
+
if not is_authorized(chat_id):
|
| 237 |
+
return
|
| 238 |
owner, repo = parse_repo_url(url)
|
| 239 |
if not owner:
|
| 240 |
await send_message(chat_id, "That doesn't look like a valid GitHub URL.")
|
|
|
|
| 250 |
await send_message(chat_id, "No assets found in the latest release.")
|
| 251 |
|
| 252 |
async def handle_watch(chat_id: int, text: str):
|
| 253 |
+
if not is_authorized(chat_id):
|
| 254 |
+
return
|
| 255 |
parts = text.split(maxsplit=1)
|
| 256 |
if len(parts) < 2:
|
| 257 |
await send_message(chat_id, "Usage: /watch <github_repo_url>")
|
|
|
|
| 271 |
async def handle_callback(callback: dict):
|
| 272 |
callback_id = callback["id"]
|
| 273 |
chat_id = callback["message"]["chat"]["id"]
|
| 274 |
+
if not is_authorized(chat_id):
|
| 275 |
+
await answer_callback(callback_id, "Unauthorized.")
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
data = callback.get("data", "")
|
| 279 |
logger.info(f"π Callback received: data='{data}', chat_id={chat_id}")
|
| 280 |
|
|
|
|
| 290 |
|
| 291 |
logger.info(f"β¬οΈ Requested asset: {original_filename}")
|
| 292 |
|
| 293 |
+
# Determine if we need to compress the file
|
| 294 |
+
need_compress = not is_compressed(original_filename)
|
| 295 |
+
if need_compress:
|
| 296 |
+
zip_filename = original_filename + ".zip"
|
| 297 |
+
caption = f"π¦ File compressed to ZIP for delivery.\nOriginal: `{original_filename}`"
|
| 298 |
+
await send_message(chat_id, "π¦ Compressing file into ZIP...")
|
|
|
|
| 299 |
else:
|
| 300 |
zip_filename = None
|
| 301 |
caption = "Here you go!"
|
|
|
|
| 310 |
try:
|
| 311 |
await download_file(url, tmp_path)
|
| 312 |
|
| 313 |
+
if need_compress:
|
| 314 |
+
# Compress to plain ZIP
|
| 315 |
zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + zip_filename)
|
| 316 |
zip_path = zip_tmp.name
|
| 317 |
zip_tmp.close()
|
| 318 |
+
compress_to_zip(tmp_path, original_filename, zip_path)
|
| 319 |
+
# Remove the original uncompressed file
|
| 320 |
os.unlink(tmp_path)
|
| 321 |
upload_path = zip_path
|
| 322 |
upload_filename = zip_filename
|
|
|
|
| 358 |
await answer_callback(callback_id, "Failed.")
|
| 359 |
finally:
|
| 360 |
# Clean up all temp files
|
| 361 |
+
for path in [tmp_path, upload_path if need_compress else None]:
|
| 362 |
if path and os.path.exists(path):
|
| 363 |
try:
|
| 364 |
os.unlink(path)
|
|
|
|
| 385 |
offset = update["update_id"] + 1
|
| 386 |
if "message" in update:
|
| 387 |
logger.info(f"π© Message from {update['message']['chat']['id']}: {update['message'].get('text', '[no text]')[:100]}")
|
| 388 |
+
try:
|
| 389 |
+
await handle_message(update["message"])
|
| 390 |
+
except Exception as e:
|
| 391 |
+
logger.error(f"Error handling message: {e}", exc_info=True)
|
| 392 |
elif "callback_query" in update:
|
| 393 |
try:
|
| 394 |
await handle_callback(update["callback_query"])
|
| 395 |
except Exception as e:
|
| 396 |
+
logger.error(f"Error in callback: {e}", exc_info=True)
|
| 397 |
except Exception as e:
|
| 398 |
logger.error(f"Polling error: {e}", exc_info=True)
|
| 399 |
await asyncio.sleep(5)
|
|
|
|
| 419 |
continue
|
| 420 |
keyboard = build_inline_keyboard(release)
|
| 421 |
for cid in chat_ids:
|
| 422 |
+
if not is_authorized(int(cid)):
|
| 423 |
+
continue # don't notify unauthorized users
|
| 424 |
try:
|
| 425 |
await send_message(int(cid), f"π New release for {owner}/{repo}: *{release['name']}*", reply_markup=keyboard)
|
| 426 |
logger.info(f"π Notified {cid} about {repo_url}")
|