Jitendrayoutubelive commited on
Commit
0eb1980
·
verified ·
1 Parent(s): 27ae582

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +162 -279
bot.py CHANGED
@@ -21,19 +21,19 @@ def health_check():
21
  def run_flask():
22
  app.run(host="0.0.0.0", port=7860)
23
 
24
- # --- Telegram Bot की डिटेल्स ---
25
- BOT_TOKEN = os.environ.get("BOT_TOKEN")
26
- API_ID = int(os.environ.get("API_ID"))
27
- API_HASH = os.environ.get("API_HASH")
28
 
29
  bot = Client("LiveBot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
30
 
31
  # --- USER SESSION (Private Channel Download के लिए) ---
32
- USER_SESSION = os.environ.get("USER_SESSION")
33
  user_app = Client("UserAcc", api_id=API_ID, api_hash=API_HASH, session_string=USER_SESSION)
34
 
35
  # --- ग्लोबल वेरिएबल्स ---
36
- ADMIN_ID = 8806858506
37
  GLOBAL_PASSWORD = "jitu@123"
38
  PASSWORD_LIMIT = 999999 # डिफ़ॉल्ट लिमिट (Unlimted)
39
  PASSWORD_USED_BY = {} # जिन लोगों ने पासवर्ड इस्तेमाल किया है उनका डेटा
@@ -112,15 +112,12 @@ def format_date(dt):
112
 
113
  def get_video_duration(file_path):
114
  try:
115
- cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1"]
116
- # ऑनलाइन लिंक (Archive.org) के लिए हेडर
117
- if str(file_path).startswith("http"):
118
- cmd.extend(["-headers", "User-Agent: Mozilla/5.0\r\n"])
119
- cmd.append(str(file_path))
120
-
121
- result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=8)
122
- val = float(result.stdout.strip())
123
- return val if val > 0 else 0
124
  except:
125
  return 0
126
 
@@ -163,15 +160,15 @@ def init_user(user_id, message=None):
163
  'rtmp_url': None,
164
  'loop_hours': 0,
165
  'orientation': 'landscape',
166
- 'custom_image_path': None, # नया: कस्टम फोटो सेव करने के लिए
167
- 'custom_audio_path': None, # ऑडियो रिप्लेस
168
- 'watermark_text': None, # <--- नया: मूविंग वाटरमार्क के लिए
169
- 'video_url': None, # डायरेक्ट लिंक
170
- 'schedule_time': None, # शेड्यूलिंग
171
  'processes':[],
172
- 'scheduled_tasks': {}, # <--- नया: शेड्यूल्ड टास्क को ट्रैक करने के लिए
173
  'stream_limit': GLOBAL_LIMIT,
174
- 'file_path': None,
175
  'manual_stop': False,
176
  'join_date': get_ist_time(),
177
  'last_online': get_ist_time(),
@@ -207,10 +204,10 @@ def watermark_choice_keyboard():
207
  def schedule_choice_keyboard():
208
  return InlineKeyboardMarkup([[InlineKeyboardButton("▶️ Start Now", callback_data="sch_now")],[InlineKeyboardButton("⏳ Schedule Time", callback_data="sch_later")]])
209
 
210
- def add_more_videos_keyboard():
211
  return InlineKeyboardMarkup([
212
- [InlineKeyboardButton("➕ Add 1 More Video (Merge)", callback_data="vid_add_more")],
213
- [InlineKeyboardButton("✅ Done (Go to Next Step)", callback_data="vid_done")]
214
  ])
215
 
216
  def admin_keyboard():
@@ -271,13 +268,11 @@ async def new_cmd(client, message):
271
  return await message.reply("🔐 **Session Expired! Please enter the new password:**")
272
 
273
  user_data[user_id]['step'] = 'PLATFORM'
274
- # नई स्ट्रीम शुरू करते समय पुराना डेटा मिटा दें (ताकि पहली स्ट्रीम से मिक्स न हो)
275
  user_data[user_id]['custom_image_path'] = None
276
  user_data[user_id]['custom_audio_path'] = None
277
  user_data[user_id]['watermark_text'] = None
278
  user_data[user_id]['video_url'] = None
279
- user_data[user_id]['file_path'] = None
280
- user_data[user_id]['file_paths'] = []
281
  await message.reply("🔄 **New Stream Setup!**\n👇 **Select platform:**", reply_markup=platform_keyboard())
282
 
283
  @bot.on_message(filters.command("stop"))
@@ -285,35 +280,21 @@ async def stop_cmd(client, message):
285
  user_id = message.chat.id
286
  if user_id not in user_data: return
287
 
288
- # एक्टिव स्ट्रीम्स की सही लिस्ट निकालें
289
  active_procs = [p for p in user_data[user_id].get('processes', []) if (p['process'].poll() if isinstance(p, dict) else p.poll()) is None]
290
- user_data[user_id]['processes'] = active_procs
291
-
292
  if not active_procs:
293
- user_data[user_id]['file_paths'] = []
294
- return await message.reply("⚠️ **No active stream found.**")
295
 
296
- # अगर सिर्फ 1 ही स्ट्रीम चल रही है, तो उसे सीधे बंद कर दो
297
- if len(active_procs) == 1:
298
- p = active_procs[0]
299
- proc_obj = p['process'] if isinstance(p, dict) else p
300
- user_data[user_id]['manual_stop'] = True
301
- proc_obj.terminate()
302
- user_data[user_id]['processes'] = []
303
- return await message.reply("🛑 **Stopping 1 Active Stream... Generating Report!**")
304
-
305
- # [FIX] अगर 1 से ज्यादा स्ट्रीम्स चल रही हैं, तो बटन देकर पूछें कि कौन सी बंद करनी है:
306
  markup = []
307
- text = f"⚠️ **आपकी {len(active_procs)} स्ट्रीम्स एक साथ चल रही हैं!**\n👇 **आप कौन सी स्ट्रीम बंद करना चाहते हैं?**\n\n"
308
  for idx, p in enumerate(active_procs, 1):
309
- if isinstance(p, dict):
310
- p_id = p.get('id', 'unknown')
311
- plat = p.get('platform', 'Live')
312
- st_time = p['start_time'].strftime("%I:%M %p")
313
- text += f"{idx}. 🟢 **{plat}** - Started: `{st_time}`\n"
314
- markup.append([InlineKeyboardButton(f"🛑 Stop Stream {idx} ({st_time})", callback_data=f"user_stop_{p_id}")])
315
-
316
- markup.append([InlineKeyboardButton("💥 Stop All (दोनों/सभी बंद करें)", callback_data="user_stop_all")])
317
  await message.reply(text, reply_markup=InlineKeyboardMarkup(markup))
318
 
319
  @bot.on_callback_query(filters.regex("^admin_"))
@@ -525,17 +506,7 @@ async def select_image_choice(client, callback_query: CallbackQuery):
525
  text = "⬛️ **No Image Selected (Black Background).**\n\n📥 **अब कोई Video File भेजें या डायरेक्ट Link (YouTube/Insta/FB) भेजें:**"
526
 
527
  await callback_query.message.edit_text(text)
