Gemini CLI commited on
Commit
2f4da2d
Β·
1 Parent(s): 87c3621

fix: chat cleanup, logic improvements, and help menu update

Browse files
Files changed (1) hide show
  1. bot.py +99 -43
bot.py CHANGED
@@ -52,7 +52,7 @@ else:
52
  "β”” πŸ“ `/files` β€’ Personal Storage\n\n"
53
  "✨ *All files are protected and encrypted.*",
54
  reply_markup=InlineKeyboardMarkup([
55
- [InlineKeyboardButton("🌐 Web Dashboard", url=BASE_URL), InlineKeyboardButton("βš™οΈ Settings", callback_data="set_del_cycle")],
56
  [InlineKeyboardButton("πŸ“– Full Usage Guide", callback_data="help_callback")]
57
  ])
58
  )
@@ -62,7 +62,7 @@ else:
62
  await cb.message.edit_text(
63
  "πŸ“– **NexusShare Usage Guide**\n\n"
64
  "1️⃣ **Hosting:** Send any file to get a high-speed direct link instantly.\n\n"
65
- "2️⃣ **Processing:** Use commands like `/zip` or `/pdf_merge`, then send all your files. Click **'βœ… Done'** when finished.\n\n"
66
  "3️⃣ **Unzipping:** Send `/unzip`, then upload your ZIP. You'll get a web link to browse individual files.\n\n"
67
  "4️⃣ **Security:** Use `/settings` to set a global password for your links.\n\n"
68
  "✨ *All files are auto-deleted after 24-48 hours.*",
@@ -74,7 +74,7 @@ else:
74
  await cb.message.edit_text(
75
  "πŸ‘‹ **Welcome to NexusShare Pro!**\n\nSelect a feature below to get started or just send me a file!",
76
  reply_markup=InlineKeyboardMarkup([
77
- [InlineKeyboardButton("🌐 Open Web Dashboard", url=BASE_URL)],
78
  [InlineKeyboardButton("πŸ“– Usage Guide", callback_data="help_callback")]
79
  ])
80
  )
@@ -103,11 +103,13 @@ else:
103
  return await message.reply_text(text)
104
 
105
  udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
 
 
106
  if not os.path.exists(udir) or not os.listdir(udir):
107
  return await message.reply_text(
108
  "πŸ“‚ **Your Cloud Storage is Empty!**\n\n"
109
  "You haven't uploaded any files yet. Send me any file or use the web dashboard to get started.",
110
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Web Dashboard", url=BASE_URL)]])
111
  )
112
 
113
  files = os.listdir(udir)
@@ -125,7 +127,7 @@ else:
125
  if len(files) > 10:
126
  text += f"✨ *+{len(files)-10} more files available in web view.*"
127
 
128
- await message.reply_text(text, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Full Web Manager", url=BASE_URL)]]))
129
 
130
  @bot.on_message(filters.command("settings") & filters.private)
131
  async def settings_cmd(client, message: Message):
@@ -198,13 +200,14 @@ else:
198
 
199
  if mode == "vcompress":
200
  kb = InlineKeyboardMarkup([
201
- [InlineKeyboardButton("πŸ“‰ Low (480p)", callback_data="vc_q_low"), InlineKeyboardButton("🎬 Medium (720p)", callback_data="vc_q_med")],
202
- [InlineKeyboardButton("✨ High (1080p)", callback_data="vc_q_high")],
203
  [InlineKeyboardButton("❌ Cancel", callback_data="close_settings")]
204
  ])
205
  msg = await message.reply_text(
206
  "🎬 **Video Compression Mode**\n━━━━━━━━━━━━━━━━━━━━\n"
207
- "Send the video you want to compress. Quality is set to `Medium` by default.",
 
208
  reply_markup=kb
209
  )
210
  user_sessions[uid] = {"mode":mode, "files":[], "quality":"med", "batch_id":bid, "status_msg_id":msg.id}
@@ -227,6 +230,17 @@ else:
227
  if uid not in user_sessions: return
228
  quality = cb.data.split("_")[-1]
229
  user_sessions[uid]["quality"] = quality
 
 
 
 
 
 
 
 
 
 
 
230
  await cb.answer(f"βœ… Quality set to {quality.upper()}")
231
 
232
  @bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
@@ -274,14 +288,58 @@ else:
274
  sess = user_sessions.get(uid)
275
  if not sess or not sess.get("files"): return await cb.answer("❌ No files provided!")
276
 
277
- await cb.message.edit_text(f"⏳ **Processing your request...**\n━━━━━━━━━━━━\nMode: `{sess['mode'].upper()}`\nFiles: `{len(sess['files'])}`")
 
278
  udir = f"user_{uid}"
279
- ext = ".zip" if sess["mode"]=="zip" else ".pdf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  oname = f"{sess['name']}{ext}" if sess.get("name") else f"{sess['batch_id']}_processed{ext}"
281
  opath = os.path.join(UPLOAD_DIR, udir, oname)
282
 
283
  try:
284
- if sess["mode"] == "zip":
285
  lvl = sess.get("level", 5)
286
  cmd = ["7z", "a", f"-mx={lvl}", "-mmt=on", opath] + [os.path.basename(f) for f in sess["files"]]
287
  p = await asyncio.create_subprocess_exec(*cmd, cwd=os.path.join(UPLOAD_DIR, udir), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
@@ -292,6 +350,11 @@ else:
292
  with open(opath, "wb") as fo: merger.write(fo)
293
  merger.close()
294
 
 
 
 
 
 
295
  settings = user_settings.get(uid, {"password":None})
296
  set_metadata(oname, {"password": settings["password"]})
297
  set_metadata(sess["batch_id"], {"password": settings["password"]})
@@ -300,7 +363,7 @@ else:
300
  vurl = f"{BASE_URL}/view/{udir}/{sess['batch_id']}"
301
 
302
  await cb.message.edit_text(
303
- f"βœ… **Processing Finished!**\n━━━━━━━━━━━━\n"
304
  f"πŸ“‚ **File:** `{oname}`\n\n"
305
  f"πŸ“₯ [Direct Download]({durl})\n"
306
  f"🌐 [Web Dashboard]({vurl})\n\n"
@@ -327,6 +390,7 @@ else:
327
 
328
  is_tool = uid in user_sessions
329
  sname = f"{user_sessions[uid]['batch_id'] if is_tool else str(uuid.uuid4())[:4]}_{fname}"
 
330
  fpath = os.path.join(udir, sname)
331
 
332
  status = await message.reply_text("πŸ“₯ **Initializing...**", quote=True)
@@ -369,43 +433,35 @@ else:
369
  del user_sessions[uid]
370
  return
371
 
372
- if user_sessions[uid]["mode"] == "vcompress":
373
- await status.edit_text("⏳ **Compressing Video (H.265 Advanced)...**\n*This is an intensive process and may take time, but the size reduction will be massive.*")
374
- quality = user_sessions[uid].get("quality", "med")
375
-
376
- # ADVANCED H.265 (HEVC) COMPRESSION
377
- # libx265 provides ~50% better compression than x264 at the same quality
378
- q_s = {
379
- "low": ["-vf", "scale=-2:480", "-c:v", "libx265", "-crf", "30", "-preset", "fast"],
380
- "med": ["-vf", "scale=-2:720", "-c:v", "libx265", "-crf", "28", "-preset", "fast"],
381
- "high": ["-vf", "scale=-2:1080", "-c:v", "libx265", "-crf", "26", "-preset", "fast"]
382
- }
383
-
384
- opath = fpath.rsplit(".", 1)[0] + "_compressed.mp4"
385
- cmd = ["ffmpeg", "-i", fpath] + q_s.get(quality, q_s["med"]) + ["-c:a", "aac", "-b:a", "96k", opath, "-y"]
386
-
387
- p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
388
- await p.communicate()
389
-
390
- if os.path.exists(opath):
391
- saved = 100 - (os.path.getsize(opath)*100/os.path.getsize(fpath))
392
- os.remove(fpath)
393
- fpath = opath
394
- await status.edit_text(f"βœ… **Compressed!**\nπŸ“Š Saved: `{saved:.1f}%`\n\nπŸ“₯ [Download]({BASE_URL}/download/user_{uid}/{os.path.basename(opath)})", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("πŸ“₯ Download", url=f"{BASE_URL}/download/user_{uid}/{os.path.basename(opath)}")]]) )
395
- else: await status.edit_text("❌ Compression failed.")
396
- del user_sessions[uid]
397
- return
398
-
399
- user_sessions[uid]["files"].append(fpath)
400
  await status.delete()
401
- try: await client.edit_message_text(uid, user_sessions[uid]["status_msg_id"], f"πŸ“¦ **{user_sessions[uid]['mode'].upper()} Active**\n━━━━━━━━━━━━\nπŸ“‚ Added: `{fname}`\nπŸ”’ Total: `{len(user_sessions[uid]['files'])}`", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("✏️ Rename", callback_data="tool_rename")],[InlineKeyboardButton("βœ… Done", callback_data="tool_done")]]))
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  except: pass
 
