Opera8 commited on
Commit
45fbbc7
·
verified ·
1 Parent(s): 28b3bcb

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +49 -44
main.py CHANGED
@@ -28,25 +28,22 @@ ADMIN_CODE = "3011"
28
  BOT_GUID = None
29
 
30
  # =======================================================
31
- # 🔥 سیستم کنترل سرعت و ضد رگبار (Burst Controller) 🔥
32
  # =======================================================
33
- global_burst_count = 0
34
- global_burst_time = time.time()
35
- burst_lock = threading.Lock()
36
-
37
- def is_backlog_burst():
38
- global global_burst_count, global_burst_time
39
- with burst_lock:
40
- now = time.time()
41
- if now - global_burst_time > 1.0:
42
- global_burst_time = now
43
- global_burst_count = 1
44
- return False
45
- else:
46
- global_burst_count += 1
47
- if global_burst_count > 5:
48
- return True
49
- return False
50
 
51
  # --- سیستم دیتابیس حساب کاربری متصل به دیتاست هاگینگ فیس ---
52
  DB_FILE = "users_db.json"
@@ -97,28 +94,40 @@ def load_db():
97
  pass
98
  return {}
99
 
100
- def _upload_db_background():
101
- if HF_TOKEN_DB:
102
- api = HfApi(token=HF_TOKEN_DB)
103
- try:
104
- api.upload_file(
105
- path_or_fileobj=DB_FILE,
106
- path_in_repo=DB_FILE,
107
- repo_id=DATASET_REPO,
108
- repo_type="dataset"
109
- )
110
- except Exception as e:
111
- print("❌ خطا در آپلود دیتابیس به هاگینگ فیس:", str(e)[:100])
112
 
113
  def save_db(db_data):
 
114
  with db_lock:
115
  try:
116
  with open(DB_FILE, "w", encoding="utf-8") as f:
117
  json.dump(db_data, f, ensure_ascii=False, indent=4)
118
- threading.Thread(target=_upload_db_background, daemon=True).start()
119
  except Exception as e:
120
  print("خطا در ذخیره دیتابیس:", e)
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  user_credits_db = load_db()
123
 
124
  def get_or_create_referral_code(chat_id):
@@ -644,7 +653,6 @@ SPEAKERS = {
644
 
645
  user_states = {}
646
  processed_message_ids = set()
647
- user_last_request_time = {}
648
 
649
 
650
  async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
@@ -1572,9 +1580,6 @@ else:
1572
  async def main_handler(client, update):
1573
  global BOT_GUID
1574
 
1575
- if is_backlog_burst():
1576
- return
1577
-
1578
  try:
1579
  if not BOT_GUID:
1580
  try:
@@ -1605,13 +1610,6 @@ else:
1605
  if unique_msg_key in processed_message_ids: return
1606
  processed_message_ids.add(unique_msg_key)
1607
  if len(processed_message_ids) > 5000: processed_message_ids.clear()
1608
-
1609
- current_time = time.time()
1610
-
1611
- last_req_time = user_last_request_time.get(chat_id, 0)
1612
- if current_time - last_req_time < 1.0:
1613
- return
1614
- user_last_request_time[chat_id] = current_time
1615
 
1616
  user_text = getattr(update, "text", "") or getattr(msg_obj, "text", "")
1617
  user_text_str = str(user_text).strip() if user_text else ""
@@ -1619,6 +1617,10 @@ else:
1619
 
1620
  str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
1621
 
 
 
 
 
1622
  if str_chat_id not in user_states:
1623
  user_states[str_chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None}
1624
 
@@ -2220,7 +2222,10 @@ if __name__ == "__main__":
2220
 
2221
  if bot_token:
2222
  loop = asyncio.get_event_loop()
2223
- loop.set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=16))
 
 
 
2224
 
2225
- print("ربات آلفا پرو با سیستم اشتراک نامحدود + سپر امنیتی + دانلود پیشرفته فایل + 16 Worker پس‌زمینه روشن شد...")
2226
  bot.run()
 
28
  BOT_GUID = None
29
 
30
  # =======================================================
31
+ # 🔥 سیستم ضد اسپم کاربر-محور (اصلاح شده) 🔥
32
  # =======================================================