528
- @bot.on_callback_query(filters.regex("^vid_"))
529
- async def video_list_choice(client, callback_query: CallbackQuery):
530
- user_id = callback_query.message.chat.id
531
- if callback_query.data == "vid_add_more":
532
- await callback_query.message.edit_text("📥 **अगला Video File या Link (YouTube/Archive) भेजें, मैं उसे पिछली वीडियो के साथ जोड़ दूंगा (Merge करूँगा):**")
533
- elif callback_query.data == "vid_done":
534
- user_data[user_id]['step'] = 'WATERMARK_CHOICE'
535
- if user_data[user_id].get('is_image_only'):
536
- await callback_query.message.edit_text("✨ **क्या आप फोटो पर चलता हुआ (Moving) नाम/वाटरमार्क लगाना चाहते हैं?**\n(यह YouTube को स्पैम से बचाएगा)", reply_markup=watermark_choice_keyboard())
537
- else:
538
- await callback_query.message.edit_text("✨ **क्या आप वीडियो पर Watermark (जैसे 'Class PDF Telegram...') लगाना चाहते हैं?**\n(यह हर 1 मिनट में दिखाई देगा)", reply_markup=watermark_choice_keyboard())
539
  @bot.on_callback_query(filters.regex("^aud_"))
540
  async def select_audio_choice(client, callback_query: CallbackQuery):
541
  user_id = callback_query.message.chat.id
@@ -557,40 +528,36 @@ async def select_watermark_choice(client, callback_query: CallbackQuery):
557
  user_data[user_id]['step'] = 'AUDIO_CHOICE'
558
  await callback_query.message.edit_text("🎵 **YouTube के लिए ऑडियो जरूरी है।**\nक्या आप अपना खुद का Audio (MP3) लगाना चाहते हैं?", reply_markup=audio_choice_keyboard())
559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560
  @bot.on_callback_query(filters.regex("^sch_"))
561
  async def select_schedule_choice(client, callback_query: CallbackQuery):
562
  user_id = callback_query.message.chat.id
563
  if callback_query.data == "sch_now":
564
  user_data[user_id]['step'] = 'READY'
565
  await callback_query.message.delete()
566
-
567
- # --- [FIX] दोनों स्ट्रीम्स को अलग रखने के लिए स्नैपशॉट ---
568
- stream_config = {
569
- 'file_paths': list(user_data[user_id].get('file_paths', [])),
570
- 'file_path': user_data[user_id].get('file_path'),
571
- 'video_url': user_data[user_id].get('video_url'),
572
- 'custom_audio_path': user_data[user_id].get('custom_audio_path'),
573
- 'platform': user_data[user_id].get('platform', 'Custom'),
574
- 'loop_hours': user_data[user_id].get('loop_hours', 0),
575
- 'rtmp_url': user_data[user_id].get('rtmp_url'),
576
- 'orientation': user_data[user_id].get('orientation', 'landscape'),
577
- 'custom_image_path': user_data[user_id].get('custom_image_path'),
578
- 'is_image_only': user_data[user_id].get('is_image_only', False),
579
- 'watermark_text': user_data[user_id].get('watermark_text')
580
- }
581
- user_data[user_id]['file_paths'] = []
582
- user_data[user_id]['video_url'] = None
583
- user_data[user_id]['custom_image_path'] = None
584
- user_data[user_id]['custom_audio_path'] = None
585
-
586
- await handle_video(client, callback_query.message, stream_config)
587
  else:
588
  user_data[user_id]['step'] = 'AWAIT_DATETIME'
589
  update_schedule_dates()
590
  markup = []
591
  for st in GLOBAL_SCHEDULE_TIMES:
 
592
  markup.append([InlineKeyboardButton(f"🗓 {st}", callback_data=f"set_schtime_{st}")])
593
 
 
594
  text = "📅 **Schedule Time चुनें या लिखें!**\n\n"
595
  if GLOBAL_SCHEDULE_TIMES:
596
  text += "👇 **एडमिन द्वारा दिए गए समय में से चुनें:**\n"
@@ -830,47 +797,43 @@ async def handle_all_messages(client, message):
830
  elif step == 'VIDEO_OR_URL':
831
  user_data[user_id]['is_image_only'] = False
832
 
 
 
 
 
833
  if message.video or message.document:
834
- msg = await message.reply("⏳ **Downloading Video...**")
835
  start_time = time.time()
836
  last_update = [start_time]
 
837
 
838
- ext = ".mp4"
839
- try:
840
- if message.video and message.video.file_name: ext = os.path.splitext(message.video.file_name)[1]
841
- elif message.document and message.document.file_name: ext = os.path.splitext(message.document.file_name)[1]
842
- except: pass
843
-
844
- safe_file_name = f"vid_{user_id}_{message.id}{ext}"
845
- file_path = await message.download(file_name=safe_file_name, progress=progress_bar, progress_args=(msg, start_time, last_update))
846
-
847
- if 'file_paths' not in user_data[user_id]:
848
- user_data[user_id]['file_paths'] = []
849
- user_data[user_id]['file_paths'].append((message.id, file_path))
850
 
851
- count = len(user_data[user_id]['file_paths'])
852
- await msg.edit_text(f"✅ **Video {count} Saved Successfully!**\n\n➕ **क्या आप और वीडियो जोड़कर लगातार चलाना चाहते हैं?**", reply_markup=add_more_videos_keyboard())
853
 
854
  elif message.photo:
855
  msg = await message.reply("⏳ **Downloading Image...**")
856
- safe_file_name = f"photo_{user_id}_{message.id}.jpg"
857
- file_path = await message.download(file_name=safe_file_name)
858
-
859
- user_data[user_id]['file_paths'] = [(message.id, file_path)]
860
  user_data[user_id]['is_image_only'] = True
861
  await msg.delete()
862
  user_data[user_id]['step'] = 'WATERMARK_CHOICE'
863
- await message.reply("✨ **क्या आप फोटो पर चलता हुआ (Moving) नाम/वाटरमार्क लगाना चाहते हैं?**\n(यह YouTube को स्पैम से बचाएगा)", reply_markup=watermark_choice_keyboard())
864
 
865
  elif message.text and "t.me/c/" in message.text:
866
  if not USER_SESSION:
867
- return await message.reply("❌ **String Session सेट नहीं है! बॉट के कोड में USER_SESSION डालें।**")
868
- msg = await message.reply("🔍 **प्राइवेट चैनल में वीडियो ढूँढा जा रहा है...**")
869
  try:
870
  link_parts = message.text.strip().split('/')
871
  chat_id = int("-100" + link_parts[4])
872
  msg_id = int(link_parts[5])
873
- if not user_app.is_connected: await user_app.start()
 
 
874
 
875
  target_msg = None
876
  messages = await user_app.get_messages(chat_id, range(max(1, msg_id - 10), msg_id + 11))
@@ -879,50 +842,26 @@ async def handle_all_messages(client, message):
879
  target_msg = m
880
  break
881
 
882
- if not target_msg: return await msg.edit_text("❌ **इस लिंक के आस-पास कोई Video नहीं मिला!**")
883
-
884
- await msg.edit_text("⏳ **Private Video Downloading...**")
 
885
  start_time = time.time()
