-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2249 lines (1956 loc) · 85.8 KB
/
bot.py
File metadata and controls
2249 lines (1956 loc) · 85.8 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
"""
BlockVeil Support Bot v4
========================
Changes in v4:
- Attachment screen: only "Skip" shown initially; "Done (Next)" appears only after
at least one attachment has been received
- One active ticket per user: a user cannot start a new ticket while one is in progress
(tracked via active_tickets table; cleared on submit or /cancel)
- Admin FAQ Manager: full add / edit / remove FAQ entries stored in DB;
user-facing FAQ reads from DB dynamically
- Statistics page: added "Download All Users" button -> sends a CSV file
containing username + user_id for every registered user
Deploy: Railway (Procfile -> worker: python bot.py)
Env vars: BOT_TOKEN, SUPPORT_GROUP_ID, BUG_FEATURE_GROUP_ID, DB_PATH (optional)
"""
import csv
import io
import asyncio
import os
import sqlite3
import logging
import zoneinfo
from datetime import datetime, timezone
from telegram import (
Update,
InlineKeyboardButton,
InlineKeyboardMarkup,
ReplyKeyboardRemove,
)
from telegram.ext import (
Application,
CommandHandler,
CallbackQueryHandler,
MessageHandler,
ConversationHandler,
filters,
ContextTypes,
)
from telegram.constants import ParseMode
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
BOT_TOKEN = os.environ["BOT_TOKEN"]
SUPPORT_GROUP_ID = int(os.environ["SUPPORT_GROUP_ID"])
BUG_FEATURE_GROUP_ID = int(os.environ["BUG_FEATURE_GROUP_ID"])
DB_PATH = os.environ.get("DB_PATH", "blockveil_support.db")
# ---------------------------------------------------------------------------
# Maintenance & Broadcast state
# ---------------------------------------------------------------------------
# In-memory maintenance flag (loaded from DB on startup, persisted on change)
_maintenance_on: bool = False
# Per-chat pending state for admin text-input flows (broadcast, set message, etc.)
_admin_pending: dict = {} # chat_id -> {"step": str, ...}
# ---------------------------------------------------------------------------
# Conversation States (user-side)
# ---------------------------------------------------------------------------
(
MAIN_MENU,
SELECT_APP,
DESCRIBE_ISSUE,
AWAIT_ATTACHMENT,
COLLECT_ATTACHMENT,
RATE_EXPERIENCE,
CONFIRM_SUBMIT,
BUG_FEATURE_DESCRIBE,
BUG_FEATURE_ATTACHMENT,
BUG_FEATURE_COLLECT,
BUG_FEATURE_SUBMIT,
TIMEZONE_INPUT,
) = range(12)
# Admin conversation states
(
ADMIN_DASHBOARD,
ADMIN_PRODUCT_LIST,
ADMIN_PRODUCT_ADD_NAME,
ADMIN_PRODUCT_DETAIL,
ADMIN_PRODUCT_EDIT_NAME,
ADMIN_FAQ_LIST,
ADMIN_FAQ_ADD_Q,
ADMIN_FAQ_ADD_A,
ADMIN_FAQ_DETAIL,
ADMIN_FAQ_EDIT_Q,
ADMIN_FAQ_EDIT_A,
ADMIN_MAINTENANCE_MSG,
ADMIN_BROADCAST,
ADMIN_BROADCAST_MSG,
) = range(20, 34)
TYPE_SUPPORT = "support"
TYPE_BUG = "bug"
TYPE_FEATURE = "feature"
POPULAR_TIMEZONES = [
("🇧🇩 Dhaka (UTC+6)", "Asia/Dhaka"),
("🇮🇳 Kolkata (UTC+5:30)", "Asia/Kolkata"),
("🇵🇰 Karachi (UTC+5)", "Asia/Karachi"),
("🇦🇪 Dubai (UTC+4)", "Asia/Dubai"),
("🇹🇷 Istanbul (UTC+3)", "Europe/Istanbul"),
("🇬🇧 London (UTC+0/1)", "Europe/London"),
("🇺🇸 New York (UTC-5/-4)", "America/New_York"),
("🇺🇸 Los Angeles (UTC-8)", "America/Los_Angeles"),
("🇸🇬 Singapore (UTC+8)", "Asia/Singapore"),
("🇯🇵 Tokyo (UTC+9)", "Asia/Tokyo"),
]
# ---------------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------------
def get_db() -> sqlite3.Connection:
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
return conn
def init_db() -> None:
with get_db() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
full_name TEXT NOT NULL,
username TEXT,
joined_at TEXT NOT NULL,
timezone TEXT DEFAULT 'Asia/Dhaka'
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ticket_id TEXT NOT NULL UNIQUE,
user_id INTEGER NOT NULL,
ticket_type TEXT NOT NULL,
app_name TEXT,
description TEXT,
rating INTEGER,
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS faq (
id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT NOT NULL,
answer TEXT NOT NULL,
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS active_tickets (
user_id INTEGER PRIMARY KEY,
started_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS bot_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
""")
conn.commit()
# Load persisted maintenance state into memory
_load_maintenance_state()
logger.info("Database initialized at %s", DB_PATH)
# --- User helpers ---
def upsert_user(user) -> None:
now_iso = datetime.now(timezone.utc).isoformat()
with get_db() as conn:
conn.execute("""
INSERT INTO users (user_id, full_name, username, joined_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
full_name = excluded.full_name,
username = excluded.username
""", (user.id, user.full_name, user.username, now_iso))
conn.commit()
def get_user_row(user_id: int):
with get_db() as conn:
return conn.execute("SELECT * FROM users WHERE user_id = ?", (user_id,)).fetchone()
def set_user_timezone(user_id: int, tz: str) -> None:
with get_db() as conn:
conn.execute("UPDATE users SET timezone = ? WHERE user_id = ?", (tz, user_id))
conn.commit()
def get_all_users():
with get_db() as conn:
return conn.execute("SELECT * FROM users ORDER BY joined_at DESC").fetchall()
# --- Ticket helpers ---
def save_ticket(ticket_id_str, user_id, ticket_type, app_name, description, rating) -> None:
now_iso = datetime.now(timezone.utc).isoformat()
with get_db() as conn:
conn.execute("""
INSERT INTO tickets (ticket_id, user_id, ticket_type, app_name, description, rating, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (ticket_id_str, user_id, ticket_type, app_name, description, rating, now_iso))
conn.commit()
def get_ticket_stats(user_id: int) -> dict:
with get_db() as conn:
row = conn.execute("""
SELECT
COUNT(*) AS total,
SUM(ticket_type='support') AS support_count,
SUM(ticket_type='bug') AS bug_count,
SUM(ticket_type='feature') AS feature_count
FROM tickets WHERE user_id = ?
""", (user_id,)).fetchone()
return {
"total": row["total"] or 0,
"support": row["support_count"] or 0,
"bug": row["bug_count"] or 0,
"feature": row["feature_count"] or 0,
}
def get_global_stats() -> dict:
with get_db() as conn:
t = conn.execute("""
SELECT
COUNT(*) AS total,
SUM(ticket_type='support') AS support_count,
SUM(ticket_type='bug') AS bug_count,
SUM(ticket_type='feature') AS feature_count
FROM tickets
""").fetchone()
u = conn.execute("SELECT COUNT(*) AS cnt FROM users").fetchone()
recent = conn.execute("""
SELECT t.ticket_id, t.ticket_type, t.app_name, t.created_at,
u.full_name, u.username
FROM tickets t LEFT JOIN users u ON t.user_id = u.user_id
ORDER BY t.created_at DESC LIMIT 5
""").fetchall()
return {
"total_tickets": t["total"] or 0,
"support": t["support_count"] or 0,
"bug": t["bug_count"] or 0,
"feature": t["feature_count"] or 0,
"total_users": u["cnt"] or 0,
"recent": recent,
}
def get_all_tickets(limit=20):
with get_db() as conn:
return conn.execute("""
SELECT t.*, u.full_name, u.username
FROM tickets t LEFT JOIN users u ON t.user_id = u.user_id
ORDER BY t.created_at DESC LIMIT ?
""", (limit,)).fetchall()
# --- Product helpers ---
def get_products():
with get_db() as conn:
return conn.execute("SELECT * FROM products ORDER BY created_at ASC").fetchall()
def add_product(name: str) -> bool:
"""Returns False if name already exists."""
try:
now_iso = datetime.now(timezone.utc).isoformat()
with get_db() as conn:
conn.execute("INSERT INTO products (name, created_at) VALUES (?, ?)", (name, now_iso))
conn.commit()
return True
except sqlite3.IntegrityError:
return False
def edit_product(product_id: int, new_name: str) -> bool:
try:
with get_db() as conn:
conn.execute("UPDATE products SET name = ? WHERE id = ?", (new_name, product_id))
conn.commit()
return True
except sqlite3.IntegrityError:
return False
def delete_product(product_id: int) -> None:
with get_db() as conn:
conn.execute("DELETE FROM products WHERE id = ?", (product_id,))
conn.commit()
def get_product_by_id(product_id: int):
with get_db() as conn:
return conn.execute("SELECT * FROM products WHERE id = ?", (product_id,)).fetchone()
# --- Active ticket lock helpers ---
def set_active_ticket(user_id: int) -> None:
"""Mark user as having an in-progress ticket."""
now_iso = datetime.now(timezone.utc).isoformat()
with get_db() as conn:
conn.execute("""
INSERT INTO active_tickets (user_id, started_at)
VALUES (?, ?)
ON CONFLICT(user_id) DO UPDATE SET started_at = excluded.started_at
""", (user_id, now_iso))
conn.commit()
def clear_active_ticket(user_id: int) -> None:
"""Remove the in-progress ticket lock for this user."""
with get_db() as conn:
conn.execute("DELETE FROM active_tickets WHERE user_id = ?", (user_id,))
conn.commit()
def has_active_ticket(user_id: int) -> bool:
with get_db() as conn:
row = conn.execute(
"SELECT 1 FROM active_tickets WHERE user_id = ?", (user_id,)
).fetchone()
return row is not None
# --- FAQ helpers ---
def get_faqs():
with get_db() as conn:
return conn.execute("SELECT * FROM faq ORDER BY id ASC").fetchall()
def get_faq_by_id(faq_id: int):
with get_db() as conn:
return conn.execute("SELECT * FROM faq WHERE id = ?", (faq_id,)).fetchone()
def add_faq(question: str, answer: str) -> None:
now_iso = datetime.now(timezone.utc).isoformat()
with get_db() as conn:
conn.execute(
"INSERT INTO faq (question, answer, created_at) VALUES (?, ?, ?)",
(question, answer, now_iso),
)
conn.commit()
def edit_faq(faq_id: int, question: str, answer: str) -> None:
with get_db() as conn:
conn.execute(
"UPDATE faq SET question = ?, answer = ? WHERE id = ?",
(question, answer, faq_id),
)
conn.commit()
def delete_faq(faq_id: int) -> None:
with get_db() as conn:
conn.execute("DELETE FROM faq WHERE id = ?", (faq_id,))
conn.commit()
# --- CSV export helper ---
def export_users_csv() -> bytes:
"""Return a UTF-8 CSV of all users as bytes: username, user_id, full_name, joined_at."""
users = get_all_users()
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["username", "user_id", "full_name", "joined_at"])
for u in users:
writer.writerow([
f"@{u['username']}" if u['username'] else "",
u['user_id'],
u['full_name'],
u['joined_at'][:19].replace("T", " "),
])
return buf.getvalue().encode("utf-8")
# --- Maintenance setting helpers ---
def _load_maintenance_state() -> None:
"""Load maintenance flag from DB into memory."""
global _maintenance_on
with get_db() as conn:
row = conn.execute(
"SELECT value FROM bot_settings WHERE key = 'maintenance'",
).fetchone()
_maintenance_on = (row["value"] == "1") if row else False
def _save_maintenance_state(value: bool) -> None:
global _maintenance_on
_maintenance_on = value
with get_db() as conn:
conn.execute(
"INSERT INTO bot_settings (key, value) VALUES ('maintenance', ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
("1" if value else "0",),
)
conn.commit()
def is_maintenance() -> bool:
return _maintenance_on
def get_maintenance_message() -> str:
"""Return admin-set maintenance message or a sensible default."""
with get_db() as conn:
row = conn.execute(
"SELECT value FROM bot_settings WHERE key = 'maintenance_message'",
).fetchone()
if row and row["value"]:
return row["value"]
return (
"🔧 *BlockVeil Support is under maintenance.*\n\n"
"We are making improvements to serve you better.\n"
"Please check back soon. Thank you for your patience!"
)
def save_maintenance_message(text: str) -> None:
with get_db() as conn:
conn.execute(
"INSERT INTO bot_settings (key, value) VALUES ('maintenance_message', ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(text,),
)
conn.commit()
# --- Broadcast helper ---
async def auto_delete_msg(message, delay: int = 30) -> None:
"""Delete a message after `delay` seconds. Used to keep the admin group clean."""
await asyncio.sleep(delay)
try:
await message.delete()
except Exception:
pass
# ---------------------------------------------------------------------------
# Utility helpers
# ---------------------------------------------------------------------------
def username_display(user) -> str:
return f"@{user.username}" if user.username else user.full_name
def gen_ticket_id(user_id: int) -> str:
ts = datetime.now(timezone.utc).strftime("%y%m%d%H%M")
return f"BV-{ts}-{user_id % 10000:04d}"
def stars(n: int) -> str:
return "★" * n + "☆" * (5 - n)
def format_date(iso_str: str, tz_name: str = "UTC") -> str:
try:
dt = datetime.fromisoformat(iso_str).astimezone(zoneinfo.ZoneInfo(tz_name))
return dt.strftime("%-d %B %Y")
except Exception:
return iso_str[:10]
def is_private(update: Update) -> bool:
return update.effective_chat and update.effective_chat.type == "private"
def is_admin_group(update: Update) -> bool:
return update.effective_chat and update.effective_chat.id == BUG_FEATURE_GROUP_ID
# ---------------------------------------------------------------------------
# User-side Keyboards
# ---------------------------------------------------------------------------
def make_main_menu_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("🛟 Need Support", callback_data="menu_support")],
[InlineKeyboardButton("🐛 Report Bug", callback_data="menu_bug"),
InlineKeyboardButton("💡 Request Feature", callback_data="menu_feature")],
[InlineKeyboardButton("🎫 View My Tickets", callback_data="menu_tickets"),
InlineKeyboardButton("❓ FAQ", callback_data="menu_faq")],
[InlineKeyboardButton("👤 Profile", callback_data="menu_profile")],
])
def make_product_select_keyboard(flow: str) -> InlineKeyboardMarkup:
"""
Build dynamic product buttons for Support or Bug flow.
flow = 'support' -> callback prefix 'app_'
flow = 'bug' -> callback prefix 'bugapp_'
Always appends an 'Others' button and a Back button.
"""
prefix = "app_" if flow == TYPE_SUPPORT else "bugapp_"
rows = []
for p in get_products():
safe_name = p["name"].replace(" ", "_")
rows.append([InlineKeyboardButton(
f"📦 {p['name']}",
callback_data=f"{prefix}prod_{p['id']}_{safe_name}"
)])
rows.append([InlineKeyboardButton("🔧 Others", callback_data=f"{prefix}others")])
rows.append([InlineKeyboardButton("⬅️ Back", callback_data="back_main")])
return InlineKeyboardMarkup(rows)
def make_next_keyboard(cb: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[InlineKeyboardButton("➡️ Next", callback_data=cb)]])
def make_skip_only_keyboard() -> InlineKeyboardMarkup:
"""Shown before any attachment is received: only Skip."""
return InlineKeyboardMarkup([[
InlineKeyboardButton("⏭️ Skip", callback_data="skip_attachment"),
]])
def make_skip_done_keyboard() -> InlineKeyboardMarkup:
"""Shown after at least one attachment is received: Skip + Done."""
return InlineKeyboardMarkup([[
InlineKeyboardButton("⏭️ Skip", callback_data="skip_attachment"),
InlineKeyboardButton("✅ Done (Next)", callback_data="done_attachment"),
]])
def make_rating_keyboard() -> InlineKeyboardMarkup:
rows = [[InlineKeyboardButton(stars(i), callback_data=f"rate_{i}")] for i in range(1, 6)]
rows.append([InlineKeyboardButton("➡️ Next (No Rating)", callback_data="rate_skip")])
return InlineKeyboardMarkup(rows)
def make_submit_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("📨 Submit Ticket", callback_data="submit_confirm")],
[InlineKeyboardButton("❌ Cancel", callback_data="back_main")],
])
def make_timezone_keyboard() -> InlineKeyboardMarkup:
rows = [[InlineKeyboardButton(label, callback_data=f"tz_{key}")] for label, key in POPULAR_TIMEZONES]
rows.append([InlineKeyboardButton("⬅️ Back to Profile", callback_data="back_profile")])
return InlineKeyboardMarkup(rows)
def make_back_main_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[InlineKeyboardButton("🏠 Main Menu", callback_data="back_main")]])
def make_back_profile_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Back to Profile", callback_data="back_profile")]])
# ---------------------------------------------------------------------------
# Admin Keyboards
# ---------------------------------------------------------------------------
def make_admin_dashboard_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("👥 User Info", callback_data="adm_user_info"),
InlineKeyboardButton("🔧 Maintenance", callback_data="adm_maintenance")],
[InlineKeyboardButton("📢 Broadcast", callback_data="adm_broadcast"),
InlineKeyboardButton("🛡️ User Control", callback_data="adm_user_control")],
[InlineKeyboardButton("📊 Statistics", callback_data="adm_statistics"),
InlineKeyboardButton("📦 Product", callback_data="adm_product")],
[InlineKeyboardButton("❓ FAQ", callback_data="adm_faq"),
InlineKeyboardButton("🎫 Ticket Info", callback_data="adm_ticket_info")],
[InlineKeyboardButton("💾 Backup", callback_data="adm_backup")],
])
def make_product_list_keyboard() -> InlineKeyboardMarkup:
"""Show all existing products as buttons + Add New Product + Back."""
rows = []
for p in get_products():
rows.append([InlineKeyboardButton(
f"📦 {p['name']}",
callback_data=f"adm_prod_detail_{p['id']}"
)])
rows.append([InlineKeyboardButton("➕ Add New Product", callback_data="adm_prod_add")])
rows.append([InlineKeyboardButton("⬅️ Back", callback_data="adm_back_dash")])
return InlineKeyboardMarkup(rows)
def make_product_detail_keyboard(product_id: int) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("✏️ Edit", callback_data=f"adm_prod_edit_{product_id}"),
InlineKeyboardButton("🗑️ Remove", callback_data=f"adm_prod_remove_{product_id}")],
[InlineKeyboardButton("⬅️ Back", callback_data="adm_product")],
])
def make_admin_back_keyboard() -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Back to Dashboard", callback_data="adm_back_dash")]])
def make_faq_list_keyboard() -> InlineKeyboardMarkup:
"""All FAQ entries as buttons + Add New + Back."""
rows = []
for f in get_faqs():
short_q = f["question"][:40] + ("..." if len(f["question"]) > 40 else "")
rows.append([InlineKeyboardButton(
f"❓ {short_q}",
callback_data=f"adm_faq_detail_{f['id']}"
)])
rows.append([InlineKeyboardButton("➕ Add New FAQ", callback_data="adm_faq_add")])
rows.append([InlineKeyboardButton("⬅️ Back", callback_data="adm_back_dash")])
return InlineKeyboardMarkup(rows)
def make_faq_detail_keyboard(faq_id: int) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("✏️ Edit", callback_data=f"adm_faq_edit_{faq_id}"),
InlineKeyboardButton("🗑️ Remove", callback_data=f"adm_faq_remove_{faq_id}")],
[InlineKeyboardButton("⬅️ Back", callback_data="adm_faq")],
])
# ---------------------------------------------------------------------------
# /start (routes by chat type)
# ---------------------------------------------------------------------------
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
chat = update.effective_chat
# In any group that is NOT the admin group -> silently ignore
if chat.type != "private" and chat.id != BUG_FEATURE_GROUP_ID:
return ConversationHandler.END
# Admin dashboard in BUG_FEATURE_GROUP
if chat.id == BUG_FEATURE_GROUP_ID:
context.user_data.clear()
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
stats = get_global_stats()
text = (
"🔐 *BlockVeil Admin Dashboard*\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"🕐 {now}\n"
f"👥 Total Users: {stats['total_users']}\n"
f"🎫 Total Tickets: {stats['total_tickets']}\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"Select a section below:"
)
await update.message.reply_text(
text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_admin_dashboard_keyboard(),
)
return ADMIN_DASHBOARD
# Private chat -> user main menu
context.user_data.clear()
user = update.effective_user
upsert_user(user)
# Block users when maintenance is active
if is_maintenance():
await update.message.reply_text(
get_maintenance_message(),
parse_mode=ParseMode.MARKDOWN,
)
return ConversationHandler.END
await update.message.reply_text(
f"👋 *Welcome to BlockVeil Support, {user.first_name}!*\n\n"
"We are here to help you. Select an option below:",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_main_menu_keyboard(),
)
return MAIN_MENU
# ---------------------------------------------------------------------------
# Admin Dashboard Callbacks
# ---------------------------------------------------------------------------
async def admin_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
data = query.data
# --- Back to dashboard ---
if data == "adm_back_dash":
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
stats = get_global_stats()
await query.edit_message_text(
"🔐 *BlockVeil Admin Dashboard*\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"🕐 {now}\n"
f"👥 Total Users: {stats['total_users']}\n"
f"🎫 Total Tickets: {stats['total_tickets']}\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"Select a section below:",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_admin_dashboard_keyboard(),
)
return ADMIN_DASHBOARD
# --- User Info ---
if data == "adm_user_info":
users = get_all_users()
if not users:
body = "_No users registered yet._"
else:
lines = []
for u in users[:20]:
uname = f"@{u['username']}" if u['username'] else u['full_name']
date = u['joined_at'][:10]
lines.append(f"• {uname} (`{u['user_id']}`) — Joined: {date}")
body = "\n".join(lines)
if len(users) > 20:
body += f"\n\n_...and {len(users) - 20} more._"
await query.edit_message_text(
f"👥 *User Info*\n"
f"━━━━━━━━━━━━━━━━━━━━\n"
f"Total registered: {len(users)}\n\n"
f"{body}",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_admin_back_keyboard(),
)
return ADMIN_DASHBOARD
# --- Statistics ---
if data == "adm_statistics":
s = get_global_stats()
recent_lines = []
for r in s["recent"]:
uname = f"@{r['username']}" if r['username'] else r['full_name'] or "Unknown"
recent_lines.append(
f"• `{r['ticket_id']}` | {r['ticket_type'].upper()} | {uname}"
)
recent_text = "\n".join(recent_lines) if recent_lines else "_No tickets yet._"
await query.edit_message_text(
"📊 *Statistics*\n"
"━━━━━━━━━━━━━━━━━━━━\n"
f"👥 Total Users: {s['total_users']}\n"
f"🎫 Total Tickets: {s['total_tickets']}\n"
f"🛟 Support: {s['support']}\n"
f"🐛 Bug Reports: {s['bug']}\n"
f"💡 Feature Reqs: {s['feature']}\n\n"
f"*Recent Tickets:*\n{recent_text}",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("📥 Download All Users (CSV)", callback_data="adm_download_users")],
[InlineKeyboardButton("⬅️ Back to Dashboard", callback_data="adm_back_dash")],
]),
)
return ADMIN_DASHBOARD
# --- Download All Users CSV ---
if data == "adm_download_users":
users = get_all_users()
if not users:
await query.answer("No users to export.", show_alert=True)
return ADMIN_DASHBOARD
csv_bytes = export_users_csv()
now_str = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M")
filename = f"blockveil_users_{now_str}.csv"
await context.bot.send_document(
chat_id=query.message.chat_id,
document=io.BytesIO(csv_bytes),
filename=filename,
caption=f"👥 *All Users Export*\n{len(users)} users | {now_str} UTC",
parse_mode=ParseMode.MARKDOWN,
)
await query.answer("CSV sent above.", show_alert=False)
return ADMIN_DASHBOARD
# --- Ticket Info ---
if data == "adm_ticket_info":
tickets = get_all_tickets(15)
if not tickets:
body = "_No tickets found._"
else:
lines = []
for t in tickets:
uname = f"@{t['username']}" if t['username'] else t['full_name'] or "Unknown"
lines.append(
f"• `{t['ticket_id']}` [{t['ticket_type'].upper()}]\n"
f" User: {uname} | App: {t['app_name'] or 'N/A'}\n"
f" Date: {t['created_at'][:10]}"
)
body = "\n\n".join(lines)
await query.edit_message_text(
f"🎫 *Ticket Info* (last 15)\n━━━━━━━━━━━━━━━━━━━━\n\n{body}",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_admin_back_keyboard(),
)
return ADMIN_DASHBOARD
# --- Maintenance ---
if data == "adm_maintenance":
return await adm_maintenance_cb(update, context)
# --- Maintenance toggle ---
if data == "adm_maintenance_toggle":
return await adm_maintenance_toggle_cb(update, context)
# --- Maintenance set message ---
if data == "adm_maintenance_set_msg":
return await adm_maintenance_set_msg_cb(update, context)
# --- Broadcast ---
if data == "adm_broadcast":
return await adm_broadcast_cb(update, context)
# --- User Control ---
if data == "adm_user_control":
await query.edit_message_text(
"🛡️ *User Control*\n━━━━━━━━━━━━━━━━━━━━\n\n"
"User ban, unban, and restriction controls are coming soon.",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_admin_back_keyboard(),
)
return ADMIN_DASHBOARD
# --- FAQ Manager (routes to ADMIN_FAQ_LIST state) ---
if data == "adm_faq":
faqs = get_faqs()
count = len(faqs)
await query.edit_message_text(
f"❓ *FAQ Manager*\n━━━━━━━━━━━━━━━━━━━━\n\n"
f"Total FAQ entries: {count}\n\n"
"Tap an entry to edit or remove it, or add a new one.",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_faq_list_keyboard(),
)
return ADMIN_FAQ_LIST
# --- Backup ---
if data == "adm_backup":
await query.edit_message_text(
"💾 *Backup*\n━━━━━━━━━━━━━━━━━━━━\n\n"
f"Database file: `{DB_PATH}`\n\n"
"Automated backup scheduling is coming soon.\n"
"For now, download the SQLite file from your Railway volume.",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_admin_back_keyboard(),
)
return ADMIN_DASHBOARD
# --- Product list ---
if data == "adm_product":
products = get_products()
count = len(products)
await query.edit_message_text(
f"📦 *Product Manager*\n━━━━━━━━━━━━━━━━━━━━\n\n"
f"Total products: {count}\n\n"
"Tap a product to edit or remove it.\n"
"Products appear as buttons inside Need Support and Report Bug flows.",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_product_list_keyboard(),
)
return ADMIN_PRODUCT_LIST
return ADMIN_DASHBOARD
# --- Product List callbacks ---
async def admin_product_list_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
data = query.data
if data == "adm_back_dash":
return await admin_callback(update, context) # Re-use back-to-dash handler
# Add new product
if data == "adm_prod_add":
await query.edit_message_text(
"📦 *Add New Product*\n━━━━━━━━━━━━━━━━━━━━\n\n"
"Send the product name you want to add.\n\n"
"_Example: BlockVeil Wallet_",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton("❌ Cancel", callback_data="adm_product")
]]),
)
return ADMIN_PRODUCT_ADD_NAME
# View product detail
if data.startswith("adm_prod_detail_"):
pid = int(data.split("_")[-1])
prod = get_product_by_id(pid)
if not prod:
await query.edit_message_text(
"Product not found.",
reply_markup=make_product_list_keyboard(),
)
return ADMIN_PRODUCT_LIST
await query.edit_message_text(
f"📦 *Product: {prod['name']}*\n━━━━━━━━━━━━━━━━━━━━\n\n"
f"ID: `{prod['id']}`\n"
f"Added: {prod['created_at'][:10]}\n\n"
"Choose an action:",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_product_detail_keyboard(pid),
)
return ADMIN_PRODUCT_DETAIL
return ADMIN_PRODUCT_LIST
async def admin_product_add_name(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Admin sends product name text."""
name = update.message.text.strip()
if not name:
await update.message.reply_text(
"Product name cannot be empty. Please try again.",
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton("❌ Cancel", callback_data="adm_product")
]]),
)
return ADMIN_PRODUCT_ADD_NAME
success = add_product(name)
if not success:
await update.message.reply_text(
f"❌ A product named *{name}* already exists.\n\nTry a different name:",
parse_mode=ParseMode.MARKDOWN,
)
return ADMIN_PRODUCT_ADD_NAME
products = get_products()
await update.message.reply_text(
f"✅ *Product Added:* {name}\n\n"
f"Total products: {len(products)}\n\n"
"It will now appear in user support and bug report flows.",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("📦 Back to Products", callback_data="adm_product")],
[InlineKeyboardButton("🏠 Dashboard", callback_data="adm_back_dash")],
]),
)
return ADMIN_PRODUCT_LIST
async def admin_product_detail_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
data = query.data
if data == "adm_product":
products = get_products()
await query.edit_message_text(
f"📦 *Product Manager*\n━━━━━━━━━━━━━━━━━━━━\n\n"
f"Total products: {len(products)}\n\n"
"Tap a product to edit or remove it.",
parse_mode=ParseMode.MARKDOWN,
reply_markup=make_product_list_keyboard(),
)
return ADMIN_PRODUCT_LIST
# Edit
if data.startswith("adm_prod_edit_"):
pid = int(data.split("_")[-1])
prod = get_product_by_id(pid)
context.user_data["editing_product_id"] = pid
await query.edit_message_text(
f"✏️ *Edit Product: {prod['name']}*\n━━━━━━━━━━━━━━━━━━━━\n\n"
"Send the new product name:",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton("❌ Cancel", callback_data="adm_product")
]]),
)
return ADMIN_PRODUCT_EDIT_NAME
# Remove
if data.startswith("adm_prod_remove_"):
pid = int(data.split("_")[-1])
prod = get_product_by_id(pid)
name = prod["name"] if prod else "Unknown"
delete_product(pid)
products = get_products()
await query.edit_message_text(
f"🗑️ *Product Removed:* {name}\n\n"