33
+ user_message_times = {}
34
+
35
+ def is_user_spamming(chat_id):
36
+ now = time.time()
37
+ times = user_message_times.get(chat_id,[])
38
+ # فقط زمان پیام‌های 3 ثانیه اخیر را نگه می‌داریم
39
+ times = [t for t in times if now - t < 3.0]
40
+ times.append(now)
41
+ user_message_times[chat_id] = times
42
+
43
+ # اگر یک کاربر به تنهایی در 3 ثانیه بیش از 4 پیام داد، پیامش نادیده گرفته شود
44
+ if len(times) > 4:
45
+ return True
46
+ return False
 
 
 
47
 
48
  # --- سیستم دیتابیس حساب کاربری متصل به دیتاست هاگینگ فیس ---
49
  DB_FILE = "users_db.json"
 
94
  pass
95
  return {}
96
 
97
+ db_needs_upload = False
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  def save_db(db_data):
100
+ global db_needs_upload
101
  with db_lock:
102
  try:
103
  with open(DB_FILE, "w", encoding="utf-8") as f:
104
  json.dump(db_data, f, ensure_ascii=False, indent=4)
105
+ db_needs_upload = True # فقط تیک می‌زنیم که نیاز به آپلود دارد
106
  except Exception as e:
107
  print("خطا در ذخیره دیتابیس:", e)
108
 
109
+ # یک تسک پس‌زمینه برای آپلود منظم و بدون فشار به سرور
110
+ async def background_db_uploader():
111
+ global db_needs_upload
112
+ while True:
113
+ await asyncio.sleep(300) # هر ۵ دقیقه چک می‌کند
114
+ if db_needs_upload and HF_TOKEN_DB:
115
+ db_needs_upload = False
116
+ api = HfApi(token=HF_TOKEN_DB)
117
+ try:
118
+ # استفاده از to_thread برای جلوگیری از قفل شدن ربات
119
+ await asyncio.to_thread(
120
+ api.upload_file,
121
+ path_or_fileobj=DB_FILE,
122
+ path_in_repo=DB_FILE,
123
+ repo_id=DATASET_REPO,
124
+ repo_type="dataset"
125
+ )
126
+ print("✅ بکاپ دیتابیس در هاگینگ فیس ذخیره شد.")
127
+ except Exception as e:
128
+ print("❌ خطا در آپلود دیتابیس به هاگینگ فیس:", str(e)[:100])
129
+ db_needs_upload = True # اگر خطا داد دفعه بعد دوباره تلاش کند
130
+
131
  user_credits_db = load_db()
132
 
133
  def get_or_create_referral_code(chat_id):
 
653
 
654
  user_states = {}
655
  processed_message_ids = set()
 
656
 
657
 
658
  async def process_gemini(client, chat_id, prompt, file_bytes=None, file_name=None):
 
1580
  async def main_handler(client, update):
1581
  global BOT_GUID
1582
 
 
 
 
1583
  try:
1584
  if not BOT_GUID:
1585
  try:
 
1610
  if unique_msg_key in processed_message_ids: return
1611
  processed_message_ids.add(unique_msg_key)
1612
  if len(processed_message_ids) > 5000: processed_message_ids.clear()
 
 
 
 
 
 
 
1613
 
1614
  user_text = getattr(update, "text", "") or getattr(msg_obj, "text", "")
1615
  user_text_str = str(user_text).strip() if user_text else ""
 
1617
 
1618
  str_chat_id = str(chat_id).replace("`", "").replace("'", "").replace('"', "").strip()
1619
 
1620
+ # بررسی اسپم فقط برای همین کاربر
1621
+ if is_user_spamming(str_chat_id):
1622
+ return
1623
+
1624
  if str_chat_id not in user_states:
1625
  user_states[str_chat_id] = {"mode": None, "text": "", "history":[], "file_bytes": None, "file_name": None}
1626
 
 
2222
 
2223
  if bot_token:
2224
  loop = asyncio.get_event_loop()
2225
+ loop.set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=32))
2226
+
2227
+ # روشن کردن سیستم آپلود دیتابیس هوشمند
2228
+ loop.create_task(background_db_uploader())
2229
 
2230
+ print("ربات آلفا پرو با سیستم اشتراک نامحدود + سپر امنیتی + دانلود پیشرفته فایل + 32 Worker پس‌زمینه روشن شد...")
2231
  bot.run()