Opera8 commited on
Commit
69a88d8
·
verified ·
1 Parent(s): c3ae020

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +45 -21
main.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import threading
3
  import random
4
  import aiohttp
@@ -13,7 +14,7 @@ from rubpy.bot import BotClient, filters
13
  # ایمپورت‌های جدید برای هوش مصنوعی و کار با فایل صوتی
14
  from huggingface_hub import AsyncInferenceClient
15
  from PIL import Image
16
- from pydub import AudioSegment # ایمپورت اضافه شده برای ترکیب پادکست
17
 
18
  # --- تنظیمات وب سرور ---
19
  app = Flask(__name__)
@@ -61,30 +62,25 @@ MAIN_KEYPAD_DICT = {
61
  }
62
 
63
 
64
- # --- تابع ارسال منحصراً برای کیبورد پایین صفحه ---
65
  async def send_with_keyboard(client, chat_id, text, use_keyboard=True):
66
- if not use_keyboard:
67
- msg = await client.send_message(chat_id, text)
68
- return msg
69
-
70
  try:
 
 
 
71
  payload = {
72
  "chat_id": chat_id,
73
  "text": text,
74
  "chat_keypad_type": "New",
75
  "chat_keypad": MAIN_KEYPAD_DICT
76
  }
77
- msg = await client._make_request("sendMessage", payload)
78
- return msg
79
  except Exception:
80
  try:
81
- msg = await client.send_message(chat_id, text, chat_keypad=MAIN_KEYPAD_DICT, chat_keypad_type="New")
82
- return msg
83
  except Exception:
84
- pass
85
-
86
- msg = await client.send_message(chat_id, text)
87
- return msg
88
 
89
 
90
  # --- 🚨 تابع هوشمند دانلود فایل 🚨 ---