403
  else:
404
  settings = user_settings.get(uid, {"password":None})
405
  set_metadata(os.path.basename(fpath), {"password": settings["password"]})
406
  durl = f"{BASE_URL}/download/user_{uid}/{os.path.basename(fpath)}"
407
- kb = InlineKeyboardMarkup([[InlineKeyboardButton("πŸ“₯ Download", url=durl)]])
 
 
408
  if fname.lower().endswith(('.mp4', '.mkv', '.webm')):
409
- kb.add(InlineKeyboardButton("🎬 Watch Online", url=f"{BASE_URL}/player/user_{uid}/{os.path.basename(fpath)}"))
 
 
410
  await status.edit_text(f"βœ… **Upload Success!**\n`{fname}`\n\nπŸ›‘οΈ Pass: `{'Yes' if settings['password'] else 'No'}`", reply_markup=kb)
411
  except Exception as e: await status.edit_text(f"❌ Error: {e}")
 
52
  "β”” πŸ“ `/files` β€’ Personal Storage\n\n"
53
  "✨ *All files are protected and encrypted.*",
54
  reply_markup=InlineKeyboardMarkup([
55
+ [InlineKeyboardButton("🌐 Web Dashboard", url=f"{BASE_URL}/?uid={message.from_user.id}"), InlineKeyboardButton("βš™οΈ Settings", callback_data="set_del_cycle")],
56
  [InlineKeyboardButton("πŸ“– Full Usage Guide", callback_data="help_callback")]
57
  ])