886
  last_update = [start_time]
 
887
 
888
- ext = ".mp4"
889
- try:
890
- if target_msg.video and target_msg.video.file_name: ext = os.path.splitext(target_msg.video.file_name)[1]
891
- elif target_msg.document and target_msg.document.file_name: ext = os.path.splitext(target_msg.document.file_name)[1]
892
- except: pass
893
-
894
- safe_file_name = f"vid_{user_id}_{target_msg.id}{ext}"
895
- file_path = await user_app.download_media(target_msg, file_name=safe_file_name, progress=progress_bar, progress_args=(msg, start_time, last_update))
896
 
897
- if 'file_paths' not in user_data[user_id]:
898
- user_data[user_id]['file_paths'] = []
899
- user_data[user_id]['file_paths'].append((message.id, file_path))
 
900
 
901
- count = len(user_data[user_id]['file_paths'])
902
- await msg.edit_text(f"✅ **Video {count} Saved Successfully!**\n\n➕ **क्या आप और वीडियो जोड़कर लगातार चलाना चाहते हैं?**", reply_markup=add_more_videos_keyboard())
903
- except Exception as e: return await msg.edit_text(f"❌ **Private Video Error:** {str(e)}")
904
-
905
  elif message.text and ("http://" in message.text or "https://" in message.text):
906
- url = message.text.strip()
907
- msg = await message.reply("🔍 **डायरेक्ट लिंक चेक किया जा रहा है (No Download)...**")
908
-
909
- # अगर यूट्यूब या अन्य सोशल मीडिया का लिंक है तो डायरेक्ट स्ट्रीम लिंक निकालें
910
- if any(x in url for x in ["youtube.com", "youtu.be", "rumble.com", "facebook.com"]):
911
- direct_url = await asyncio.to_thread(get_direct_url, url)
912
- else:
913
- direct_url = url # Archive.org / MP4 लिंक सीधा चलेगा
914
-
915
- if 'file_paths' not in user_data[user_id]:
916
- user_data[user_id]['file_paths'] = []
917
- user_data[user_id]['file_paths'].append((int(time.time()), direct_url))
918
-
919
- count = len(user_data[user_id]['file_paths'])
920
- await msg.edit_text(
921
- f"✅ **Link {count} Saved (Direct Stream)!**\n"
922
- f"⚡ __यह बिना डाउनलोड किए सीधा इंटरनेट से लाइव चलेगा (Zero CPU Load).__\n\n"
923
- f"➕ **क्या आप और वीडियो या लिंक जोड़ना चाहते हैं?**",
924
- reply_markup=add_more_videos_keyboard()
925
- )
926
  else:
927
  return await message.reply("⚠️ **कृपया सही Video, Photo या Link भेजें!**")
928
 
@@ -960,7 +899,7 @@ async def handle_all_messages(client, message):
960
  # --- Snapshot Configuration ---
961
  # (अगर यूज़र दूसरी स्ट्रीम बनायेगा तो पहली स्ट्रीम का डेटा डिलीट न हो)
