Opera8 commited on
Commit
a432394
·
verified ·
1 Parent(s): 7302581

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +52 -70
main.py CHANGED
@@ -698,134 +698,116 @@ HF_TOKENS_STR = os.environ.get("HF_TOKENS", "")
698
  HF_TOKENS =[k.strip() for k in HF_TOKENS_STR.split(",") if k.strip()]
699
 
700
  # ==============================================================================
701
- # 🟢 پارت 11: آپلودر فوق‌سریع و مستقیم (نسخه صنعتی چندرشته‌ای - 15 ورکر همزمان)
702
  # ==============================================================================
703
  import asyncio
704
  import os
705
  import aiohttp
 
706
 
707
- # 🟢 سیستم توزیع بار (Load Balancer): اجازه آپلود همزمان به 15 کاربر (به جای 2 کاربر)
708
- # این همان اضافه کردن ورکرهایی است که درخواست دادید!
709
  _upload_lock = None
710
  def get_upload_lock():
711
  global _upload_lock
712
  if _upload_lock is None:
713
- _upload_lock = asyncio.Semaphore(15) # 🚀 ارتقا به 15 ورکـر همزمان برای آپلود سریع
714
  return _upload_lock
715
 
716
  async def helper_upload_file(client, chat_id, file_name, file_type="Image", caption=""):
717
  abs_path = os.path.abspath(file_name)
 
 
 
718
  error_logs = []
 
719
 
 
720
  api_file_type = "Image" if file_type in ["photo", "Image", "image"] else "Voice" if file_type in ["voice", "Voice", "audio"] else file_type
721
-
722
  if api_file_type == "Voice" and not abs_path.lower().endswith('.ogg'):
723
  api_file_type = "Music"
724
  if api_file_type == "File" and abs_path.lower().endswith('.mp3'):
725
  api_file_type = "Music"
726
 
727
- bot_token = os.environ.get("RUBIKA_AUTH", "").strip()
728
-
729
- # 🟢 ورود به تونل پرسرعت آپلود (همزمان 15 نفر بدون تداخل عبور می‌کنند)
730
  async with get_upload_lock():
731
-
732
- # 🚀 فاز اصلی: استفاده 100٪ از API خام و پرسرعت روبیکا (بدون استفاده از کدهای کند rubpy)
733
- for attempt in range(8): # 8 بار تلاش برق‌آسا
734
  try:
735
- url_request = f"https://botapi.rubika.ir/v3/{bot_token}/requestSendFile"
736
- url_send = f"https://botapi.rubika.ir/v3/{bot_token}/sendFile"
737
-
738
- # تایم‌اوت‌های کوتاه برای جلوگیری از گیر کردن ربات روی یک فایل خراب
739
- timeout_cfg = aiohttp.ClientTimeout(total=45)
740
  async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
741
- # 1. گرفتن لینک پرسرعت آپلود از روبیکا
742
- async with session.post(url_request, json={"type": api_file_type}) as resp:
743
- if resp.status != 200:
744
- await asyncio.sleep(1)
745
- continue
746
-
 
747
  req_data = await resp.json()
748
 
749
  if req_data.get("status") == "TOO_REQUESTS":
750
- error_logs.append("TOO_REQUESTS_REQ")
751
- await asyncio.sleep(3) # 👈 خواب‌های 15 ثانیه‌ای را به 3 ثانیه کاهش دادیم
752
  continue
753
 
754
  if req_data.get("status") == "OK":
755
  upload_url = req_data.get("data", {}).get("upload_url")
756
  if not upload_url: continue
757
 
758
- # 2. شلیک مستقیم فایل به سرور ابری روبیکا
759
  with open(abs_path, "rb") as f:
760
  form = aiohttp.FormData()
761
  form.add_field('file', f, filename=os.path.basename(abs_path))
 
762
  async with session.post(upload_url, data=form) as up_resp:
763
- if up_resp.status != 200:
764
- await asyncio.sleep(1)
765
- continue
766
-
767
  up_data = await up_resp.json()
768
 
769
  if up_data.get("status") == "TOO_REQUESTS":
