-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsuperadmin.py
More file actions
234 lines (198 loc) · 8.98 KB
/
superadmin.py
File metadata and controls
234 lines (198 loc) · 8.98 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
from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import ConversationHandler, ContextTypes
import strings
import keyboards
import states
from database import db
import psutil
import time
import logging
import asyncio
logger = logging.getLogger(__name__)
# --- HELPERS ---
def get_user_lang(context: ContextTypes.DEFAULT_TYPE):
return context.user_data.get('lang', strings.DEFAULT_LANG)
async def run_db_call(func, *args, **kwargs):
return await asyncio.to_thread(func, *args, **kwargs)
def get_super_menu(lang='EN'):
return ReplyKeyboardMarkup([
[strings.get('BTN_SA_MAINTENANCE', lang), strings.get('BTN_SA_REFRESH', lang)],
[strings.get('BTN_SA_ADMINS', lang), strings.get('BTN_SA_HEALTH', lang)],
[strings.get('BTN_SA_LOGS', lang)],
[strings.get('BTN_SA_EXIT', lang)]
], resize_keyboard=True)
# --- START ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
user_id = update.effective_user.id
is_sa = db.is_superadmin(user_id)
logger.info(f"DEBUG: /superadmin attempt by {user_id}. Is SA? {is_sa}. SA List: {db.superadmin_ids}")
if not is_sa:
# Security: Silent fail for non-superadmins
return ConversationHandler.END
# Sync config in background so UI pops immediately
# We rely on cache for immediate display. The refresh happens for NEXT time.
# Or we can await loop.run_in_executor(None, db.refresh_system_config)
# But even that awaits.
# FASTEST: Just trigger it and don't wait. Or trust the background job.
# Let's trust cache. If it's stale, it updates in background.
# For now, let's just make it non-blocking fire-and-forget style or short timeout?
# Actually, asyncio.to_thread is good for Py3.9+.
# Since we want speed, let's skip the forced refresh here and rely on the background job?
# But we don't have a background job for config refresh yet (only check_registrations).
# Let's add loop.run_in_executor.
loop = asyncio.get_running_loop()
loop.run_in_executor(None, db.refresh_system_config)
lang = get_user_lang(context)
status = "ON" if db.maintenance_mode else "OFF"
await update.message.reply_text(
f"*Superadmin Dashboard*\n\nMaintenance Mode: {status}",
parse_mode="Markdown",
reply_markup=get_super_menu(lang)
)
return states.SUPER_MENU
# --- FEATURES ---
async def refresh_config(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await run_db_call(db.refresh_system_config, force=True)
lang = get_user_lang(context)
await update.message.reply_text(strings.get('MSG_CONFIG_REFRESHED', lang), parse_mode="Markdown")
return states.SUPER_MENU
async def check_health(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
cpu = psutil.cpu_percent()
ram = psutil.virtual_memory().percent
uptime = time.time() - psutil.boot_time()
# Format uptime roughly
hours = int(uptime // 3600)
mins = int((uptime % 3600) // 60)
msg = (
f"*System Health*\n\n"
f"CPU: *{cpu}%*\n"
f"RAM: *{ram}%*\n"
f"Uptime: ~*{hours}h* *{mins}m*"
)
await update.message.reply_text(msg, parse_mode="Markdown")
return states.SUPER_MENU
async def toggle_maintenance(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
new_state = not db.maintenance_mode
if await run_db_call(db.set_maintenance, new_state):
status = "ENABLED" if new_state else "DISABLED"
await update.message.reply_text(f"Maintenance Mode: *{status}*", parse_mode="Markdown")
else:
await update.message.reply_text("❌ Failed to update config.")
return states.SUPER_MENU
async def view_logs(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
try:
await update.message.reply_document(
document=open("activity.log", "rb"),
filename="activity.txt"
)
except FileNotFoundError:
await update.message.reply_text("📂 Log file is empty or missing.")
except Exception as e:
logger.error(e)
await update.message.reply_text("❌ Error reading logs.")
return states.SUPER_MENU
# --- ADMIN MANAGEMENT ---
# --- MENUS ---
def get_manage_admins_menu(lang='EN'):
return ReplyKeyboardMarkup([
[strings.get('BTN_SA_ADD_ADMIN', lang), strings.get('BTN_SA_DEL_ADMIN', lang)],
[strings.get('BTN_SA_LIST_ADMIN', lang)],
[strings.get('BTN_BACK', lang)]
], resize_keyboard=True)
# --- ADMIN MANAGEMENT ---
async def manage_admins(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
await update.message.reply_text(
strings.get('BTN_SA_ADMINS', lang), # Use button label as title
reply_markup=get_manage_admins_menu(lang)
)
return states.SUPER_ADMIN_MANAGE
# --- SUBMENU ACTIONS ---
async def list_admins(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
admins = db.cached_sheet_admins
if not admins:
msg = "No secondary admins found."
else:
msg = f"*Secondary Admins ({len(admins)}):*\n" + "\n".join([f"`{a}`" for a in admins])
await update.message.reply_text(msg, parse_mode="Markdown")
return states.SUPER_ADMIN_MANAGE
async def add_admin_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
await update.message.reply_text(
strings.get('PROMPT_SA_ADD', lang),
parse_mode="Markdown",
reply_markup=keyboards.get_cancel_menu(lang)
)
return states.SUPER_ADD_ID
async def add_admin_save(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
text = update.message.text.strip()
if not text.isdigit():
await update.message.reply_text(strings.get('ERR_SA_INVALID_ID', lang), parse_mode="Markdown")
return states.SUPER_ADD_ID
user_id = int(text)
# Check if already admin
if db.is_admin(user_id):
await update.message.reply_text(
strings.get('ERR_SA_ALREADY_ADMIN', lang),
parse_mode="Markdown",
reply_markup=get_manage_admins_menu(lang)
)
return states.SUPER_ADMIN_MANAGE
# Add to sheet
if await run_db_call(db.add_admin, user_id, "Unknown", f"SA:{update.effective_user.id}"):
await update.message.reply_text(strings.get('MSG_SA_ADDED', lang), parse_mode="Markdown", reply_markup=get_manage_admins_menu(lang))
# Notify the new admin
try:
await context.bot.send_message(
chat_id=user_id,
text=strings.get('MSG_SA_PROMOTED', lang),
parse_mode="Markdown"
)
except Exception as e:
logger.warning(f"Failed to notify new admin {user_id}: {e}")
db.log_action(update.effective_user.first_name, "ADD_ADMIN", f"Promoted User {user_id}")
return states.SUPER_ADMIN_MANAGE
else:
await update.message.reply_text("❌ DB Error", reply_markup=get_manage_admins_menu(lang))
return states.SUPER_ADMIN_MANAGE
async def del_admin_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
await update.message.reply_text(
strings.get('PROMPT_SA_DEL', lang),
parse_mode="Markdown",
reply_markup=keyboards.get_cancel_menu(lang)
)
return states.SUPER_DEL_ID
async def del_admin_perform(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
text = update.message.text.strip()
if not text.isdigit():
await update.message.reply_text(strings.get('ERR_SA_INVALID_ID', lang), parse_mode="Markdown")
return states.SUPER_DEL_ID
user_id = int(text)
if await run_db_call(db.remove_admin, user_id):
db.log_action(update.effective_user.first_name, "REMOVE_ADMIN", f"Demoted User {user_id}")
await update.message.reply_text(strings.get('MSG_SA_DELETED', lang), parse_mode="Markdown", reply_markup=get_manage_admins_menu(lang))
else:
await update.message.reply_text("❌ Not found or Error", reply_markup=get_manage_admins_menu(lang))
return states.SUPER_ADMIN_MANAGE
async def back_to_manage(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
await update.message.reply_text(
strings.get('ERR_CANCEL', lang),
reply_markup=get_manage_admins_menu(lang)
)
return states.SUPER_ADMIN_MANAGE
async def back_to_super(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
await update.message.reply_text(
"🔙 Superadmin Dashboard",
reply_markup=get_super_menu(lang)
)
return states.SUPER_MENU
async def exit(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
lang = get_user_lang(context)
await update.message.reply_text("Superadmin closed.", reply_markup=keyboards.get_main_menu(lang))
return ConversationHandler.END