@@ -242,6 +238,10 @@ SPEAKERS = {
242
 
243
  user_states = {}
244
 
 
 
 
 
245
 
246
  # --- ۱. پردازش چت متنی و چندرسانه‌ای ---
247
  async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
@@ -650,13 +650,42 @@ else:
650
  @bot.on_update(filters.private)
651
  async def main_handler(client, update):
652
  try:
653
- user_text = getattr(update, "text", "") or getattr(getattr(update, "message", None), "text", "") or getattr(getattr(update, "new_message", None), "text", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654
  user_text_str = str(user_text).strip() if user_text else ""
655
 
656
  # تشخیص فایل
657
  is_file = False
658
  file_name = "unknown_file.jpg"
659
- msg_obj = getattr(update, "message", None) or getattr(update, "new_message", None)
660
 
661
  if msg_obj:
662
  for attr in ['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
@@ -675,9 +704,6 @@ else:
675
  if isinstance(file_attr, dict) and 'file_name' in file_attr: file_name = file_attr['file_name']
676
  break
677
 
678
- chat_id = getattr(update, "chat_id", None) or getattr(update, "author_guid", None) or getattr(update, "object_guid", None)
679
- if not chat_id: return
680
-
681
  if chat_id not in user_states:
682
  user_states[chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None}
683
 
@@ -686,7 +712,6 @@ else:
686
  await send_with_keyboard(client, chat_id, "سلام! به ربات هوشمند آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
687
  return
688
 
689
- # اصلاح شرط‌های if منطبق با متن دکمه‌های جدید
690
  if user_text_str in ["/chat", "💬 چت", "چت با هوش مصنوعی 🤖"]:
691
  user_states[chat_id] = {"mode": "chat", "text": "", "history":[]}
692
  await send_with_keyboard(client, chat_id, "💬 شما وارد بخش **چت با هوش مصنوعی** شدید.\n\nهر سوالی دارید بفرستید تا جواب بدم:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
@@ -772,7 +797,6 @@ else:
772
  await send_with_keyboard(client, chat_id, "❌ شماره نامعتبر است! لطفاً فقط یک عدد بین 1 تا 30 بفرستید.", False)
773
  return
774
 
775
- # --- بخش مسیریابی برای قابلیت جدید (پادکست) ---
776
  elif current_mode == "podcast_waiting_for_topic":
777
  if user_text_str:
778
  asyncio.create_task(process_podcast(client, chat_id, user_text_str))
 
1
  import os
2
+ import time
3
  import threading
4
  import random
5
  import aiohttp
 
14
  # ایمپورت‌های جدید برای هوش مصنوعی و کار با فایل صوتی
15
  from huggingface_hub import AsyncInferenceClient
16
  from PIL import Image
17
+ from pydub import AudioSegment
18
 
19
  # --- تنظیمات وب سرور ---
20
  app = Flask(__name__)
 
62
  }
63
 
64
 
65
+ # --- تابع ارسال منحصراً برای کیبورد پایین صفحه (اصلاح شده برای جلوگیری از اسپم) ---
66
  async def send_with_keyboard(client, chat_id, text, use_keyboard=True):
 
 
 
 
67
  try:
68
+ if not use_keyboard:
69
+ return await client.send_message(chat_id, text)
70
+
71
  payload = {
72
  "chat_id": chat_id,
73
  "text": text,
74
  "chat_keypad_type": "New",
75
  "chat_keypad": MAIN_KEYPAD_DICT
76
  }
77
+ return await client._make_request("sendMessage", payload)
 
78
  except Exception:
79
  try:
80
+ # اگر حالت کیبورد دار در سطح API خطا داد، فقط یکبار به صورت ساده پیام ارسال شود
81
+ return await client.send_message(chat_id, text)
82
  except Exception:
83
+ return None
 
 
 
84
 
85
 
86
  # --- 🚨 تابع هوشمند دانلود فایل 🚨 ---
 
238
 
239
  user_states = {}
240
 
241
+ # --- متغیرهای کَش برای جلوگیری از پیام تکراری و اسپم شدن ---
242
+ processed_message_ids = set()
243
+ user_last_request_time = {}
244
+
245
 
246
  # --- ۱. پردازش چت متنی و چندرسانه‌ای ---
247
  async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
 
650
  @bot.on_update(filters.private)
651
  async def main_handler(client, update):
652
  try:
653
+ current_time = time.time()
654
+
655
+ # --- 🛡 سیستم ضد اسپم و حذف پیام‌های تکراری 🛡 ---
656
+ msg_obj = getattr(update, "message", None) or getattr(update, "new_message", None)
657
+ msg_id = getattr(update, "message_id", None)
658
+ if not msg_id and msg_obj:
659
+ if isinstance(msg_obj, dict):
660
+ msg_id = msg_obj.get("message_id")
661
+ else:
662
+ msg_id = getattr(msg_obj, "message_id", None)
663
+
664
+ # جلوگیری از پردازش یک آیدی پیام برای دفعات متعدد
665
+ if msg_id:
666
+ if msg_id in processed_message_ids:
667
+ return
668
+ processed_message_ids.add(msg_id)
669
+ # پاکسازی کش برای جلوگیری از پر شدن رم
670
+ if len(processed_message_ids) > 5000:
671
+ processed_message_ids.clear()
672
+
673
+ chat_id = getattr(update, "chat_id", None) or getattr(update, "author_guid", None) or getattr(update, "object_guid", None)
674
+ if not chat_id: return
675
+
676
+ # سیستم Rate Limit برای کاربران (جلوگیری از پاسخ به پیام‌های جمع شده در بک‌لاگ ربات)
677
+ last_req_time = user_last_request_time.get(chat_id, 0)
678
+ if current_time - last_req_time < 1.0: # اگر کاربر در کمتر از ۱ ثانیه پیام جدید داده، آن را نادیده بگیر
679
+ return
680
+ user_last_request_time[chat_id] = current_time
681
+ # ----------------------------------------------------
682
+
683
+ user_text = getattr(update, "text", "") or getattr(msg_obj, "text", "")
684
  user_text_str = str(user_text).strip() if user_text else ""
685
 
686
  # تشخیص فایل
687
  is_file = False
688
  file_name = "unknown_file.jpg"
 
689
 
690
  if msg_obj:
691
  for attr in ['file', 'file_inline', 'photo', 'voice', 'audio', 'document', 'video']:
 
704
  if isinstance(file_attr, dict) and 'file_name' in file_attr: file_name = file_attr['file_name']
705
  break
706
 
 
 
 
707
  if chat_id not in user_states:
708
  user_states[chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None}
709
 
 
712
  await send_with_keyboard(client, chat_id, "سلام! به ربات هوشمند آلفا خوش آمدید 🤖\n\nلطفاً برای شروع، از کیبورد پایین یکی از بخش‌ها را انتخاب کنید:", True)
713
  return
714
 
 
715
  if user_text_str in ["/chat", "💬 چت", "چت با هوش مصنوعی 🤖"]:
716
  user_states[chat_id] = {"mode": "chat", "text": "", "history":[]}
717
  await send_with_keyboard(client, chat_id, "💬 شما وارد بخش **چت با هوش مصنوعی** شدید.\n\nهر سوالی دارید بفرستید تا جواب بدم:\n(برای خروج دکمه «برگشت♻️» را بزنید)", True)
 
797
  await send_with_keyboard(client, chat_id, "❌ شماره نامعتبر است! لطفاً فقط یک عدد بین 1 تا 30 بفرستید.", False)
798
  return
799
 
 
800
  elif current_mode == "podcast_waiting_for_topic":
801
  if user_text_str:
802
  asyncio.create_task(process_podcast(client, chat_id, user_text_str))