770
- await asyncio.sleep(3)
771
  continue
772
 
773
  final_file_id = None
774
-
775
- if up_data.get("status") == "INVALID_INPUT" and "format" in str(up_data).lower():
776
- api_file_type = "File"
777
- await asyncio.sleep(1)
778
- continue
779
-
780
  if up_data.get("status") in ["OK", "OK_DET"]:
781
- if "data" in up_data and isinstance(up_data["data"], dict):
782
- final_file_id = up_data["data"].get("file_id") or up_data["data"].get("id")
783
- elif "file_id" in up_data:
784
- final_file_id = up_data.get("file_id")
785
 
786
- # 3. ارسال فایل به پی‌وی کاربر در کسری از ثانیه
787
  if final_file_id:
788
  send_payload = {
789
  "chat_id": str(chat_id),
790
  "file_id": str(final_file_id),
791
  "text": caption,
792
  "chat_keypad_type": "New",
793
- "chat_keypad": MAIN_KEYPAD_DICT
794
  }
795
- async with session.post(url_send, json=send_payload) as send_resp:
 
 
 
 
796
  s_data = await send_resp.json()
797
- if s_data.get("status") == "TOO_REQUESTS":
798
- await asyncio.sleep(3)
799
- continue
800
  if s_data.get("status") == "OK":
801
  return True
 
 
 
802
  except Exception as e:
803
- error_logs.append(f"Fast HTTP Error: {str(e)[:30]}")
804
- await asyncio.sleep(1.5)
805
-
806
- # --- فاز دوم (سنگر آخر): اگر API خام مسدود بود، فایل را از طریق روب‌پای می‌فرستیم ---
807
- for attempt in range(3):
808
- try:
809
- if api_file_type == "Image" and hasattr(client, "send_photo"):
810
- try:
811
- await client.send_photo(chat_id, photo=abs_path, caption=caption)
812
- return True
813
- except TypeError:
814
- await client.send_photo(chat_id, abs_path, caption=caption)
815
- return True
816
- else:
817
- if hasattr(client, "send_document"):
818
- try:
819
- await client.send_document(chat_id, document=abs_path, caption=caption)
820
- return True
821
- except TypeError:
822
- await client.send_document(chat_id, abs_path, caption=caption)
823
- return True
824
- except Exception as e:
825
- error_logs.append(f"Fallback Error: {str(e)[:30]}")
826
  await asyncio.sleep(2)
827
 
828
- return "\n".join(error_logs[-5:])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829
 
830
  # ==============================================================================
831
  # 🟢 پارت 12: توابع تغییر صدا و لیست گویندگان
 
698
  HF_TOKENS =[k.strip() for k in HF_TOKENS_STR.split(",") if k.strip()]
699
 
700
  # ==============================================================================
701
+ # 🟢 پارت 11: آپلودر فوق‌سریع و مستقیم (نسخه مقاوم در برابر ترافیک سنگین)
702
  # ==============================================================================
703
  import asyncio
704
  import os
705
  import aiohttp
706
+ import uuid
707
 
708
+ # 🟢 مدیریت صف آپلود: اجازه پردازش همزمان ۱۵ فایل
 
709
  _upload_lock = None
710
  def get_upload_lock():
711
  global _upload_lock
712
  if _upload_lock is None:
713
+ _upload_lock = asyncio.Semaphore(15)
714
  return _upload_lock
715
 
716
  async def helper_upload_file(client, chat_id, file_name, file_type="Image", caption=""):
717
  abs_path = os.path.abspath(file_name)
718
+ if not os.path.exists(abs_path):
719
+ return "File Not Found"
720
+
721
  error_logs = []
722
+ bot_token = os.environ.get("RUBIKA_AUTH", "").strip()
723
 
724
+ # تعیین نوع دقیق فایل برای سرور روبیکا
725
  api_file_type = "Image" if file_type in ["photo", "Image", "image"] else "Voice" if file_type in ["voice", "Voice", "audio"] else file_type
 
726
  if api_file_type == "Voice" and not abs_path.lower().endswith('.ogg'):
