-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
966 lines (779 loc) · 34.6 KB
/
app.py
File metadata and controls
966 lines (779 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
from bale import Bot, Message, SuccessfulPayment, Update, InlineKeyboardMarkup, InlineKeyboardButton, LabeledPrice
import aiohttp
import asyncio
import sqlite3
import threading
import logging
import pytz
import jdatetime
import re
from datetime import datetime
from contextlib import asynccontextmanager
from typing import Optional, List, Tuple
import concurrent.futures
import time
import gc
BOT_TOKEN = "TOKEN"
MAX_CONCURRENT_UPDATES = 10
UPDATE_BATCH_SIZE = 20
MEMORY_CLEAN_INTERVAL = 10
MAX_ACTIVE_GROUPS = 300
ACTIVATION_PRICE = 15000
PROVIDER_TOKEN = "PAYMENT_TOKEN"
bot = Bot(token=BOT_TOKEN)
TEHRAN_TIMEZONE = pytz.timezone('Asia/Tehran')
en_to_fa = {"0": "۰", "1": "۱", "2": "۲", "3": "۳", "4": "۴",
"5": "۵", "6": "۶", "7": "۷", "8": "۸", "9": "۹"}
logging.basicConfig(
level=logging.WARNING,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%H:%M:%S'
)
logger = logging.getLogger(__name__)
async def is_admins(chat_id: int, user_id: int) -> bool:
try:
admins = await bot.get_chat_administrators(chat_id)
for admin in admins:
if admin.user.id == user_id:
return True
return False
except Exception:
return False
class OptimizedDatabase:
def __init__(self):
self._init_database()
self._cache = {}
self._cache_time = {}
self._cache_ttl = 30
def _init_database(self):
conn = sqlite3.connect("group_bio_opt.db", check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA cache_size=500")
conn.execute("PRAGMA temp_store=MEMORY")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS groups (
chat_id INTEGER PRIMARY KEY,
custom_bio TEXT,
is_active INTEGER DEFAULT 0,
last_update TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
paid INTEGER DEFAULT 0,
payer_id INTEGER
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_active ON groups(is_active)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_last_update ON groups(last_update)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_paid ON groups(paid)")
conn.commit()
conn.close()
def _get_cached(self, key):
if key in self._cache:
if time.time() - self._cache_time[key] < self._cache_ttl:
return self._cache[key]
else:
del self._cache[key]
del self._cache_time[key]
return None
def _set_cached(self, key, value):
self._cache[key] = value
self._cache_time[key] = time.time()
if len(self._cache) > 500:
oldest = min(self._cache_time.items(), key=lambda x: x[1])
del self._cache[oldest[0]]
del self._cache_time[oldest[0]]
def execute_query_sync(self, query: str, params: tuple = ()):
conn = sqlite3.connect("group_bio_opt.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute(query, params)
result = cursor.fetchall()
conn.commit()
conn.close()
return result
def execute_update_sync(self, query: str, params: tuple = ()):
conn = sqlite3.connect("group_bio_opt.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute(query, params)
conn.commit()
conn.close()
async def get_active_groups_count(self):
cache_key = "active_count"
cached = self._get_cached(cache_key)
if cached:
return cached
results = self.execute_query_sync("""
SELECT COUNT(*) FROM groups WHERE is_active = 1
""")
count = results[0][0] if results else 0
self._set_cached(cache_key, count)
return count
async def get_paid_groups_count(self):
results = self.execute_query_sync("""
SELECT COUNT(*) FROM groups WHERE paid = 1
""")
return results[0][0] if results else 0
async def can_add_new_group(self):
active_count = await self.get_active_groups_count()
paid_count = await self.get_paid_groups_count()
return active_count < MAX_ACTIVE_GROUPS
async def add_group_with_payment(self, chat_id: int, payer_id: int):
cache_key = f"group_{chat_id}"
self._set_cached(cache_key, (1, None, 1))
self.execute_update_sync("""
INSERT OR REPLACE INTO groups(chat_id, is_active, paid, payer_id, last_update)
VALUES (?, 1, 1, ?, CURRENT_TIMESTAMP)
""", (chat_id, payer_id))
return True
async def toggle_group_status(self, chat_id: int, status: int):
cache_key = f"group_{chat_id}"
current = self._get_cached(cache_key)
if current:
custom_bio = current[1]
paid = current[2] if len(current) > 2 else 0
self._set_cached(cache_key, (status, custom_bio, paid))
self.execute_update_sync("""
UPDATE groups
SET is_active = ?, last_update = CURRENT_TIMESTAMP
WHERE chat_id = ?
""", (status, chat_id))
async def update_custom_bio(self, chat_id: int, custom_bio: Optional[str]):
cache_key = f"group_{chat_id}"
current = self._get_cached(cache_key)
status = current[0] if current else 1
paid = current[2] if current and len(current) > 2 else 1
self._set_cached(cache_key, (status, custom_bio, paid))
self.execute_update_sync("""
UPDATE groups
SET custom_bio = ?, last_update = CURRENT_TIMESTAMP
WHERE chat_id = ?
""", (custom_bio, chat_id))
async def update_last_update_time(self, chat_id: int):
self.execute_update_sync("""
UPDATE groups
SET last_update = CURRENT_TIMESTAMP
WHERE chat_id = ?
""", (chat_id,))
async def get_active_groups_batch(self, limit: int = UPDATE_BATCH_SIZE, offset: int = 0):
results = self.execute_query_sync("""
SELECT chat_id, custom_bio
FROM groups
WHERE is_active = 1 AND paid = 1
ORDER BY last_update ASC
LIMIT ? OFFSET ?
""", (limit, offset))
for row in results:
yield (row[0], row[1])
async def get_all_active_groups_count(self):
return await self.get_active_groups_count()
async def get_group_status(self, chat_id: int):
cache_key = f"group_{chat_id}"
cached = self._get_cached(cache_key)
if cached:
return cached
results = self.execute_query_sync("""
SELECT is_active, custom_bio, paid FROM groups WHERE chat_id = ?
""", (chat_id,))
if results:
status = results[0]
self._set_cached(cache_key, status)
return status
return None
async def group_exists(self, chat_id: int):
cache_key = f"exists_{chat_id}"
cached = self._get_cached(cache_key)
if cached is not None:
return cached
results = self.execute_query_sync("""
SELECT 1 FROM groups WHERE chat_id = ?
""", (chat_id,))
exists = bool(results)
self._set_cached(cache_key, exists)
return exists
async def is_group_paid(self, chat_id: int):
cache_key = f"paid_{chat_id}"
cached = self._get_cached(cache_key)
if cached is not None:
return cached
results = self.execute_query_sync("""
SELECT paid FROM groups WHERE chat_id = ?
""", (chat_id,))
if results:
paid = results[0][0]
self._set_cached(cache_key, paid)
return paid == 1
return False
def clear_cache(self):
self._cache.clear()
self._cache_time.clear()
db = OptimizedDatabase()
_time_cache = {}
_date_cache = {}
def persian_number(text):
if not text:
return ""
result = []
for ch in str(text):
result.append(en_to_fa.get(ch, ch))
return ''.join(result)
def get_current_time_fa():
now = datetime.now(TEHRAN_TIMEZONE)
minute_key = f"time_{now.minute}"
if minute_key in _time_cache:
return _time_cache[minute_key]
time_24h = now.strftime("%H:%M")
time_12h = now.strftime("%I:%M %p")
time_12h_fa = persian_number(time_12h.replace("AM", "ق.ظ").replace("PM", "ب.ظ"))
time_24h_fa = persian_number(time_24h)
result = f"{time_24h_fa} ({time_12h_fa})"
_time_cache[minute_key] = result
if len(_time_cache) > 60:
oldest = min(_time_cache.keys())
del _time_cache[oldest]
return result
def get_current_date_fa():
now = datetime.now(TEHRAN_TIMEZONE)
date_key = f"date_{now.day}"
if date_key in _date_cache:
return _date_cache[date_key]
jdate = jdatetime.datetime.fromgregorian(datetime=now)
result = f"{persian_number(jdate.year)}/{persian_number(jdate.month)}/{persian_number(jdate.day)}"
_date_cache[date_key] = result
if len(_date_cache) > 31:
oldest = min(_date_cache.keys())
del _date_cache[oldest]
return result
def get_formatted_time(custom_bio: Optional[str] = None):
time_fa = get_current_time_fa()
date_fa = get_current_date_fa()
if not custom_bio:
return f"🕒 ساعت تهران: *{time_fa}*\n📅 تاریخ: *{date_fa}*\n\nلحظات خود را با ما شیرین کنید 🍯"
result = custom_bio
if '{time}' in result.lower():
result = re.sub(r'\{time\}', time_fa, result, flags=re.IGNORECASE)
if '{date}' in result.lower():
result = re.sub(r'\{date\}', date_fa, result, flags=re.IGNORECASE)
return result
class LightweightRateLimiter:
def __init__(self, max_per_minute: int = 15):
self.max_per_minute = max_per_minute
self.requests = []
async def acquire(self):
now = time.time()
self.requests = [req for req in self.requests if now - req < 60]
if len(self.requests) >= self.max_per_minute:
wait_time = 60 - (now - self.requests[0])
if wait_time > 0:
await asyncio.sleep(wait_time)
self.requests.pop(0)
self.requests.append(now)
rate_limiter = LightweightRateLimiter(max_per_minute=15)
async def update_single_group_description(session: aiohttp.ClientSession,
chat_id: int,
custom_bio: Optional[str] = None):
await rate_limiter.acquire()
description = get_formatted_time(custom_bio)
api_url = f"https://tapi.bale.ai/bot{BOT_TOKEN}/setChatDescription"
try:
async with session.post(
api_url,
json={"chat_id": chat_id, "description": description},
timeout=aiohttp.ClientTimeout(total=8)
) as response:
if response.status == 200:
await db.update_last_update_time(chat_id)
return True
else:
logger.warning(f"Group {chat_id}: HTTP {response.status}")
return False
except asyncio.TimeoutError:
logger.warning(f"Timeout for group {chat_id}")
return False
except Exception as e:
logger.error(f"Error updating group {chat_id}: {str(e)[:50]}")
return False
async def update_groups_batch(group_batch: List[Tuple[int, Optional[str]]]):
successful = 0
failed = 0
async with aiohttp.ClientSession() as session:
semaphore = asyncio.Semaphore(MAX_CONCURRENT_UPDATES)
async def limited_update(chat_id, custom_bio):
async with semaphore:
return await update_single_group_description(session, chat_id, custom_bio)
tasks = []
for chat_id, custom_bio in group_batch:
tasks.append(limited_update(chat_id, custom_bio))
for i in range(0, len(tasks), MAX_CONCURRENT_UPDATES):
batch_tasks = tasks[i:i+MAX_CONCURRENT_UPDATES]
results = await asyncio.gather(*batch_tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
failed += 1
elif result:
successful += 1
else:
failed += 1
if i + MAX_CONCURRENT_UPDATES < len(tasks):
await asyncio.sleep(0.5)
return successful, failed
async def update_all_groups_loop():
logger.info("🔄 Starting optimized update loop...")
last_memory_clean = time.time()
while True:
try:
total_groups = await db.get_all_active_groups_count()
if total_groups == 0:
await asyncio.sleep(60)
continue
all_successful = 0
all_failed = 0
for batch_num in range(0, total_groups, UPDATE_BATCH_SIZE):
batch = []
async for group in db.get_active_groups_batch(UPDATE_BATCH_SIZE, batch_num):
batch.append(group)
if not batch:
break
successful, failed = await update_groups_batch(batch)
all_successful += successful
all_failed += failed
if batch_num + UPDATE_BATCH_SIZE < total_groups:
await asyncio.sleep(1)
current_time = time.time()
if current_time - last_memory_clean > MEMORY_CLEAN_INTERVAL * 60:
gc.collect()
db.clear_cache()
_time_cache.clear()
_date_cache.clear()
last_memory_clean = current_time
now = datetime.now(TEHRAN_TIMEZONE)
seconds_elapsed = now.second + now.microsecond / 1_000_000
sleep_time = max(1, 60 - seconds_elapsed)
await asyncio.sleep(sleep_time)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in update loop: {e}")
await asyncio.sleep(30)
async def request_payment_for_group(message: Message):
chat_id = message.chat.id
user_id = message.from_user.id
try:
await message.reply(
f"💰 *پرداخت فعالسازی ربات*\n\n"
f"برای فعالسازی ربات در این گروه، باید مبلغ *{ACTIVATION_PRICE:,} تومان* پرداخت کنید.\n\n"
f"📍 *محدودیت:* فقط {MAX_ACTIVE_GROUPS} گروه میتوانند همزمان فعال باشند.\n"
f"✅ پس از پرداخت، ربات به طور خودکار فعال میشود.\n\n"
f"برای پرداخت از دکمه زیر استفاده کنید:"
)
await message.chat.send_invoice(
title="فعالسازی ربات بروزرسانی بیو گروه",
description=f"فعالسازی ربات در گروه {message.chat.title}\nپس از پرداخت، ربات به مدت نامحدود فعال خواهد بود.",
provider_token=PROVIDER_TOKEN,
payload=f"{{'chat_id': {chat_id}, 'payer_id': {user_id}}}",
prices=[LabeledPrice(label="فعالسازی ربات", amount=ACTIVATION_PRICE * 10)],
photo_url="https://s6.uupload.ir/files/chatgpt_image_nov_16_2025_08_06_07_am_lbvh_ejas.png"
)
except Exception as e:
logger.error(f"Payment request error: {e}")
await message.reply("❌ خطا در ایجاد فاکتور پرداخت. لطفاً دوباره تلاش کنید.")
async def handle_activation(message: Message):
chat_id = message.chat.id
user_id = message.from_user.id
can_add = await db.can_add_new_group()
if not can_add:
await message.reply(
f"⛔ *ظرفیت تکمیل شده!*\n\n"
f"در حال حاضر {MAX_ACTIVE_GROUPS} گروه فعال هستند.\n"
f"لطفاً منتظر بمانید تا ظرفیت خالی شود."
)
return
is_paid = await db.is_group_paid(chat_id)
if is_paid:
await db.toggle_group_status(chat_id, 1)
status = await db.get_group_status(chat_id)
custom_bio = status[1] if status else None
if custom_bio:
message_text = (
"✅ *ربات مجدداً فعال شد!*\n\n"
f"📝 بیو سفارشی حفظ شد:\n{custom_bio}\n\n"
"🔹 توضیحات گروه هر دقیقه به طور خودکار بروزرسانی میشود."
)
else:
message_text = (
"✅ *ربات مجدداً فعال شد!*\n\n"
"📝 توضیحات گروه هر دقیقه به طور خودکار بروزرسانی میشود."
)
commands_text = (
"\n\n🔹 *دستورات موجود:*\n"
"• /help - راهنما\n"
"• /disable - غیرفعال کردن\n"
"• /setbio [متن] - تنظیم بیو سفارشی\n"
"• /removebio - حذف بیو سفارشی\n"
"• /status - وضعیت فعلی"
)
await message.reply(message_text + commands_text)
else:
await request_payment_for_group(message)
async def handle_deactivation(message: Message):
chat_id = message.chat.id
status = await db.get_group_status(chat_id)
if status and status[0] == 1:
await db.toggle_group_status(chat_id, 0)
await message.reply(
"❌ *ربات غیرفعال شد!*\n\n"
"📌 *نکته:*\n"
"تنظیمات بیو سفارشی شما حفظ شده.\n"
"برای فعالسازی مجدد از /enable استفاده کنید."
)
else:
await message.reply("⚠️ *ربات از قبل غیرفعال است!*")
async def handle_enable(message: Message):
await handle_activation(message)
async def handle_set_bio(message: Message):
chat_id = message.chat.id
is_paid = await db.is_group_paid(chat_id)
if not is_paid:
await message.reply(
"⚠️ *ابتدا باید ربات را فعال کنید!*\n\n"
"برای فعالسازی و پرداخت از دستور /enable استفاده کنید."
)
return
command_parts = message.text.split(maxsplit=1)
if len(command_parts) < 2:
await message.reply(
"⚠️ *لطفاً متن بیو را وارد کنید!*\n\n"
"📝 استفاده صحیح:\n"
"*/setbio متن دلخواه شما*\n\n"
"🔸 *متغیرهای قابل استفاده:*\n"
"• *{TIME}* - نمایش زمان فارسی\n"
"• *{DATE}* - نمایش تاریخ فارسی\n\n"
"📌 *مثال:*\n"
"*/setbio گروه برنامهنویسان\nزمان: {TIME}\nتاریخ: {DATE}*\n\n"
)
return
custom_bio = command_parts[1].strip()
if len(custom_bio) > 200:
await message.reply("❌ *متن بیو نباید بیشتر از ۲۰۰ کاراکتر باشد!*")
return
await db.update_custom_bio(chat_id, custom_bio)
preview = get_formatted_time(custom_bio)
await message.reply(
f"✅ *بیو سفارشی ذخیره شد!*\n\n"
f"📝 *پیشنمایش:*\n"
f"{preview}\n\n"
)
try:
async with aiohttp.ClientSession() as session:
await update_single_group_description(session, chat_id, custom_bio)
except:
pass
async def handle_remove_bio(message: Message):
chat_id = message.chat.id
is_paid = await db.is_group_paid(chat_id)
if not is_paid:
await message.reply(
"⚠️ *ابتدا باید ربات را فعال کنید!*\n\n"
"برای فعالسازی و پرداخت از دستور /enable استفاده کنید."
)
return
status = await db.get_group_status(chat_id)
if status and status[1]:
await db.update_custom_bio(chat_id, None)
await message.reply(
"✅ *بیو سفارشی حذف شد!*\n\n"
"📌 بیو گروه به حالت پیشفرض بازگشت.\n"
"برای تنظیم مجدد از دستور /setbio استفاده کنید."
)
try:
async with aiohttp.ClientSession() as session:
await update_single_group_description(session, chat_id, None)
except:
pass
else:
await message.reply("⚠️ *بیو سفارشیای برای حذف وجود ندارد!*")
async def handle_status(message: Message):
chat_id = message.chat.id
status = await db.get_group_status(chat_id)
active_groups = await db.get_active_groups_count()
paid_groups = await db.get_paid_groups_count()
if not status:
response = (
"📊 *وضعیت ربات:* ❌ غیرفعال\n\n"
"ربات در این گروه فعال نشده است.\n"
"برای فعالسازی از دستور /enable استفاده کنید.\n\n"
f"📈 *آمار کلی:*\n"
f"• گروههای فعال: {active_groups}/{MAX_ACTIVE_GROUPS}\n"
f"• گروههای پرداختشده: {paid_groups}"
)
else:
is_active, custom_bio, paid = status
status_text = "✅ فعال" if is_active == 1 else "❌ غیرفعال"
payment_status = "✅ پرداخت شده" if paid == 1 else "❌ پرداخت نشده"
bio_status = f"✅ تنظیم شده" if custom_bio else "❌ تنظیم نشده"
response = (
f"📊 *وضعیت ربات در این گروه:*\n\n"
f"🔸 *وضعیت:* {status_text}\n"
f"🔸 *وضعیت پرداخت:* {payment_status}\n"
f"🔸 *بیو سفارشی:* {bio_status}\n\n"
)
if custom_bio:
response += (
f"📝 *متن ذخیره شده:*\n"
f"{custom_bio}\n\n"
)
response += (
f"🕒 *زمان فعلی:* {get_current_time_fa()}\n"
f"📅 *تاریخ فعلی:* {get_current_date_fa()}\n\n"
f"🆔 *شناسه گروه:* {chat_id}\n\n"
f"📈 *آمار کلی:*\n"
f"• گروههای فعال: {active_groups}/{MAX_ACTIVE_GROUPS}\n"
f"• گروههای پرداختشده: {paid_groups}"
)
await message.reply(response)
async def handle_help(message: Message):
help_text = (
"📚 *راهنمای کامل ربات*\n\n"
"💰 *سیستم پرداخت:*\n"
f"• هزینه فعالسازی: {ACTIVATION_PRICE:,} تومان\n"
f"• محدودیت: {MAX_ACTIVE_GROUPS} گروه همزمان\n"
"• پرداخت یکباره برای همیشه\n\n"
"🔸 *فعالسازی و غیرفعالسازی:*\n"
"*/enable* - فعال کردن ربات (نیاز به پرداخت)\n"
"*/disable* - غیرفعال کردن ربات\n"
"*/status* - نمایش وضعیت\n\n"
"🔸 *تنظیمات بیو:*\n"
"*/setbio [متن]* - تنظیم بیو سفارشی\n"
"*/removebio* - حذف بیو سفارشی\n\n"
"🔸 *متغیرهای بیو سفارشی:*\n"
"• *{TIME}* - نمایش زمان فارسی\n"
"• *{DATE}* - نمایش تاریخ فارسی\n"
"• *پشتیبانی از حروف ترکیبی:*\n"
" {TiMe}، {DaTE}، {Time}، {date}\n\n"
"📌 *مثال استفاده:*\n"
"/setbio گروه ما\n"
"🕒 زمان: {TIME}\n"
"📅 تاریخ: {DATE}\n"
"به گروه خوش آمدید!\n\n"
"🔸 *سایر دستورات:*\n"
"*/help* - نمایش این راهنما\n"
"*/about* - درباره ربات\n\n"
"📌 *الزامات:*\n"
"• ربات باید ادمین گروه باشد\n"
"• بیو سفارشی حداکثر ۲۰۰ کاراکتر\n"
"• بروزرسانی هر دقیقه انجام میشود"
)
await message.reply(help_text)
async def handle_about(message: Message):
active_groups = await db.get_active_groups_count()
paid_groups = await db.get_paid_groups_count()
about_text = (
"🤖 *ربات بروزرسانی بیو گروه*\n\n"
"📝 *توضیحات:*\n"
"این ربات به طور خودکار توضیحات گروه را\n"
"با زمان و تاریخ فارسی به روز میکند.\n\n"
"💰 *سیستم پرداخت:*\n"
f"• هزینه فعالسازی: {ACTIVATION_PRICE:,} تومان\n"
f"• محدودیت: {MAX_ACTIVE_GROUPS} گروه\n"
f"• گروههای فعال: {active_groups}\n"
f"• گروههای پرداختشده: {paid_groups}\n\n"
"✨ *ویژگیهای ویژه این نسخه:*\n"
"• پشتیبانی از متغیرهای زمان و تاریخ\n"
"• نمایش زمان به دو فرمت ۱۲ و ۲۴ ساعته\n"
"• تاریخ شمسی دقیق\n"
"• محدودیت ۳۰۰ گروه فعال\n\n"
"🛠 *توسعهدهنده:*\n"
"توسعه داده شده توسط تیم *DigiX*\n\n"
"📞 *پشتیبانی:*\n"
"برای گزارش مشکل از دستور /help استفاده کنید\n\n"
"💾 *ذخیره سازی:*\n"
"همه تنظیمات ذخیره میشوند\n\n"
"🕒 *زمان فعلی:* {}\n"
"📅 *تاریخ فعلی:* {}"
).format(get_current_time_fa(), get_current_date_fa())
await message.reply(about_text)
async def handle_donate(message: Message):
if message.content == "💸 حمایت مالی":
try:
await message.reply("لطفا مبلغ مورد نظر را وارد کنید (ریال)")
def answer_checker(m: Message):
return m.author == message.author and bool(m.text)
answer_obj: Message = await bot.wait_for('message', check=answer_checker)
numbers = re.findall(r"\d+", answer_obj.content)
if not numbers:
await message.reply("*لطفا فقط عدد وارد کنید*")
return
PRICE = numbers[0].strip()
if not PRICE.isdigit():
await message.reply("*لطفا فقط عدد وارد کنید*")
return
PRICE = int(PRICE)
if PRICE <= 1000:
await message.reply("*لطفا مبلغ معتبر وارد کنید (سقف: 10000﷼)*")
return
await message.chat.send_invoice(
title="Donate",
description="""ممنون از حمایت شما! دونیشنهای شما به ما کمک میکند پروژهها و خدماتمان را ادامه دهیم و همیشه بهترین کیفیت را ارائه کنیم.""",
provider_token=PROVIDER_TOKEN,
payload="{{'name': '{}', 'price': {}}}".format(message.from_user.first_name, PRICE),
prices=[LabeledPrice(label="Donate", amount=PRICE)],
photo_url="https://s6.uupload.ir/files/chatgpt_image_nov_16_2025_08_06_07_am_lbvh_ejas.png"
)
except Exception as e:
logger.error(f"Donation error: {e}")
async def private_handler(message: Message):
if message.chat.type != "private":
return
active_groups = await db.get_active_groups_count()
await message.reply(
"👋 *سلام!* به ربات بروزرسانی بیو گروه خوش آمدید.\n\n"
"📝 این ربات به طور خودکار توضیحات گروه را\n"
"با زمان و تاریخ فارسی به روز میکند.\n\n"
f"💰 *هزینه فعالسازی:* {ACTIVATION_PRICE:,} تومان\n"
f"📊 *ظرفیت فعلی:* {active_groups}/{MAX_ACTIVE_GROUPS} گروه\n\n"
"🔸 *ویژگیهای اصلی:*\n"
"• پشتیبانی از بیو سفارشی\n"
"• تبدیل خودکار {TIME} و {DATE}\n"
"• نمایش زمان به دو فرمت ۱۲ و ۲۴ ساعته\n"
"• پرداخت یکباره برای همیشه\n\n"
"📌 *نحوه استفاده:*\n"
"1. ربات را به گروه اضافه کنید\n"
"2. در گروه دستور /enable را بفرستید\n"
f"3. پرداخت {ACTIVATION_PRICE:,} تومان را انجام دهید\n"
"4. ربات را ادمین کنید\n"
"5. بیو گروه به طور خودکار بروزرسانی میشود\n\n"
"🔹 *دستورات:*\n"
"• /help - راهنمای کامل\n"
"• /about - درباره ربات"
)
@bot.event
async def on_message(message: Message):
user_id = message.from_user.id
chat_id = message.chat_id
if not message.text:
return
if message.chat.type == "private":
if message.text in ["/start", "/help", "راهنما"]:
await private_handler(message)
elif message.text == "/about":
await handle_about(message)
elif message.text == "💸 حمایت مالی":
await handle_donate(message)
return
if message.chat.type not in ["group", "supergroup"]:
return
text = message.text.strip()
is_admin = await is_admins(chat_id=chat_id, user_id=user_id)
if not is_admin:
return
if text == "/enable" or text == "فعالسازی":
await handle_enable(message)
elif text == "/disable" or text == "غیرفعالسازی":
await handle_deactivation(message)
elif text.startswith("/setbio"):
await handle_set_bio(message)
elif text == "/removebio":
await handle_remove_bio(message)
elif text == "/status":
await handle_status(message)
elif text == "/help":
await handle_help(message)
elif text == "/about":
await handle_about(message)
elif text in ["start", "/start"]:
await private_handler(message)
@bot.event
async def on_successful_payment(successful_payment: SuccessfulPayment):
try:
data = eval(successful_payment.payload)
if 'chat_id' in data and 'payer_id' in data:
chat_id = data['chat_id']
payer_id = data['payer_id']
await db.add_group_with_payment(chat_id, payer_id)
await bot.send_message(
chat_id=chat_id,
text=(
"✅ *پرداخت موفقیتآمیز بود!*\n\n"
"🎉 ربات با موفقیت فعال شد.\n"
"📝 اکنون ربات را ادمین کنید تا توضیحات گروه\n"
"به طور خودکار هر دقیقه بروزرسانی شود.\n\n"
"🔹 *دستورات موجود:*\n"
"• /setbio - تنظیم بیو سفارشی\n"
"• /status - نمایش وضعیت\n"
"• /help - راهنمای کامل"
)
)
await bot.send_message(
chat_id=payer_id,
text=(
f"✅ *پرداخت شما تایید شد!*\n\n"
f"ربات در گروه با شناسه {chat_id} فعال شد.\n"
f"مبلغ: {successful_payment.total_amount / 10:,} تومان\n\n"
f"ممنون از اعتماد شما! 🙏"
)
)
else:
user_name = data['name']
price = data['price']
bot_username = await bot.get_me()
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton("مشاهده ربات", url=f"https://ble.ir/{bot_username.username}"))
await bot.send_message(
chat_id=data.get('payer_id', data.get('user_id', 4573593712)),
text=(
f"*دمت گرم* {user_name}! 💪💸\n\n"
f"{price:,} ریال واریز شد، کلی بهمون انرژی دادی! 🙌🔥"
),
components=markup
)
except Exception as e:
logger.error(f"Payment processing error: {e}")
@bot.event
async def on_update(update: Update):
if update.pre_checkout_query:
try:
await bot.answer_pre_checkout_query(
pre_checkout_query_id=update.pre_checkout_query.id,
ok=True
)
except Exception as e:
logger.error(f"Pre-checkout error: {e}")
await bot.answer_pre_checkout_query(
pre_checkout_query_id=update.pre_checkout_query.id,
ok=False,
error_message="پرداخت امکانپذیر نیست"
)
def start_update_thread():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(update_all_groups_loop())
except KeyboardInterrupt:
logger.info("Update thread stopped")
except Exception as e:
logger.error(f"Update thread error: {e}")
finally:
loop.close()
def main():
gc.set_threshold(700, 10, 10)
update_thread = threading.Thread(
target=start_update_thread,
daemon=True,
name="UpdateThread"
)
update_thread.start()
try:
print("Bot is running")
bot.run()
except KeyboardInterrupt:
print("Bot stopped by user")
except Exception as e:
print(f"Error: {e}")
finally:
print("All connections closed")
if __name__ == "__main__":
try:
import resource
resource.setrlimit(resource.RLIMIT_AS, (150 * 1024 * 1024, 200 * 1024 * 1024))
except:
pass
main()