962
  stream_config = {
963
- 'file_path': user_data[user_id].get('file_path'),
964
  'video_url': user_data[user_id].get('video_url'),
965
  'custom_audio_path': user_data[user_id].get('custom_audio_path'),
966
  'platform': user_data[user_id].get('platform', 'Custom'),
@@ -1006,40 +945,18 @@ async def cancel_sch_callback(client, callback_query: CallbackQuery):
1006
  @bot.on_callback_query(filters.regex("^user_stop_"))
1007
  async def stop_running_callback(client, callback_query: CallbackQuery):
1008
  user_id = callback_query.message.chat.id
1009
- data = callback_query.data
1010
 
1011
- # अगर यूज़र ने "Stop All" दबाया
1012
- if data == "user_stop_all":
1013
- active_procs = [p for p in user_data[user_id].get('processes', []) if (p['process'].poll() if isinstance(p, dict) else p.poll()) is None]
1014
- if not active_procs:
1015
- return await callback_query.message.edit_text("❌ **कोई भी स्ट्रीम अभी चालू नहीं है।**")
1016
- user_data[user_id]['manual_stop'] = True
1017
- for p in active_procs:
1018
- proc = p['process'] if isinstance(p, dict) else p
1019
- proc.terminate()
1020
- user_data[user_id]['processes'] = []
1021
- return await callback_query.message.edit_text(f"🛑 **सभी {len(active_procs)} स्ट्रीम्स बंद कर दी गई हैं!**")
1022
-
1023
- # अगर यूज़र ने किसी एक स्ट्रीम को चुना:
1024
- p_id = data.replace("user_stop_", "")
1025
  stopped = False
1026
- remaining = []
1027
-
1028
  for p in user_data[user_id].get('processes', []):
1029
- if isinstance(p, dict) and p.get('id') == p_id:
1030
- if p['process'].poll() is None:
1031
- user_data[user_id]['manual_stop'] = True
1032
- p['process'].terminate()
1033
- stopped = True
1034
- else:
1035
- # बाकी बची हुई जिंदा स्ट्रीम्स को लिस्ट में सुरक्षित रखें
1036
- if (p['process'].poll() if isinstance(p, dict) else p.poll()) is None:
1037
- remaining.append(p)
1038
-
1039
- user_data[user_id]['processes'] = remaining
1040
-
1041
  if stopped:
1042
- await callback_query.message.edit_text("✅ **सिर्फ चुनी हुई स्ट्रीम बंद कर दी गई है! आपकी दूसरी स्ट्रीम अभी भी चल रही है।**")
1043
  else:
1044
  await callback_query.message.edit_text("❌ **यह स्ट्रीम पहले ही बंद हो चुकी है।**")
1045
 
@@ -1057,24 +974,6 @@ async def scheduled_stream_starter(client, message, delay, stream_config, s_id):
1057
  async def process_stream_start(client, message):
1058
  await handle_video(client, message)
1059
 
1060
- def download_url_video(url, user_id):
1061
- file_prefix = f"vid_{user_id}_{int(time.time())}"
1062
- ydl_opts = {
1063
- 'format': 'bestvideo+bestaudio/best',
1064
- 'merge_output_format': 'mp4',
1065
- 'outtmpl': f"{file_prefix}.%(ext)s",
1066
- 'quiet': True,
1067
- 'noplaylist': True,
1068
- 'overwrites': True
1069
- }
1070
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
1071
- info = ydl.extract_info(url, download=True)
1072
- filename = ydl.prepare_filename(info)
1073
- base, _ = os.path.splitext(filename)
1074
- if os.path.exists(f"{base}.mp4"):
1075
- return f"{base}.mp4"
1076
- return filename
1077
-
1078
  def get_direct_url(url):
1079
  ydl_opts = {'format': 'best', 'quiet': True, 'noplaylist': True}
1080
  try:
@@ -1086,8 +985,6 @@ def get_direct_url(url):
1086
 
1087
  async def handle_video(client, message, stream_config=None):
1088
  user_id = message.chat.id
1089
-
1090
- # अगर कॉन्फ़िग स्नैपशॉट (शेड्यूल से) आया है, तो उसका इस्तेमाल करें। नहीं तो करंट डेटा का।
1091
  config = stream_config if stream_config else user_data[user_id]
1092
 
1093
  user_data[user_id]['manual_stop'] = False
@@ -1096,43 +993,29 @@ async def handle_video(client, message, stream_config=None):
1096
  except:
1097
  msg = await message.reply("⏳ **Preparing Stream Environment...**")
1098
 
1099
- raw_file_paths = config.get('file_paths', [])
1100
- if raw_file_paths and isinstance(raw_file_paths[0], tuple):
1101
- raw_file_paths.sort(key=lambda x: x[0])
1102
- file_paths = [fp for msg_id, fp in raw_file_paths]
1103
- else:
1104
- file_paths = raw_file_paths
1105
-
1106
- file_path = file_paths[0] if file_paths else None # <--- CRASH FIX
1107
  video_url = config.get('video_url')
1108
  custom_audio = config.get('custom_audio_path')
1109
 
1110
- input_source = None
1111
  is_concat = False
1112
- playlist_path = None
1113
- vid_duration = 0
1114
 
1115
  if video_url:
1116
- await msg.edit_text("🔗 **Extracting direct stream link (YouTube/Facebook/Rumble etc.)...**")
1117
  input_source = await asyncio.to_thread(get_direct_url, video_url)
1118
  if not input_source:
1119
  return await msg.edit_text("❌ **Failed to extract link!**")
1120
- elif file_paths:
1121
- if len(file_paths) == 1:
1122
- input_source = file_paths[0]
1123
- vid_duration = get_video_duration(input_source)
1124
- else:
 
 
1125
  is_concat = True
1126
- playlist_path = f"playlist_{user_id}_{uuid.uuid4().hex[:6]}.txt"
1127
- with open(playlist_path, "w", encoding="utf-8") as f:
1128
- for fp in file_paths:
1129
- # [FIX] ऑनलाइन लिंक पर abspath न लगाएं ताकि URL खराब न हो
1130
- if str(fp).startswith("http://") or str(fp).startswith("https://"):
1131
- f.write(f"file '{fp}'\n")
1132
- else:
1133
- f.write(f"file '{os.path.abspath(fp)}'\n")
1134
- vid_duration += get_video_duration(fp)
1135
- input_source = playlist_path
1136
 
1137
  platform = config.get('platform', 'Custom')
1138
  loop_hours = config.get('loop_hours', 0)
@@ -1143,29 +1026,28 @@ async def handle_video(client, message, stream_config=None):
1143
  user_data[user_id]['total_streams'] += 1
1144
  user_data[user_id]['last_stream'] = get_ist_time()
1145
 
 
 
 
 
1146
  # -----------------------------------------------------
1147
- # REAL STREAM DURATION LOGIC (FIXED)
1148
  # -----------------------------------------------------
1149
  if loop_hours > 0:
1150
- actual_stream_seconds = loop_hours * 3600
 
 
 
1151
  total_stream_time = actual_stream_seconds
1152
  else:
1153
- # 1-Time Play में कोई फिक्स टाइमर न लगाएं, यह सारी वीडियो खत्म होने तक लगातार चलेगा
1154
- actual_stream_seconds = 0
1155
- total_stream_time = 0
1156
 
1157
  is_image_only = config.get('is_image_only', False)
1158
 
1159
  # --- FFMPEG Command Setup ---
1160
  command = ["ffmpeg", "-re"]
1161
 
1162
- if is_concat:
1163
- # [FIX] बिना डाउनलोड किए ऑनलाइन लिंक्स (HTTP/HTTPS) सीधे चलाने की परमिशन
1164
- command.extend(["-f", "concat", "-safe", "0", "-protocol_whitelist", "file,http,https,tcp,tls"])
1165
-
1166
- # [FIX] Prevent Buffer lag on servers (Prevents Poor Health)
1167
- command.extend(["-thread_queue_size", "1024"])
1168
-
1169
  if is_image_only:
1170
  # Image Only Streaming Logic (YouTube Standard 30 FPS)
1171
  command.extend(["-loop", "1", "-framerate", "30", "-i", input_source])
@@ -1178,28 +1060,39 @@ async def handle_video(client, message, stream_config=None):
1178
  command.extend(["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100"])
1179
  command.extend(["-map", "0:v", "-map", "1:a"])
1180
 
 
 
 
1181
  if orientation == 'portrait':
 
1182
  vf_filter = "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black"
1183
  else:
 
1184
  vf_filter = "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black"
1185
 
 
1186
  wm_text = config.get('watermark_text')
1187
  if wm_text:
1188
  safe_text = wm_text.replace("'", "\\'").replace(":", "\\:")
 
1189
  drawtext = f",drawtext=text='{safe_text}':fontcolor=white@0.4:fontsize=50:x=(w-tw)/2+((w-tw)/2.5)*sin(t/10):y=(h-th)/2+((h-th)/2.5)*cos(t/15)"
1190
  vf_filter += drawtext
1191
 
1192
  command.extend(["-vf", vf_filter])
 
1193
 
1194
- # [FIX] YouTube 6000k Strict CBR Bitrate with Ultrafast preset
1195
- command.extend(["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"])
 
1196
  command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
1197
- command.extend(["-b:v", "6000k", "-maxrate", "6000k", "-minrate", "6000k", "-bufsize", "12000k", "-nal-hrd", "cbr"])
 
1198
  command.extend(["-c:a", "aac", "-b:a", "128k"])
1199
 
1200
  else:
1201
- # Normal Video Logic
1202
  if loop_hours > 0: command.extend(["-stream_loop", "-1"])
 
1203
  command.extend(["-i", input_source])
1204
 
1205
  current_idx = 1; idx_aud = 0
@@ -1220,23 +1113,25 @@ async def handle_video(client, message, stream_config=None):
1220
  vf_filter = "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black"
1221
  command.extend(["-vf", vf_filter, "-map", "0:v"])
1222
 
1223
- command.extend(["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"])
 
1224
  command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
1225
  command.extend(["-b:v", "6000k", "-maxrate", "6000k", "-minrate", "6000k", "-bufsize", "12000k", "-nal-hrd", "cbr"])
1226
  else:
1227
- # --- [FIX] MERGE CRASH FIX: Force 1920x1080 so all merged videos match perfectly ---
1228
- vf_filter = "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black"
1229
-
1230
  wm_text = config.get('watermark_text')
 
1231
  if wm_text:
1232
  safe_text = wm_text.replace("'", "\\'").replace(":", "\\:")
 
1233
  timing_logic = "between(t\\,60\\,75)+between(t\\,180\\,195)+(gte(t\\,480)*lt(mod(t-480\\,300)\\,15))"
1234
- vf_filter += f",drawtext=text=' Telegram\\: {safe_text} ':fontcolor=white:fontsize=38:box=1:boxcolor=#2AABEE@0.9:boxborderw=15:x=40:y=h-th-40:enable='{timing_logic}'"
1235
-
1236
- command.extend(["-vf", vf_filter, "-map", "0:v"])
1237
 
1238
- # [FIX] YouTube 6000k Strict CBR Bitrate with Ultrafast preset
1239
- command.extend(["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"])
 
 
 
 
1240
  command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
1241
  command.extend(["-b:v", "6000k", "-maxrate", "6000k", "-minrate", "6000k", "-bufsize", "12000k", "-nal-hrd", "cbr"])
1242
 
@@ -1246,13 +1141,9 @@ async def handle_video(client, message, stream_config=None):
1246
  command.extend(["-map", "0:a?", "-c:a", "aac", "-b:a", "128k"])
1247
 
1248
  # Apply time limit for BOTH Image and Video
1249
-
1250
- # [FIX] वीडियो मर्जिंग (Concat) क्रैश को रोकने के लिए इसे हमेशा चालू रखें (1-Time के लिए भी)
1251
- if not is_image_only:
1252
- command.extend(["-fflags", "+genpts"])
1253
-
1254
  if loop_hours > 0:
1255
  seconds_str = str(int(actual_stream_seconds)) # असली रैंडम सेकंड्स
 
1256
  command.extend(["-t", seconds_str])
1257
 
1258
  command.extend(["-f", "flv", rtmp_url])
@@ -1277,9 +1168,9 @@ async def handle_video(client, message, stream_config=None):
1277
  'platform': platform
1278
  })