58
  )
 
62
  await cb.message.edit_text(
63
  "πŸ“– **NexusShare Usage Guide**\n\n"
64
  "1️⃣ **Hosting:** Send any file to get a high-speed direct link instantly.\n\n"
65
+ "2️⃣ **Processing:** Use commands like `/zip`, `/pdf_merge` or `/vcompress` (H.265), then send all your files. Click **'βœ… Done'** when finished.\n\n"
66
  "3️⃣ **Unzipping:** Send `/unzip`, then upload your ZIP. You'll get a web link to browse individual files.\n\n"
67
  "4️⃣ **Security:** Use `/settings` to set a global password for your links.\n\n"
68
  "✨ *All files are auto-deleted after 24-48 hours.*",
 
74
  await cb.message.edit_text(
75
  "πŸ‘‹ **Welcome to NexusShare Pro!**\n\nSelect a feature below to get started or just send me a file!",
76
  reply_markup=InlineKeyboardMarkup([
77
+ [InlineKeyboardButton("🌐 Open Web Dashboard", url=f"{BASE_URL}/?uid={cb.from_user.id}")],
78
  [InlineKeyboardButton("πŸ“– Usage Guide", callback_data="help_callback")]
79
  ])
80
  )
 
103
  return await message.reply_text(text)
104
 
105
  udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
106
+ web_url = f"{BASE_URL}/?uid={uid}"
107
+
108
  if not os.path.exists(udir) or not os.listdir(udir):
109
  return await message.reply_text(
110
  "πŸ“‚ **Your Cloud Storage is Empty!**\n\n"
111
  "You haven't uploaded any files yet. Send me any file or use the web dashboard to get started.",
112
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Web Dashboard", url=web_url)]])
113
  )
114
 
115
  files = os.listdir(udir)
 
127
  if len(files) > 10:
128
  text += f"✨ *+{len(files)-10} more files available in web view.*"
129
 
130
+ await message.reply_text(text, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Full Web Manager", url=web_url)]]))
131
 
132
  @bot.on_message(filters.command("settings") & filters.private)
133
  async def settings_cmd(client, message: Message):
 
200
 
201
  if mode == "vcompress":
202
  kb = InlineKeyboardMarkup([
203
+ [InlineKeyboardButton("πŸ”‹ Ultra Low (360p)", callback_data="vc_q_ulow"), InlineKeyboardButton("πŸ“‰ Low (480p)", callback_data="vc_q_low")],
204
+ [InlineKeyboardButton("🎬 Medium (720p)", callback_data="vc_q_med"), InlineKeyboardButton("✨ High (1080p)", callback_data="vc_q_high")],
205
  [InlineKeyboardButton("❌ Cancel", callback_data="close_settings")]
206
  ])
207
  msg = await message.reply_text(
208
  "🎬 **Video Compression Mode**\n━━━━━━━━━━━━━━━━━━━━\n"
209
+ "Send the videos you want to compress. Quality is set to `Medium` by default.\n"
210
+ "You can send multiple videos to process them in a batch.",
211
  reply_markup=kb
212
  )
213
  user_sessions[uid] = {"mode":mode, "files":[], "quality":"med", "batch_id":bid, "status_msg_id":msg.id}
 
230
  if uid not in user_sessions: return
231
  quality = cb.data.split("_")[-1]
232
  user_sessions[uid]["quality"] = quality
233
+
234
+ q_map = {"ulow": "360p", "low": "480p", "med": "720p", "high": "1080p"}
235
+ kb = InlineKeyboardMarkup([
236
+ [InlineKeyboardButton("βœ… Start Batch Compression", callback_data="tool_done")]
237
+ ])
238
+ await cb.message.edit_text(
239
+ f"🎬 **Video Compression Mode**\n━━━━━━━━━━━━\n"
240
+ f"Quality: `{q_map.get(quality, '720p')}`\n\n"
241
+ "✨ Now send me all the videos you want to compress, then click 'Start' below.",
242
+ reply_markup=kb
243
+ )
244
  await cb.answer(f"βœ… Quality set to {quality.upper()}")
245
 
246
  @bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
 
288
  sess = user_sessions.get(uid)
289
  if not sess or not sess.get("files"): return await cb.answer("❌ No files provided!")
290
 
291
+ mode = sess["mode"]
292
+ await cb.message.edit_text(f"⏳ **Processing your request...**\n━━━━━━━━━━━━\nMode: `{mode.upper()}`\nFiles: `{len(sess['files'])}`")
293
  udir = f"user_{uid}"
294
+
295
+ if mode == "vcompress":
296
+ results_text = "🎬 **Batch Compression Results:**\n━━━━━━━━━━━━━━━━━━━━\n\n"
297
+ quality = sess.get("quality", "med")
298
+ q_s = {
299
+ "ulow": ["-vf", "scale=-2:360", "-c:v", "libx265", "-crf", "32", "-preset", "fast"],
300
+ "low": ["-vf", "scale=-2:480", "-c:v", "libx265", "-crf", "30", "-preset", "fast"],
301
+ "med": ["-vf", "scale=-2:720", "-c:v", "libx265", "-crf", "28", "-preset", "fast"],
302
+ "high": ["-vf", "scale=-2:1080", "-c:v", "libx265", "-crf", "26", "-preset", "fast"]
303
+ }
304
+
305
+ for i, fpath in enumerate(sess["files"]):
306
+ if not os.path.exists(fpath): continue
307
+ fname = os.path.basename(fpath)
308
+ await cb.message.edit_text(f"⏳ **Compressing Video ({i+1}/{len(sess['files'])})...**\n`{fname}`")
309
+
310
+ opath = fpath.rsplit(".", 1)[0] + "_batch_comp.mp4"
311
+ cmd = ["ffmpeg", "-i", fpath] + q_s.get(quality, q_s["med"]) + ["-c:a", "aac", "-b:a", "96k", opath, "-y"]
312
+
313
+ p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
314
+ await p.communicate()
315
+
316
+ # Cleaning source files
317
+ if os.path.exists(opath):
318
+ orig_size = os.path.getsize(fpath)
319
+ new_size = os.path.getsize(opath)
320
+ saved = 100 - (new_size * 100 / orig_size) if orig_size > 0 else 0
321
+ try: os.remove(fpath)
322
+ except: pass
323
+ sname = os.path.basename(opath)
324
+ set_metadata(sname, {"password": user_settings.get(uid, {}).get("password")})
325
+ durl = f"{BASE_URL}/download/user_{uid}/{sname}"
326
+ results_text += f"βœ… `{fname}`\nβ”” πŸ“Š Saved: `{saved:.1f}%` β€’ [Link]({durl})\n\n"
327
+ else:
328
+ results_text += f"❌ `{fname}` - Compression failed.\n\n"
329
+ # Even if failed, if the user requested batch, we might want to clean up to save space
330
+ # try: os.remove(fpath) except: pass
331
+
332
+ await cb.message.edit_text(results_text, disable_web_page_preview=True)
333
+ del user_sessions[uid]
334
+ return
335
+
336
+ # ZIP and PDF Merge logic
337
+ ext = ".zip" if mode=="zip" else ".pdf"
338
  oname = f"{sess['name']}{ext}" if sess.get("name") else f"{sess['batch_id']}_processed{ext}"
339
  opath = os.path.join(UPLOAD_DIR, udir, oname)
340
 
341
  try:
342
+ if mode == "zip":
343
  lvl = sess.get("level", 5)
344
  cmd = ["7z", "a", f"-mx={lvl}", "-mmt=on", opath] + [os.path.basename(f) for f in sess["files"]]
345
  p = await asyncio.create_subprocess_exec(*cmd, cwd=os.path.join(UPLOAD_DIR, udir), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
 
350
  with open(opath, "wb") as fo: merger.write(fo)
351
  merger.close()
352
 
353
+ # CLEANUP: Delete source files after successful processing
354
+ for f in sess["files"]:
355
+ try: os.remove(f)
356
+ except: pass
357
+
358
  settings = user_settings.get(uid, {"password":None})
359
  set_metadata(oname, {"password": settings["password"]})
360
  set_metadata(sess["batch_id"], {"password": settings["password"]})
 
363
  vurl = f"{BASE_URL}/view/{udir}/{sess['batch_id']}"
364
 
365
  await cb.message.edit_text(
366
+ f"βœ… **{mode.upper()} Finished!**\n━━━━━━━━━━━━\n"
367
  f"πŸ“‚ **File:** `{oname}`\n\n"
368
  f"πŸ“₯ [Direct Download]({durl})\n"
369
  f"🌐 [Web Dashboard]({vurl})\n\n"
 
390
 
391
  is_tool = uid in user_sessions
392
  sname = f"{user_sessions[uid]['batch_id'] if is_tool else str(uuid.uuid4())[:4]}_{fname}"
393
+ if is_tool: sname = f"{len(user_sessions[uid].get('files', []))+1:03d}_{sname}"
394
  fpath = os.path.join(udir, sname)
395
 
396
  status = await message.reply_text("πŸ“₯ **Initializing...**", quote=True)
 
433
  del user_sessions[uid]
434
  return
435
 
436
+ # Batch processing for others
437
+ user_sessions[uid].setdefault("files", []).append(fpath)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
  await status.delete()
439
+ try:
440
+ btn_row1 = []
441
+ if user_sessions[uid]["mode"] != "vcompress":
442
+ btn_row1.append(InlineKeyboardButton("✏️ Rename", callback_data="tool_rename"))
443
+
444
+ await client.edit_message_text(
445
+ uid, user_sessions[uid]["status_msg_id"],
446
+ f"πŸ“¦ **{user_sessions[uid]['mode'].upper()} Active**\n━━━━━━━━━━━━\n"
447
+ f"πŸ“‚ Added: `{fname}`\nπŸ”’ Total: `{len(user_sessions[uid]['files'])}`",
448
+ reply_markup=InlineKeyboardMarkup([
449
+ btn_row1,
450
+ [InlineKeyboardButton("βœ… Done / Start Process", callback_data="tool_done")]
451
+ ])
452
+ )
453
  except: pass
454
+ return
455
  else:
456
  settings = user_settings.get(uid, {"password":None})
457
  set_metadata(os.path.basename(fpath), {"password": settings["password"]})
458
  durl = f"{BASE_URL}/download/user_{uid}/{os.path.basename(fpath)}"
459
+
460
+ # Fix for InlineKeyboardMarkup issue
461
+ btns = [[InlineKeyboardButton("πŸ“₯ Download", url=durl)]]
462
  if fname.lower().endswith(('.mp4', '.mkv', '.webm')):
463
+ btns.append([InlineKeyboardButton("🎬 Watch Online", url=f"{BASE_URL}/player/user_{uid}/{os.path.basename(fpath)}")])
464
+
465
+ kb = InlineKeyboardMarkup(btns)
466
  await status.edit_text(f"βœ… **Upload Success!**\n`{fname}`\n\nπŸ›‘οΈ Pass: `{'Yes' if settings['password'] else 'No'}`", reply_markup=kb)
467
  except Exception as e: await status.edit_text(f"❌ Error: {e}")