727
  api_file_type = "Music"
728
  if api_file_type == "File" and abs_path.lower().endswith('.mp3'):
729
  api_file_type = "Music"
730
 
 
 
 
731
  async with get_upload_lock():
732
+ # 🚀 تلاش برای آپلود مستقیم (Bypass Rubpy Latency)
733
+ for attempt in range(10):
 
734
  try:
735
+ # تنظیم تایم‌آوت بالا برای فایل‌های حجیم در ترافیک سنگین
736
+ timeout_cfg = aiohttp.ClientTimeout(total=300, connect=30)
 
 
 
737
  async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
738
+
739
+ # مرحله ۱: درخواست لینک آپلود
740
+ async with session.post(
741
+ f"https://botapi.rubika.ir/v3/{bot_token}/requestSendFile",
742
+ json={"type": api_file_type},
743
+ timeout=30
744
+ ) as resp:
745
  req_data = await resp.json()
746
 
747
  if req_data.get("status") == "TOO_REQUESTS":
748
+ await asyncio.sleep(5)
 
749
  continue
750
 
751
  if req_data.get("status") == "OK":
752
  upload_url = req_data.get("data", {}).get("upload_url")
753
  if not upload_url: continue
754
 
755
+ # مرحله ۲: آپلود فیزیکی فایل با بافرینگ مناسب
756
  with open(abs_path, "rb") as f:
757
  form = aiohttp.FormData()
758
  form.add_field('file', f, filename=os.path.basename(abs_path))
759
+
760
  async with session.post(upload_url, data=form) as up_resp:
 
 
 
 
761
  up_data = await up_resp.json()
762
 
763
  if up_data.get("status") == "TOO_REQUESTS":
764
+ await asyncio.sleep(5)
765
  continue
766
 
767
  final_file_id = None
 
 
 
 
 
 
768
  if up_data.get("status") in ["OK", "OK_DET"]:
769
+ data_part = up_data.get("data", {})
770
+ final_file_id = data_part.get("file_id") or data_part.get("id") or up_data.get("file_id")
 
 
771
 
772
+ # مرحله ۳: نهایی‌سازی و ارسال پیام به کاربر
773
  if final_file_id:
774
  send_payload = {
775
  "chat_id": str(chat_id),
776
  "file_id": str(final_file_id),
777
  "text": caption,
778
  "chat_keypad_type": "New",
779
+ "chat_keypad": MAIN_KEYPAD_DICT # از متغیر سراسری استفاده می‌کند
780
  }
781
+ async with session.post(
782
+ f"https://botapi.rubika.ir/v3/{bot_token}/sendFile",
783
+ json=send_payload,
784
+ timeout=30
785
+ ) as send_resp:
786
  s_data = await send_resp.json()
 
 
 
787
  if s_data.get("status") == "OK":
788
  return True
789
+ elif s_data.get("status") == "TOO_REQUESTS":
790
+ await asyncio.sleep(5)
791
+ continue
792
  except Exception as e:
793
+ error_logs.append(f"Attempt {attempt+1}: {str(e)[:40]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
794
  await asyncio.sleep(2)
795
 
796
+ # 🛡️ سیستم پشتیبان (Fallback): اگر آپلود مستقیم شکست خورد، از متد خود کتابخانه استفاده کن
797
+ try:
798
+ if api_file_type == "Image":
799
+ await client.send_photo(chat_id, photo=abs_path, caption=caption)
800
+ return True
801
+ elif api_file_type in ["Music", "Voice"]:
802
+ await client.send_music(chat_id, abs_path, caption=caption)
803
+ return True
804
+ else:
805
+ await client.send_file(chat_id, abs_path)
806
+ return True
807
+ except Exception as e:
808
+ error_logs.append(f"Fallback Fail: {str(e)[:40]}")
809
+
810
+ return "❌ خطا در آپلود پس از چندین تلاش:\n" + "\n".join(error_logs[-3:])
811
 
812
  # ==============================================================================
813
  # 🟢 پارت 12: توابع تغییر صدا و لیست گویندگان