1279
 
1280
- asyncio.create_task(monitor_stream(client, message.chat.id, process_obj, file_paths, playlist_path, live_msg.id, loop_hours, platform, total_stream_time, image_path, custom_audio))
1281
 
1282
- async def monitor_stream(client, chat_id, process, stream_files, playlist_file, msg_id, loop_hours, platform, total_time, image_path, custom_audio):
1283
  start_time_ist = get_ist_time()
1284
  last_ui_update = time.time()
1285
  mode_text = f"🔁 {loop_hours} Hours Loop" if loop_hours > 0 else "▶️ 1-Time Play"
@@ -1287,27 +1178,24 @@ async def monitor_stream(client, chat_id, process, stream_files, playlist_file,
1287
  while process.poll() is None:
1288
  await asyncio.sleep(5)
1289
  now_time = time.time()
1290
- if now_time - last_ui_update > 60:
1291
  last_ui_update = now_time
1292
  elapsed = (get_ist_time() - start_time_ist).total_seconds()
1293
  rem_sec = total_time - elapsed
1294
 
1295
- if total_time > 0 and rem_sec > 0:
1296
  h = int(rem_sec // 3600)
1297
  m = int((rem_sec % 3600) // 60)
1298
  time_left_str = f"{h}h {m}m" if h > 0 else f"{m}m"
1299
- else:
1300
- time_left_str = "♾ Auto (जब तक सारे वीडियो पूरे न हों)"
1301
-
1302
- try:
1303
- await client.edit_message_text(
1304
- chat_id, msg_id,
1305
- f"🟢 **Live is RUNNING on {platform}!**\n"
1306
- f"⏱ **Loop:** `{mode_text}`\n"
1307
- f"⏳ **Time Left:** `{time_left_str}`\n\n"
1308
- f"🔹 Send /stop to end manually."
1309
- )
1310
- except: pass
1311
 
1312
  end_time_ist = get_ist_time()
1313
  duration = end_time_ist - start_time_ist
@@ -1315,16 +1203,11 @@ async def monitor_stream(client, chat_id, process, stream_files, playlist_file,
1315
  try: await client.delete_messages(chat_id, msg_id)
1316
  except: pass
1317
 
1318
- # Server Storage साफ़ करना (सिर्फ इसी स्ट्रीम की फाइल्स डिलीट करें, दूसरी स्ट्रीम की नहीं!)
1319
  try:
1320
- if playlist_file and os.path.exists(playlist_file):
1321
- os.remove(playlist_file)
1322
-
1323
- if stream_files:
1324
- for fp in stream_files:
1325
- if isinstance(fp, tuple): fp = fp[1]
1326
- if fp and os.path.exists(fp): os.remove(fp)
1327
-
1328
  if image_path and os.path.exists(image_path): os.remove(image_path)
1329
  if custom_audio and os.path.exists(custom_audio): os.remove(custom_audio)
1330
  except: pass
@@ -1351,4 +1234,4 @@ async def monitor_stream(client, chat_id, process, stream_files, playlist_file,
1351
  if __name__ == "__main__":
1352
  load_data() # बॉट स्टार्ट होते ही पुरानी सेटिंग्स और यूज़र्स वापस लोड करें
1353
  Thread(target=run_flask).start()
1354
- bot.run()h
 
21
  def run_flask():
22
  app.run(host="0.0.0.0", port=7860)
23
 
24
+ # --- Telegram Bot की डिटेल्स (Environment Variables से) ---
25
+ BOT_TOKEN = os.getenv("BOT_TOKEN")
26
+ API_ID = int(os.getenv("API_ID", "0"))
27
+ API_HASH = os.getenv("API_HASH")
28
 
29
  bot = Client("LiveBot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
30
 
31
  # --- USER SESSION (Private Channel Download के लिए) ---
32
+ USER_SESSION = os.getenv("USER_SESSION")
33
  user_app = Client("UserAcc", api_id=API_ID, api_hash=API_HASH, session_string=USER_SESSION)
34
 
35
  # --- ग्लोबल वेरिएबल्स ---
36
+ ADMIN_ID = 7700628753
37
  GLOBAL_PASSWORD = "jitu@123"
38
  PASSWORD_LIMIT = 999999 # डिफ़ॉल्ट लिमिट (Unlimted)
39
  PASSWORD_USED_BY = {} # जिन लोगों ने पासवर्ड इस्तेमाल किया है उनका डेटा
 
112
 
113
  def get_video_duration(file_path):
114
  try:
115
+ result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path],
116
+ stdout=subprocess.PIPE,
117
+ stderr=subprocess.STDOUT,
118
+ text=True
119
+ )
120
+ return float(result.stdout.strip())
 
 
 
121
  except:
122
  return 0
123
 
 
160
  'rtmp_url': None,
161
  'loop_hours': 0,
162
  'orientation': 'landscape',
163
+ 'custom_image_path': None,
164
+ 'custom_audio_path': None,
165
+ 'watermark_text': None,
166
+ 'video_url': None,
167
+ 'schedule_time': None,
168
  'processes':[],
169
+ 'scheduled_tasks': {},
170
  'stream_limit': GLOBAL_LIMIT,
171
+ 'video_files': [], # <--- NEW: Multi Video Playlist
172
  'manual_stop': False,
173
  'join_date': get_ist_time(),
174
  'last_online': get_ist_time(),
 
204
  def schedule_choice_keyboard():
205
  return InlineKeyboardMarkup([[InlineKeyboardButton("▶️ Start Now", callback_data="sch_now")],[InlineKeyboardButton("⏳ Schedule Time", callback_data="sch_later")]])
206
 
207
+ def more_video_keyboard():
208
  return InlineKeyboardMarkup([
209
+ [InlineKeyboardButton("➕ Add More Video", callback_data="vid_add")],
210
+ [InlineKeyboardButton("✅ Done (Start Live)", callback_data="vid_done")]
211
  ])
212
 
213
  def admin_keyboard():
 
268
  return await message.reply("🔐 **Session Expired! Please enter the new password:**")
269
 
270
  user_data[user_id]['step'] = 'PLATFORM'
 
271
  user_data[user_id]['custom_image_path'] = None
272
  user_data[user_id]['custom_audio_path'] = None
273
  user_data[user_id]['watermark_text'] = None
274
  user_data[user_id]['video_url'] = None
275
+ user_data[user_id]['video_files'] = [] # <--- NEW
 
276
  await message.reply("🔄 **New Stream Setup!**\n👇 **Select platform:**", reply_markup=platform_keyboard())
277
 
278
  @bot.on_message(filters.command("stop"))
 
280
  user_id = message.chat.id
281
  if user_id not in user_data: return
282
 
 
283
  active_procs = [p for p in user_data[user_id].get('processes', []) if (p['process'].poll() if isinstance(p, dict) else p.poll()) is None]
284
+
 
285
  if not active_procs:
286
+ return await message.reply("⚠️ **No active stream found.**\n(आपकी कोई स्ट्रीम अभी नहीं चल रही है)")
 
287
 
288
+ text = "🛑 **कौनसी स्ट्रीम बंद करनी है? चुनें:**\n\n"
 
 
 
 
 
 
 
 
 
289
  markup = []
290
+
291
  for idx, p in enumerate(active_procs, 1):
292
+ plat = p.get('platform', 'Unknown')
293
+ start_time_str = p['start_time'].strftime('%I:%M %p')
294
+ p_id = p.get('id', 'unknown')
295
+ text += f"**{idx}.** 🟢 {plat} | शुरू हुई: `{start_time_str}`\n"
296
+ markup.append([InlineKeyboardButton(f"🛑 Stop {plat} (Stream {idx})", callback_data=f"user_stop_{p_id}")])
297
+
 
 
298
  await message.reply(text, reply_markup=InlineKeyboardMarkup(markup))
299
 
300
  @bot.on_callback_query(filters.regex("^admin_"))
 
506
  text = "⬛️ **No Image Selected (Black Background).**\n\n📥 **अब कोई Video File भेजें या डायरेक्ट Link (YouTube/Insta/FB) भेजें:**"
507
 
508
  await callback_query.message.edit_text(text)
509
+
 
 
 
 
 
 
 
 
 
 
510
  @bot.on_callback_query(filters.regex("^aud_"))
511
  async def select_audio_choice(client, callback_query: CallbackQuery):
512
  user_id = callback_query.message.chat.id
 
528
  user_data[user_id]['step'] = 'AUDIO_CHOICE'
529
  await callback_query.message.edit_text("🎵 **YouTube के लिए ऑडियो जरूरी है।**\nक्या आप अपना खुद का Audio (MP3) लगाना चाहते हैं?", reply_markup=audio_choice_keyboard())
530
 
531
+ @bot.on_callback_query(filters.regex("^vid_"))
532
+ async def video_step_choice(client, callback_query: CallbackQuery):
533
+ user_id = callback_query.message.chat.id
534
+ data = callback_query.data
535
+ if data == "vid_add":
536
+ user_data[user_id]['step'] = 'VIDEO_OR_URL'
537
+ await callback_query.message.edit_text("📥 **अगला Video File भेजें:**\n(आप जितनी चाहें उतनी वीडियो भेज सकते हैं)")
538
+ elif data == "vid_done":
539
+ user_data[user_id]['step'] = 'WATERMARK_CHOICE'
540
+ if user_data[user_id].get('is_image_only'):
541
+ await callback_query.message.edit_text("✨ **क्या आप फोटो पर चलता हुआ (Moving) नाम/वाटरमार्क लगाना चाहते हैं?**", reply_markup=watermark_choice_keyboard())
542
+ else:
543
+ await callback_query.message.edit_text("✨ **क्या आप वीडियो पर Watermark (जैसे 'Class PDF Telegram...') लगाना चाहते हैं?**\n(यह हर 1 मिनट में दिखाई देगा)", reply_markup=watermark_choice_keyboard())
544
+
545
  @bot.on_callback_query(filters.regex("^sch_"))
546
  async def select_schedule_choice(client, callback_query: CallbackQuery):
547
  user_id = callback_query.message.chat.id
548
  if callback_query.data == "sch_now":
549
  user_data[user_id]['step'] = 'READY'
550
  await callback_query.message.delete()
551
+ await process_stream_start(client, callback_query.message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
552
  else:
553
  user_data[user_id]['step'] = 'AWAIT_DATETIME'
554
  update_schedule_dates()
555
  markup = []
556
  for st in GLOBAL_SCHEDULE_TIMES:
557
+ # Inline button format for specific times
558
  markup.append([InlineKeyboardButton(f"🗓 {st}", callback_data=f"set_schtime_{st}")])
559
 
560
+ # बटन के बिना मैन्युअल एंट्री का निर्देश
561
  text = "📅 **Schedule Time चुनें या लिखें!**\n\n"
562
  if GLOBAL_SCHEDULE_TIMES:
563
  text += "👇 **एडमिन द्वारा दिए गए समय में से चुनें:**\n"
 
797
  elif step == 'VIDEO_OR_URL':
798
  user_data[user_id]['is_image_only'] = False
799
 
800
+ # यूनीक नाम बनाना (ताकि दूसरी स्ट्रीम की वीडियो से मिक्स न हो)
801
+ file_count = len(user_data[user_id].get('video_files', [])) + 1
802
+ custom_filename = f"downloads/{user_id}_vid_{file_count}_{uuid.uuid4().hex[:6]}.mp4"
803
+
804
  if message.video or message.document:
805
+ msg = await message.reply(f"⏳ **Downloading Video {file_count}...**")
806
  start_time = time.time()
807
  last_update = [start_time]
808
+ file_path = await message.download(file_name=custom_filename, progress=progress_bar, progress_args=(msg, start_time, last_update))
809
 
810
+ if 'video_files' not in user_data[user_id]: user_data[user_id]['video_files'] = []
811
+ user_data[user_id]['video_files'].append(file_path)
 
 
 
 
 
 
 
 
 
 
812
 
813
+ await msg.delete()
814
+ await message.reply(f"✅ **Video {file_count} Saved!**\n\n🤔 **क्या आप और वीडियो जोड़ना चाहते हैं या Live चालू करें?**", reply_markup=more_video_keyboard())
815
 
816
  elif message.photo:
817
  msg = await message.reply("⏳ **Downloading Image...**")
818
+ custom_img_name = f"downloads/{user_id}_img_{uuid.uuid4().hex[:6]}.jpg"
819
+ file_path = await message.download(file_name=custom_img_name)
820
+ user_data[user_id]['video_files'] = [file_path]
 
821
  user_data[user_id]['is_image_only'] = True
822
  await msg.delete()
823
  user_data[user_id]['step'] = 'WATERMARK_CHOICE'
824
+ await message.reply("✨ **क्या आप फोटो पर चलता हुआ (Moving) नाम/वाटरमार्क लगाना चाहते हैं?**", reply_markup=watermark_choice_keyboard())
825
 
826
  elif message.text and "t.me/c/" in message.text:
827
  if not USER_SESSION:
828
+ return await message.reply("❌ **String Session सेट नहीं है!**")
829
+ msg = await message.reply(f"🔍 **प्राइवेट वीडियो ढूँढा जा रहा है...**")
830
  try:
831
  link_parts = message.text.strip().split('/')
832
  chat_id = int("-100" + link_parts[4])
833
  msg_id = int(link_parts[5])
834
+
835
+ if not user_app.is_connected:
836
+ await user_app.start()
837
 
838
  target_msg = None
839
  messages = await user_app.get_messages(chat_id, range(max(1, msg_id - 10), msg_id + 11))
 
842
  target_msg = m
843
  break
844
 
845
+ if not target_msg:
846
+ return await msg.edit_text("❌ **इस लिंक के आस-पास कोई Video नहीं मिला!**")
847
+
848
+ await msg.edit_text(f"⏳ **Private Video {file_count} Downloading...**")
849
  start_time = time.time()
850
  last_update = [start_time]
851
+ file_path = await user_app.download_media(target_msg, file_name=custom_filename, progress=progress_bar, progress_args=(msg, start_time, last_update))
852
 
853
+ if 'video_files' not in user_data[user_id]: user_data[user_id]['video_files'] = []
854
+ user_data[user_id]['video_files'].append(file_path)
 
 
 
 
 
 
855
 
856
+ await msg.delete()
857
+ await message.reply(f"✅ **Private Video {file_count} Saved!**\n\n🤔 **क्या आप और वीडियो जोड़ना चाहते हैं या Live चालू करें?**", reply_markup=more_video_keyboard())
858
+ except Exception as e:
859
+ return await msg.edit_text(f"❌ **Error:** {str(e)}")
860
 
 
 
 
 
861
  elif message.text and ("http://" in message.text or "https://" in message.text):
862
+ user_data[user_id]['video_url'] = message.text.strip()
863
+ user_data[user_id]['step'] = 'WATERMARK_CHOICE'
864
+ await message.reply("✨ **क्या आप वीडियो पर Watermark लगाना चाहते हैं?**", reply_markup=watermark_choice_keyboard())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
865
  else:
866
  return await message.reply("⚠️ **कृपया सही Video, Photo या Link भेजें!**")
867
 
 
899
  # --- Snapshot Configuration ---
900
  # (अगर यूज़र दूसरी स्ट्रीम बनायेगा तो पहली स्ट्रीम का डेटा डिलीट न हो)
901
  stream_config = {
902
+ 'video_files': user_data[user_id].get('video_files', []),
903
  'video_url': user_data[user_id].get('video_url'),
904
  'custom_audio_path': user_data[user_id].get('custom_audio_path'),
905
  'platform': user_data[user_id].get('platform', 'Custom'),
 
945
  @bot.on_callback_query(filters.regex("^user_stop_"))
946
  async def stop_running_callback(client, callback_query: CallbackQuery):
947
  user_id = callback_query.message.chat.id
948
+ p_id = callback_query.data.replace("user_stop_", "")
949
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
950
  stopped = False
 
 
951
  for p in user_data[user_id].get('processes', []):
952
+ if p.get('id') == p_id and p['process'].poll() is None:
953
+ user_data[user_id]['manual_stop'] = True
954
+ p['process'].terminate()
955
+ stopped = True
956
+ break
957
+
 
 
 
 
 
 
958
  if stopped:
959
+ await callback_query.message.edit_text("✅ **Running Stream को सफलतापूर्वक बंद कर दिया गया है!**")
960
  else:
961
  await callback_query.message.edit_text("❌ **यह स्ट्रीम पहले ही बंद हो चुकी है।**")
962
 
 
974
  async def process_stream_start(client, message):
975
  await handle_video(client, message)
976
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
977
  def get_direct_url(url):
978
  ydl_opts = {'format': 'best', 'quiet': True, 'noplaylist': True}
979
  try:
 
985
 
986
  async def handle_video(client, message, stream_config=None):
987
  user_id = message.chat.id
 
 
988
  config = stream_config if stream_config else user_data[user_id]
989
 
990
  user_data[user_id]['manual_stop'] = False
 
993
  except:
994
  msg = await message.reply("⏳ **Preparing Stream Environment...**")
995
 
996
+ video_files = config.get('video_files', [])
 
 
 
 
 
 
 
997
  video_url = config.get('video_url')
998
  custom_audio = config.get('custom_audio_path')
999
 
 
1000
  is_concat = False
1001
+ concat_file = None
1002
+ input_source = None
1003
 
1004
  if video_url:
1005
+ await msg.edit_text("🔗 **Extracting direct stream link...**")
1006
  input_source = await asyncio.to_thread(get_direct_url, video_url)
1007
  if not input_source:
1008
  return await msg.edit_text("❌ **Failed to extract link!**")
1009
+ elif video_files:
1010
+ if len(video_files) > 1:
1011
+ concat_file = f"concat_{user_id}_{uuid.uuid4().hex[:6]}.txt"
1012
+ with open(concat_file, 'w', encoding='utf-8') as f:
1013
+ for vf in video_files:
1014
+ f.write(f"file '{os.path.abspath(vf)}'\n")
1015
+ input_source = concat_file
1016
  is_concat = True
1017
+ else:
1018
+ input_source = video_files[0]
 
 
 
 
 
 
 
 
1019
 
1020
  platform = config.get('platform', 'Custom')
1021
  loop_hours = config.get('loop_hours', 0)
 
1026
  user_data[user_id]['total_streams'] += 1
1027
  user_data[user_id]['last_stream'] = get_ist_time()
1028
 
1029
+ import random # Random time जनरेट करने के लिए
1030
+
1031
+ vid_duration = sum(get_video_duration(f) for f in video_files) if video_files else 3600
1032
+
1033
  # -----------------------------------------------------
1034
+ # ANTI-BOT RANDOMIZER: हर बार समय को थोड़ा आगे-पीछे करना
1035
  # -----------------------------------------------------
1036
  if loop_hours > 0:
1037
+ base_sec = loop_hours * 3600
1038
+ # 10% समय रैंडमली कम या ज्यादा करें (जैसे 3 घंटे में +/- 18 मिनट, 30 मिनट में +/- 3 मिनट)
1039
+ random_offset = random.randint(int(-0.1 * base_sec), int(0.1 * base_sec))
1040
+ actual_stream_seconds = base_sec + random_offset
1041
  total_stream_time = actual_stream_seconds
1042
  else:
1043
+ total_stream_time = vid_duration
1044
+ actual_stream_seconds = vid_duration
 
1045
 
1046
  is_image_only = config.get('is_image_only', False)
1047
 
1048
  # --- FFMPEG Command Setup ---
1049
  command = ["ffmpeg", "-re"]
1050
 
 
 
 
 
 
 
 
1051
  if is_image_only:
1052
  # Image Only Streaming Logic (YouTube Standard 30 FPS)
1053
  command.extend(["-loop", "1", "-framerate", "30", "-i", input_source])
 
1060
  command.extend(["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100"])
1061
  command.extend(["-map", "0:v", "-map", "1:a"])
1062
 
1063
+ # -----------------------------------------------------
1064
+ # NEW: Aspect Ratio Fix for Image (Portrait vs Landscape)
1065
+ # -----------------------------------------------------
1066
  if orientation == 'portrait':
1067
+ # Makes 16:9 photo into 9:16 (Adds black bars on top/bottom)
1068
  vf_filter = "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black"
1069
  else:
1070
+ # Ensures normal photos fit 16:9 screen
1071
  vf_filter = "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black"
1072
 
1073
+ # --- NEW: SLOW SMOOTH MOVING WATERMARK ---
1074
  wm_text = config.get('watermark_text')
1075
  if wm_text:
1076
  safe_text = wm_text.replace("'", "\\'").replace(":", "\\:")
1077
+ # sin(t/10) और cos(t/15) का मतलब है कि यह बहुत धीरे-धीरे (Slowly) पूरी स्क्रीन पर गोल घूमेगा
1078
  drawtext = f",drawtext=text='{safe_text}':fontcolor=white@0.4:fontsize=50:x=(w-tw)/2+((w-tw)/2.5)*sin(t/10):y=(h-th)/2+((h-th)/2.5)*cos(t/15)"
1079
  vf_filter += drawtext
1080
 
1081
  command.extend(["-vf", vf_filter])
1082
+ # -----------------------------------------------------
1083
 
1084
+ # Encode with strict YouTube standards (30 FPS, 2-sec Keyframe, CBR)
1085
+ command.extend(["-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
1086
+ # YouTube Keyframe Fix: 30fps के हिसाब से हर 2 सेकंड में कीफ्रेम (-g 60)
1087
  command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
1088
+ # YouTube Bitrate Fix: Strict CBR (Constant Bitrate) with Dummy Padding
1089
+ command.extend(["-b:v", "4000k", "-maxrate", "4000k", "-minrate", "4000k", "-bufsize", "8000k", "-nal-hrd", "cbr"])
1090
  command.extend(["-c:a", "aac", "-b:a", "128k"])
1091
 
1092
  else:
1093
+ # Normal & Playlist Video Logic
1094
  if loop_hours > 0: command.extend(["-stream_loop", "-1"])
1095
+ if is_concat: command.extend(["-f", "concat", "-safe", "0"])
1096
  command.extend(["-i", input_source])
1097
 
1098
  current_idx = 1; idx_aud = 0
 
1113
  vf_filter = "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black"
1114
  command.extend(["-vf", vf_filter, "-map", "0:v"])
1115
 
1116
+ # YouTube Strict Bitrate & Keyframe (GOP) Fix for Portrait Video
1117
+ command.extend(["-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
1118
  command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
1119
  command.extend(["-b:v", "6000k", "-maxrate", "6000k", "-minrate", "6000k", "-bufsize", "12000k", "-nal-hrd", "cbr"])
1120
  else:
1121
+ # YouTube Strict Bitrate & Keyframe (GOP) Fix for Landscape Video
 
 
1122
  wm_text = config.get('watermark_text')
1123
+
1124
  if wm_text:
1125
  safe_text = wm_text.replace("'", "\\'").replace(":", "\\:")
1126
+ # Custom Timing Logic: 1st min, 3rd min, then every 5 mins (each for 15 sec)
1127
  timing_logic = "between(t\\,60\\,75)+between(t\\,180\\,195)+(gte(t\\,480)*lt(mod(t-480\\,300)\\,15))"
 
 
 
1128
 
1129
+ vf_filter = f"drawtext=text=' Telegram\\: {safe_text} ':fontcolor=white:fontsize=38:box=1:boxcolor=#2AABEE@0.9:boxborderw=15:x=40:y=h-th-40:enable='{timing_logic}'"
1130
+ command.extend(["-vf", vf_filter, "-map", "0:v"])
1131
+ else:
1132
+ command.extend(["-map", "0:v"])
1133
+
1134
+ command.extend(["-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
1135
  command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
1136
  command.extend(["-b:v", "6000k", "-maxrate", "6000k", "-minrate", "6000k", "-bufsize", "12000k", "-nal-hrd", "cbr"])
1137
 
 
1141
  command.extend(["-map", "0:a?", "-c:a", "aac", "-b:a", "128k"])
1142
 
1143
  # Apply time limit for BOTH Image and Video
 
 
 
 
 
1144
  if loop_hours > 0:
1145
  seconds_str = str(int(actual_stream_seconds)) # असली रैंडम सेकंड्स
1146
+ if not is_image_only: command.extend(["-fflags", "+genpts"])
1147
  command.extend(["-t", seconds_str])
1148
 
1149
  command.extend(["-f", "flv", rtmp_url])
 
1168
  'platform': platform
1169
  })
1170
 
1171
+ asyncio.create_task(monitor_stream(client, message.chat.id, process_obj, video_files, concat_file, live_msg.id, loop_hours, platform, total_stream_time, image_path, custom_audio))
1172
 
1173
+ async def monitor_stream(client, chat_id, process, video_files, concat_file, msg_id, loop_hours, platform, total_time, image_path, custom_audio):
1174
  start_time_ist = get_ist_time()
1175
  last_ui_update = time.time()
1176
  mode_text = f"🔁 {loop_hours} Hours Loop" if loop_hours > 0 else "▶️ 1-Time Play"
 
1178
  while process.poll() is None:
1179
  await asyncio.sleep(5)
1180
  now_time = time.time()
1181
+ if total_time > 0 and (now_time - last_ui_update > 60):
1182
  last_ui_update = now_time
1183
  elapsed = (get_ist_time() - start_time_ist).total_seconds()
1184
  rem_sec = total_time - elapsed
1185
 
1186
+ if rem_sec > 0:
1187
  h = int(rem_sec // 3600)
1188
  m = int((rem_sec % 3600) // 60)
1189
  time_left_str = f"{h}h {m}m" if h > 0 else f"{m}m"
1190
+ try:
1191
+ await client.edit_message_text(
1192
+ chat_id, msg_id,
1193
+ f"🟢 **Live is RUNNING on {platform}!**\n"
1194
+ f"⏱ **Loop:** `{mode_text}`\n"
1195
+ f"⏳ **Time Left:** `{time_left_str}`\n\n"
1196
+ f"🔹 Send /stop to end manually."
1197
+ )
1198
+ except: pass
 
 
 
1199
 
1200
  end_time_ist = get_ist_time()
1201
  duration = end_time_ist - start_time_ist
 
1203
  try: await client.delete_messages(chat_id, msg_id)
1204
  except: pass
1205
 
1206
+ # Server Storage साफ़ करना (Delete file to save memory)
1207
  try:
1208
+ for vf in video_files:
1209
+ if os.path.exists(vf): os.remove(vf)
1210
+ if concat_file and os.path.exists(concat_file): os.remove(concat_file)
 
 
 
 
 
1211
  if image_path and os.path.exists(image_path): os.remove(image_path)
1212
  if custom_audio and os.path.exists(custom_audio): os.remove(custom_audio)
1213
  except: pass
 
1234
  if __name__ == "__main__":
1235
  load_data() # बॉट स्टार्ट होते ही पुरानी सेटिंग्स और यूज़र्स वापस लोड करें
1236
  Thread(target=run_flask).start()
1237
+ bot.run()