-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathmain.py
More file actions
3436 lines (2905 loc) · 114 KB
/
Copy pathmain.py
File metadata and controls
3436 lines (2905 loc) · 114 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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import os
import subprocess
import sys
import time
from uuid import uuid4
import redis
import telethon
import telethon.tl.types
from telethon import TelegramClient, events
from telethon import Button
from telethon.tl.functions.messages import ForwardMessagesRequest
from telethon.types import Message, UpdateNewMessage
from cansend import CanSend
from config import *
from terabox import get_files
from tools import (
add_watermark,
convert_seconds,
download_file,
download_image_to_bytesio,
escape_markdown,
extract_code_from_url,
get_formatted_size,
get_video_info,
get_urls_from_string,
is_user_on_chat,
send_document_via_api,
VIDEO_EXTENSIONS,
)
bot = TelegramClient("tele", API_ID, API_HASH)
db = redis.Redis(
host=HOST,
port=PORT,
password=PASSWORD,
decode_responses=True,
)
PREMIUM_SET_KEY = "premium_users" # Redis SET — legacy, kept for /demote_all_premium
PREMIUM_EXPIRY_KEY = "premium_expiry" # Redis HASH — user_id → expiry timestamp
BANNED_USERS_KEY = "banned_users" # Redis SET — banned user IDs
HISTORY_KEY = "download_history" # Redis HASH — user_id → JSON list of downloads
STATS_KEY = "bot_stats" # Redis HASH — total_downloads, total_users
BANNED_SET_KEY = "banned_users_set"
AUDIT_LOG_KEY = "audit_log" # Redis LIST — recent admin actions
MAINTENANCE_KEY = "maintenance_mode" # Redis STRING — "1" = maintenance on
COOLDOWN_KEY = "download_cooldown" # Redis STRING — user_id → timestamp
DYNAMIC_ADMINS_KEY = "dynamic_admins" # Redis SET — dynamically added admin IDs
CUSTOM_TAGS_KEY = "custom_tags" # Redis HASH — user_id → custom tag
GC_USED_KEY = "gc_used" # Redis HASH — code → "user_id:timestamp:days"
MAX_FILES_PER_REQUEST = 10
DOWNLOAD_COOLDOWN_SECONDS = 10
# ==================== DYNAMIC ADMIN SYSTEM ====================
def is_admin(user_id):
"""Check if user is admin (config + dynamic)."""
uid = int(user_id)
if uid in ADMINS:
return True
return db.sismember(DYNAMIC_ADMINS_KEY, str(uid))
def get_all_admins():
"""Return all admin IDs (config + dynamic)."""
dynamic = db.smembers(DYNAMIC_ADMINS_KEY)
all_admins = set(ADMINS)
for uid in dynamic:
all_admins.add(int(uid))
return all_admins
def add_admin(user_id):
"""Add admin dynamically."""
db.sadd(DYNAMIC_ADMINS_KEY, str(user_id))
def remove_admin(user_id):
"""Remove dynamic admin (can't remove config admins)."""
db.srem(DYNAMIC_ADMINS_KEY, str(user_id))
def grant_premium(user_id, days):
"""Grant premium to user for N days from now."""
import time as _time
expiry = int(_time.time()) + (days * 86400)
db.hset(PREMIUM_EXPIRY_KEY, str(user_id), expiry)
db.sadd(PREMIUM_SET_KEY, str(user_id))
def revoke_premium(user_id):
"""Revoke premium from user."""
db.hdel(PREMIUM_EXPIRY_KEY, str(user_id))
db.srem(PREMIUM_SET_KEY, str(user_id))
def is_premium_user(user_id):
"""Check if user has active premium (not expired)."""
import time as _time
uid = str(user_id)
if not db.hexists(PREMIUM_EXPIRY_KEY, uid):
return False
expiry = int(db.hget(PREMIUM_EXPIRY_KEY, uid) or 0)
if _time.time() >= expiry:
revoke_premium(user_id)
return False
return True
def get_premium_remaining(user_id):
"""Return remaining premium seconds, or 0."""
import time as _time
uid = str(user_id)
expiry = int(db.hget(PREMIUM_EXPIRY_KEY, uid) or 0)
remaining = expiry - int(_time.time())
return max(remaining, 0)
def get_all_premium_users():
"""Return list of active premium user IDs."""
return db.smembers(PREMIUM_SET_KEY)
def get_custom_tag(user_id):
"""Get custom tag for a user. Auto-sets owner/admin tags."""
uid = str(user_id)
# Auto-tag owner
if user_id == OWNER_ID:
tag = db.hget(CUSTOM_TAGS_KEY, uid) or "OWNER"
db.hset(CUSTOM_TAGS_KEY, uid, tag)
return tag
# Auto-tag admins
if is_admin(user_id):
tag = db.hget(CUSTOM_TAGS_KEY, uid) or "ADMIN"
db.hset(CUSTOM_TAGS_KEY, uid, tag)
return tag
return db.hget(CUSTOM_TAGS_KEY, uid) or ""
def set_custom_tag(user_id, tag):
"""Set custom tag for a user."""
db.hset(CUSTOM_TAGS_KEY, str(user_id), tag)
def log_audit(action, admin_id, details=""):
"""Log admin action to Redis audit trail."""
import json as _json
entry = _json.dumps({
"action": action,
"admin": admin_id,
"details": details,
"time": time.strftime("%Y-%m-%d %H:%M:%S"),
})
db.lpush(AUDIT_LOG_KEY, entry)
db.ltrim(AUDIT_LOG_KEY, 0, 999) # keep last 1000 entries
def is_maintenance():
"""Check if bot is in maintenance mode."""
return db.get(MAINTENANCE_KEY) == "1"
def check_cooldown(user_id):
"""Check if user is on cooldown. Returns remaining seconds or 0."""
last = db.get(f"{COOLDOWN_KEY}_{user_id}")
if not last:
return 0
elapsed = time.time() - float(last)
if elapsed < DOWNLOAD_COOLDOWN_SECONDS:
return int(DOWNLOAD_COOLDOWN_SECONDS - elapsed)
return 0
def set_cooldown(user_id):
"""Set download cooldown for user."""
db.set(f"{COOLDOWN_KEY}_{user_id}", time.time(), ex=DOWNLOAD_COOLDOWN_SECONDS + 5)
# Define /info and /id commands to display user information
@bot.on(
events.NewMessage(
pattern="/info",
incoming=True,
outgoing=False,
)
)
@bot.on(
events.NewMessage(
pattern="/id",
incoming=True,
outgoing=False,
)
)
async def user_info(m: UpdateNewMessage):
import time as _time
from datetime import datetime
user_id = m.sender_id
name = m.sender.first_name
username = m.sender.username if m.sender.username else "-"
if is_premium_user(user_id):
remaining = get_premium_remaining(user_id)
if remaining > 9000000:
plan = "⭐ Premium (Permanent)"
else:
days = remaining // 86400
hours = (remaining % 86400) // 3600
mins = (remaining % 3600) // 60
expiry_ts = int(_time.time()) + remaining
expiry_str = datetime.fromtimestamp(expiry_ts).strftime("%d %b %Y, %I:%M %p")
plan = f"⭐ Premium ({days}d {hours}h {mins}m left)\nExpires: {expiry_str}"
else:
plan = "🆓 Free"
tag = get_custom_tag(user_id)
tag_line = f"**Tag:** {tag}\n" if tag else ""
info_text = (
f"**Name:** {name}\n"
f"**Username:** @{username}\n"
f"**User ID:** `{user_id}`\n"
f"{tag_line}"
f"**Plan:** {plan}"
)
await m.reply(info_text, parse_mode="markdown", link_preview=False)
# Define /cmds or /help command to describe all available commands
# @bot.on(
# events.NewMessage(
# pattern="/cmds|/help",
# incoming=True,
# outgoing=False,
# func=lambda x: x.is_private,
# )
# )
# async def command_help(m: UpdateNewMessage):
# help_text = """
# ┏━━━━━━━━━━⍟
# ┃ 𝘼𝙫𝙖𝙞𝙡𝙖𝙗𝙡𝙚 𝘾𝙤𝙢𝙢𝙖𝙣𝙙𝙨
# ┗━━━━━━━━━━━━━━━━━⍟
# /start - Start the bot and receive a welcome message.
# /info or /id - Get your user information.
# /redeem <gift_code> - Redeem a gift code for premium access.
# /cmds, or /help to view available cmds
# /plan - To check availabe plan
# Directly share me the link i will share you the video with direct link
# For premium contact @abdul97233
# """
# await m.reply(help_text)
@bot.on(
events.NewMessage(
pattern="/cmds|/help",
incoming=True,
outgoing=False,
)
)
async def command_help(m: UpdateNewMessage):
text = WELCOME_TEXT.format(name=m.sender.first_name)
buttons = [
[
Button.inline("📥 How to Use", data="menu_howto"),
Button.inline("📋 My Info", data="menu_info"),
],
[
Button.inline("⭐ Premium", data="menu_premium"),
Button.inline("🎁 Redeem Card", data="menu_redeem"),
],
[
Button.inline("🛠 Tools", data="menu_tools"),
Button.inline("🌐 Language", data="menu_lang"),
],
[
Button.url("📢 Channel", url="https://t.me/NTMpro"),
Button.url("💬 Group", url="https://t.me/NTMchat"),
],
]
if is_admin(m.sender_id):
buttons.insert(2, [Button.inline("⚙️ Admin Panel", data="menu_admin")])
await m.reply(
text,
link_preview=False,
parse_mode="markdown",
buttons=buttons,
)
# Define /ping command to check bot's latency
@bot.on(
events.NewMessage(
pattern="/ping",
incoming=True,
outgoing=False,
# func=lambda x: x.is_private,
)
)
async def ping_pong(m: UpdateNewMessage):
start_time = time.time()
message = await m.reply("🖥️ Connection Status\nCommand: `/ping`\nResponse Time: Calculating...")
end_time = time.time()
latency = end_time - start_time # Calculate latency in seconds
latency_str = "{:.2f}".format(latency) # Format latency with two decimal places
await message.edit(f"🖥️ Connection Status\nCommand: `/ping`\nResponse Time: {latency_str} seconds")
# ==================== /gen — GENERATE GIFT CARDS ====================
# Usage: /gen <duration> [count] [tag]
# Example: /gen 7d 5 VIP → generates 5 gift codes for 7 days with VIP tag
GC_REDIS_KEY = "gift_cards" # HASH: code → duration_days
GC_TAGS_KEY = "gc_tags" # HASH: code → custom_tag
DURATION_MAP_GC = {
"1d": 1, "2d": 2, "3d": 3, "5d": 5, "7d": 7,
"1w": 7, "2w": 14, "1m": 30, "1mo": 30,
"unlimited": 0, "perm": 0,
}
@bot.on(
events.NewMessage(
pattern=r"/gen\s+(\S+)(?:\s+(\d+))?(?:\s+(.+))?",
incoming=True,
outgoing=False,
func=lambda m: is_admin(m.sender_id),
)
)
async def generate_gc(m: UpdateNewMessage):
duration_str = m.pattern_match.group(1).lower()
count = int(m.pattern_match.group(2) or 1)
tag = (m.pattern_match.group(3) or "").strip()
if count > 50:
return await m.reply("Max 50 codes at once.")
if duration_str not in DURATION_MAP_GC:
valid = ", ".join(DURATION_MAP_GC.keys())
return await m.reply(
f"Invalid duration: `{duration_str}`\n\n"
f"Valid: `{valid}`\n\n"
f"**Usage:** `/gen <duration> [count] [tag]`\n"
f"Examples:\n"
f"- `/gen 7d 5` — 5 cards, 7 days\n"
f"- `/gen 7d 5 VIP` — 5 cards, 7 days, VIP tag\n"
f"- `/gen unlimited 1 PREMIUM` — 1 card, permanent, PREMIUM tag"
)
days = DURATION_MAP_GC[duration_str]
codes = []
for _ in range(count):
code = f"NTM-{str(uuid4())[:8].upper()}"
db.hset(GC_REDIS_KEY, code, days)
if tag:
db.hset(GC_TAGS_KEY, code, tag)
codes.append(code)
duration_label = f"{days} day(s)" if days > 0 else "Permanent (Unlimited)"
# Build redeem codes with /redeem prefix for easy copy
redeem_lines = []
for c in codes:
if tag:
redeem_lines.append(f"`/redeem {c}` (Tag: {tag})")
else:
redeem_lines.append(f"`/redeem {c}`")
tag_info = f"\nTag: **{tag}**" if tag else ""
await m.reply(
f"**{count} Gift Card(s) Generated**\n\n"
f"Duration: **{duration_label}**{tag_info}\n\n"
f"**Send these to users:**\n" + "\n".join(redeem_lines),
parse_mode="markdown",
)
# ==================== /gclist — LIST ALL GIFT CARDS (WITH BUTTONS) ====================
GC_LIST_PER_PAGE = 10
@bot.on(
events.NewMessage(
pattern="/gclist",
incoming=True,
outgoing=False,
func=lambda m: is_admin(m.sender_id),
)
)
async def list_gc(m: UpdateNewMessage):
unused = db.hgetall(GC_REDIS_KEY)
used = db.hgetall(GC_USED_KEY)
if not unused and not used:
return await m.reply("No gift cards found.")
# Build combined list: unused first, then used
items = []
for code, days in unused.items():
days = int(days)
label = "Permanent" if days == 0 else f"{days}d"
items.append({"code": code, "status": "available", "label": label})
for code, val in used.items():
parts = val.split(":")
uid = parts[0] if len(parts) > 0 else "?"
ts = parts[1] if len(parts) > 1 else "?"
days = int(parts[2]) if len(parts) > 2 else 0
label = "Permanent" if days == 0 else f"{days}d"
items.append({"code": code, "status": "used", "label": label, "user": uid, "time": ts})
total = len(items)
total_pages = max(1, (total + GC_LIST_PER_PAGE - 1) // GC_LIST_PER_PAGE)
page = 1
await _send_gc_list(m, items, page, total_pages, total)
async def _send_gc_list(m, items, page, total_pages, total):
start = (page - 1) * GC_LIST_PER_PAGE
end = start + GC_LIST_PER_PAGE
page_items = items[start:end]
unused_count = sum(1 for i in items if i["status"] == "available")
used_count = total - unused_count
lines = []
for i, item in enumerate(page_items, start=start + 1):
if item["status"] == "available":
lines.append(f"{i}. `/redeem {item['code']}` — {item['label']} [Available]")
else:
user = item.get("user", "?")
lines.append(f"{i}. `{item['code']}` — {item['label']} [Used by `{user}`]")
text = (
f"**Gift Cards** ({total} total)\n"
f"Available: {unused_count} | Used: {used_count}\n"
f"Page {page}/{total_pages}\n\n" +
"\n".join(lines)
)
buttons = []
nav = []
if page > 1:
nav.append(Button.inline("◀️ Prev", data=f"gcpage_{page - 1}_{total}"))
if page < total_pages:
nav.append(Button.inline("Next ▶️", data=f"gcpage_{page + 1}_{total}"))
if nav:
buttons.append(nav)
buttons.append([Button.inline("Refresh", data=f"gcpage_{page}_{total}")])
await m.reply(text, parse_mode="markdown", buttons=buttons)
@bot.on(events.CallbackQuery(func=lambda e: e.data and e.data.startswith(b"gcpage_")))
async def gc_page_cb(e):
try:
parts = e.data.decode().split("_")
page = int(parts[1])
total = int(parts[2])
except Exception:
return await e.answer("Invalid callback data.", alert=True)
unused = db.hgetall(GC_REDIS_KEY)
used = db.hgetall(GC_USED_KEY)
tags = db.hgetall(GC_TAGS_KEY)
items = []
for code, days in unused.items():
days = int(days)
label = "Permanent" if days == 0 else f"{days}d"
tag = tags.get(code, "")
items.append({"code": code, "status": "available", "label": label, "tag": tag})
for code, val in used.items():
parts = val.split(":")
uid = parts[0] if len(parts) > 0 else "?"
days = int(parts[2]) if len(parts) > 2 else 0
label = "Permanent" if days == 0 else f"{days}d"
tag = tags.get(code, "")
items.append({"code": code, "status": "used", "label": label, "user": uid, "tag": tag})
total_pages = max(1, (len(items) + GC_LIST_PER_PAGE - 1) // GC_LIST_PER_PAGE)
page = min(page, total_pages)
start = (page - 1) * GC_LIST_PER_PAGE
end = start + GC_LIST_PER_PAGE
page_items = items[start:end]
unused_count = sum(1 for i in items if i["status"] == "available")
used_count = len(items) - unused_count
lines = []
for i, item in enumerate(page_items, start=start + 1):
tag_str = f" [{item.get('tag', '')}]" if item.get('tag') else ""
if item["status"] == "available":
lines.append(f"{i}. `/redeem {item['code']}` — {item['label']}{tag_str} [Available]")
else:
user = item.get("user", "?")
lines.append(f"{i}. `{item['code']}` — {item['label']}{tag_str} [Used by `{user}`]")
text = (
f"**Gift Cards** ({len(items)} total)\n"
f"Available: {unused_count} | Used: {used_count}\n"
f"Page {page}/{total_pages}\n\n" +
"\n".join(lines)
)
buttons = []
nav = []
if page > 1:
nav.append(Button.inline("◀️ Prev", data=f"gcpage_{page - 1}_{len(items)}"))
if page < total_pages:
nav.append(Button.inline("Next ▶️", data=f"gcpage_{page + 1}_{len(items)}"))
if nav:
buttons.append(nav)
buttons.append([Button.inline("Refresh", data=f"gcpage_{page}_{len(items)}")])
await e.edit(text, parse_mode="markdown", buttons=buttons)
# ==================== /gcdel — DELETE A GIFT CARD ====================
@bot.on(
events.NewMessage(
pattern=r"/gcdel\s+(\S+)",
incoming=True,
outgoing=False,
func=lambda m: is_admin(m.sender_id),
)
)
async def delete_gc(m: UpdateNewMessage):
code = m.pattern_match.group(1).upper()
if db.hdel(GC_REDIS_KEY, code):
await m.reply(f"Deleted `{code}`.")
else:
await m.reply(f"Code `{code}` not found.")
# ==================== /gctrack — TRACK GIFT CARD USAGE ====================
@bot.on(
events.NewMessage(
pattern=r"/gctrack(?:\s+(\S+))?",
incoming=True,
outgoing=False,
func=lambda m: is_admin(m.sender_id),
)
)
async def track_gc(m: UpdateNewMessage):
filter_type = m.pattern_match.group(1)
used = db.hgetall(GC_USED_KEY)
if not used:
return await m.reply("No redeemed gift cards found.")
now = int(time.time())
results = []
for code, val in used.items():
parts = val.split(":")
uid = parts[0] if len(parts) > 0 else "?"
ts = int(parts[1]) if len(parts) > 1 else 0
days = int(parts[2]) if len(parts) > 2 else 0
age_hours = (now - ts) / 3600 if ts else 0
label = "Permanent" if days == 0 else f"{days}d"
from datetime import datetime
time_str = datetime.fromtimestamp(ts).strftime("%d %b %Y, %I:%M %p") if ts else "?"
entry = {
"code": code, "user": uid, "days": label,
"time": time_str, "age_hours": round(age_hours, 1),
}
if filter_type == "1h" and age_hours > 1:
continue
elif filter_type == "24h" and age_hours > 24:
continue
elif filter_type == "7d" and age_hours > 168:
continue
elif filter_type and filter_type.isdigit():
if uid != filter_type:
continue
elif filter_type:
if code.upper() != filter_type.upper():
continue
results.append(entry)
if not results:
return await m.reply("No matching gift cards found.")
lines = []
for r in results:
lines.append(
f"`{r['code']}` — {r['days']}\n"
f" User: `{r['user']}`\n"
f" Time: {r['time']} ({r['age_hours']}h ago)"
)
text = f"**Gift Card Usage** ({len(results)} found)\n\n" + "\n\n".join(lines)
if len(text) > 3000:
text = text[:3000] + "\n\n... (truncated)"
buttons = [
[Button.inline("Last 1h", data="gctrack_1h"),
Button.inline("Last 24h", data="gctrack_24h"),
Button.inline("Last 7d", data="gctrack_7d")],
[Button.inline("All", data="gctrack_all")],
]
await m.reply(text, parse_mode="markdown", buttons=buttons)
@bot.on(events.CallbackQuery(func=lambda e: e.data and e.data.startswith(b"gctrack_")))
async def gctrack_cb(e):
try:
filter_type = e.data.decode().split("_", 1)[1]
except Exception:
return await e.answer("Invalid callback data.", alert=True)
used = db.hgetall(GC_USED_KEY)
now = int(time.time())
results = []
for code, val in used.items():
parts = val.split(":")
uid = parts[0] if len(parts) > 0 else "?"
ts = int(parts[1]) if len(parts) > 1 else 0
days = int(parts[2]) if len(parts) > 2 else 0
age_hours = (now - ts) / 3600 if ts else 0
label = "Permanent" if days == 0 else f"{days}d"
from datetime import datetime
time_str = datetime.fromtimestamp(ts).strftime("%d %b %Y, %I:%M %p") if ts else "?"
if filter_type == "1h" and age_hours > 1:
continue
elif filter_type == "24h" and age_hours > 24:
continue
elif filter_type == "7d" and age_hours > 168:
continue
results.append({
"code": code, "user": uid, "days": label,
"time": time_str, "age_hours": round(age_hours, 1),
})
if not results:
return await e.answer("No results for this filter.", alert=True)
lines = []
for r in results:
lines.append(
f"`{r['code']}` — {r['days']}\n"
f" User: `{r['user']}`\n"
f" Time: {r['time']} ({r['age_hours']}h ago)"
)
text = f"**Gift Card Usage** ({len(results)} found)\n\n" + "\n\n".join(lines)
if len(text) > 3000:
text = text[:3000] + "\n\n... (truncated)"
buttons = [
[Button.inline("Last 1h", data="gctrack_1h"),
Button.inline("Last 24h", data="gctrack_24h"),
Button.inline("Last 7d", data="gctrack_7d")],
[Button.inline("All", data="gctrack_all")],
]
await e.edit(text, parse_mode="markdown", buttons=buttons)
# ==================== /redeem — REDEEM GIFT CARD ====================
@bot.on(
events.NewMessage(
pattern=r"/redeem\s+(\S+)",
incoming=True,
outgoing=False,
)
)
async def redeem_gc(m: UpdateNewMessage):
code = m.pattern_match.group(1).upper()
user_id = m.sender_id
# Check if user already redeemed AND still has active premium
if db.get(f"gc_redeemed_{user_id}") and is_premium_user(user_id):
return await m.reply(
"You have already redeemed a gift card and your premium is still active.\n"
"Each user can only redeem **1 gift card** while premium is active.\n"
"Wait for expiry or contact admin."
)
days_str = db.hget(GC_REDIS_KEY, code)
if not days_str:
return await m.reply("Invalid or already used gift card.")
days = int(days_str)
# Get tag before deleting
tag = db.hget(GC_TAGS_KEY, code) or ""
db.hdel(GC_REDIS_KEY, code)
db.hdel(GC_TAGS_KEY, code)
# Track who used this code
db.hset(GC_USED_KEY, code, f"{user_id}:{int(time.time())}:{days}")
# Mark user as having redeemed a gift card (permanent record)
db.set(f"gc_redeemed_{user_id}", "1")
# Apply tag if gift card had one
if tag:
set_custom_tag(user_id, tag)
tag_info = f"\nTag: **{tag}**" if tag else ""
if days == 0:
grant_premium(user_id, 99999)
await m.reply(
f"Gift card redeemed!\n\n"
f"**Premium: Unlimited**\n"
f"Duration: Permanent (never expires){tag_info}",
parse_mode="markdown",
)
else:
grant_premium(user_id, days)
import time as _time
from datetime import datetime
expiry = int(_time.time()) + (days * 86400)
expiry_str = datetime.fromtimestamp(expiry).strftime("%d %b %Y, %I:%M %p")
await m.reply(
f"Gift card redeemed!\n\n"
f"**Premium: {days} day(s)**\n"
f"Expires: `{expiry_str}`{tag_info}",
parse_mode="markdown",
)
# Notify admins
user = await bot.get_entity(m.sender_id)
name = user.first_name
username = user.username if user.username else "-"
tag_msg = f"\nTag: {tag}" if tag else ""
for admin_id in get_all_admins():
await bot.send_message(
admin_id,
f"Gift Card Redeemed!\nUser: {name} (@{username})\nID: `{m.sender_id}`\nCode: `{code}`\nDuration: {days}d{tag_msg}"
)
# ==================== /allowredeem — OWNER RESETS USER GC REDEMPTION ====================
@bot.on(
events.NewMessage(
pattern=r"/allowredeem\s+(\d+)",
incoming=True,
outgoing=False,
from_users=[OWNER_ID],
)
)
async def allow_redeem(m: UpdateNewMessage):
user_id = m.pattern_match.group(1)
db.delete(f"gc_redeemed_{user_id}")
log_audit("ALLOW_REDEEM", m.sender_id, f"Reset GC redemption for {user_id}")
await m.reply(f"User `{user_id}` can now redeem another gift card.")
# ==================== /settag — SET CUSTOM TAG ====================
@bot.on(
events.NewMessage(
pattern=r"/settag\s+(\d+)\s+(.+)",
incoming=True,
outgoing=False,
func=lambda m: is_admin(m.sender_id),
)
)
async def set_tag_cmd(m: UpdateNewMessage):
user_id = int(m.pattern_match.group(1))
tag = m.pattern_match.group(2).strip()
set_custom_tag(user_id, tag)
log_audit("SET_TAG", m.sender_id, f"Set tag '{tag}' for {user_id}")
await m.reply(f"Tag set!\nUser: `{user_id}`\nTag: **{tag}**", parse_mode="markdown")
# ==================== /tag — VIEW YOUR TAG ====================
@bot.on(
events.NewMessage(
pattern="/tag",
incoming=True,
outgoing=False,
)
)
async def view_tag_cmd(m: UpdateNewMessage):
tag = get_custom_tag(m.sender_id)
if tag:
await m.reply(f"Your tag: **{tag}**", parse_mode="markdown")
else:
await m.reply("You have no custom tag.\nAdmins can set one with `/settag <user_id> <tag>`")
@bot.on(
events.NewMessage(
pattern="/broadcast",
incoming=True,
outgoing=False,
func=lambda m: is_admin(m.sender_id),
)
)
async def broadcast_message(m: UpdateNewMessage):
broadcast_text = m.text.split("/broadcast", 1)[1].strip()
if not broadcast_text:
return await m.reply(
"**Usage:** `/broadcast <message>`\n"
"Send a message to all bot users."
)
status = await m.reply("Broadcasting...")
all_users = await bot.get_participants(-1001336746488)
total = len(all_users)
sent = 0
failed = 0
for user in all_users:
try:
await bot.send_message(user.id, broadcast_text)
sent += 1
except Exception:
failed += 1
await status.edit(
f"**Broadcast Complete**\n\n"
f"Total users: **{total}**\n"
f"Sent: **{sent}**\n"
f"Failed: **{failed}**",
parse_mode="markdown",
)
# Define start command to check user's plan and send welcome message accordingly
# @bot.on(
# events.NewMessage(
# pattern="/start",
# incoming=True,
# outgoing=False,
# )
# )
# async def start(m: UpdateNewMessage):
# user_id = m.sender_id
# if db.sismember(PREMIUM_USERS_KEY, user_id):
# # Premium user
# reply_text = """
# ┏━━━━━━━━━━⍟
# ┃ 𝐍𝐓𝐌 𝐓𝐞𝐫𝐚 𝐁𝐨𝐱 𝐃𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐫 𝐁𝐨𝐭
# ┗━━━━━━━━━━━━━━━━━⍟
# ╔══════════⍟
# ┃🌟 Welcome! 🌟
# ┃
# ┃Excited to introduce Tera Box video downloader bot! 🤖
# ┃Simply share the terabox link, and voila!
# ┃Your desired video will swiftly start downloading.
# ┃It's that easy! 🚀
# ╚═════════════════⍟
# Do /help or /cmds - Display available commands.
# [『 𝗡⋆𝗧⋆𝗠 』](https://t.me/NTMpro)
# """
# else:
# # Free user
# reply_text = """
# ┏━━━━━━━━━━⍟
# ┃ 𝐅𝐑𝐄𝐄 𝐔𝐒𝐄𝐑
# ┗━━━━━━━━━━━━━━━━━⍟
# ╔══════════⍟
# ┃ As a free user,
# ┃ you're not approved to access the full capabilities of this bot.
# ┃
# ┃ Upgrade to premium or utilize /id, /cmds, or /help to view available details.
# ┃
# ┃ To check availabe plan do /plan in chat group @NTMchat
# ╚═════════════════⍟
# For subscription inquiries, contact @abdul97233.
# """
# # Send the welcome message
# check_if = await is_user_on_chat(bot, "@NTMpro", m.peer_id)
# if not check_if:
# return await m.reply("Please join @NTMpro then send me the link again.")
# await m.reply(reply_text, link_preview=False, parse_mode="markdown")
# ==================== /start — MODERN BUTTON MENU ====================
WELCOME_TEXT = """
┏━━━━━━━━━━━━━━━━━⍟
┃ 𝐍𝐓𝐌 𝐓𝐞𝐫𝐚 𝐁𝐨𝐱 𝐃𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐫
┗━━━━━━━━━━━━━━━━━━━━━⍟
👋 Welcome **{name}**!
Simply send me a **TeraBox link** and I'll download the video for you instantly.
⚡ Free: 10 downloads/hour
⭐ Premium: Unlimited + no limits
Choose an option below 👇
"""
@bot.on(
events.NewMessage(
pattern="/start",
incoming=True,
outgoing=False,
)
)
async def start(m: UpdateNewMessage):
user_id = m.sender_id
user = await bot.get_entity(user_id)
name = user.first_name
# Notify admins
admin_message = f"👤 New user started bot:\nName: {name}\nUsername: @{user.username or '-'}\nID: `{user_id}`"
for admin_id in get_all_admins():
try:
await bot.send_message(admin_id, admin_message)
except Exception:
pass
plan = "⭐ Premium" if is_premium_user(user_id) else "🆓 Free"
remaining = ""
if is_premium_user(user_id):
rem = get_premium_remaining(user_id)
if rem > 9000000:
remaining = " ♾️ Permanent"
else:
days = rem // 86400
hours = (rem % 86400) // 3600
remaining = f" ({days}d {hours}h left)"
text = WELCOME_TEXT.format(name=name)
buttons = [
[
Button.inline("📥 How to Use", data="menu_howto"),
Button.inline("📋 My Info", data="menu_info"),
],
[
Button.inline("⭐ Premium", data="menu_premium"),
Button.inline("🎁 Redeem Card", data="menu_redeem"),
],
[
Button.inline("🛠 Tools", data="menu_tools"),
Button.inline("🌐 Language", data="menu_lang"),
],
[
Button.url("📢 Channel", url="https://t.me/NTMpro"),
Button.url("💬 Group", url="https://t.me/NTMchat"),
],
]
if user_id in ADMINS:
buttons.insert(2, [
Button.inline("⚙️ Admin Panel", data="menu_admin"),
])
await m.reply(
text,
link_preview=False,
parse_mode="markdown",
buttons=buttons,
)
# ==================== CALLBACK HANDLERS ====================
@bot.on(events.CallbackQuery(data=b"menu_howto"))
async def cb_howto(e):
text = """
┏━━━━━━━━━━━━━━━━━⍟
┃ 📥 𝐇𝐨𝐰 𝐭𝐨 𝐔𝐬𝐞
┗━━━━━━━━━━━━━━━━━━━━━⍟
**Step 1:** Join our Channel & Group
**Step 2:** Send me any TeraBox link
**Step 3:** Wait for the magic! ✨
**Supported formats:**
mp4, mkv, webm, mov, avi, flv, wmv, m4v, mpg, mpeg, 3gp, ts, and more...
**Commands:**
`/dl <link>` — Download original
`/dl 720p <link>` — Download + compress 720p
`/dl 480p <link>` — Download + compress 480p
`/folder <link>` — Download entire folder