-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
783 lines (647 loc) · 31.5 KB
/
bot.py
File metadata and controls
783 lines (647 loc) · 31.5 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
#!/usr/bin/env python3
"""
Server Control Telegram Bot
Управление сервером через Telegram
"""
import subprocess
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, Defaults, MessageHandler, filters, JobQueue
# ========== НАСТРОЙКИ ==========
# Импорт из config.py
try:
from config import BOT_TOKEN, OWNER_ID, ALLOWED_USERS
except ImportError:
print("❌ Ошибка: Создайте config.py или установите BOT_TOKEN")
BOT_TOKEN = None
OWNER_ID = 0
ALLOWED_USERS = []
# ========== ЛОГИРОВАНИЕ ==========
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# ========== ПРОВЕРКА ДОСТУПА ==========
def is_authorized(user_id):
"""Проверка доступа пользователя"""
return user_id in ALLOWED_USERS
# ========== КОМАНДЫ ==========
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Приветствие"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
await update.message.reply_text(
f"👋 Привет, {update.effective_user.first_name}!\n\n"
"🛠️ **Команды управления сервером:**\n\n"
"📊 **Информация:**\n"
"/status - Статус сервера\n"
"/services - Список служб\n"
"/disk - Место на диске\n"
"/ram - Использование RAM\n"
"/logs - Последние логи\n"
"/backups - Последние бэкапы\n\n"
"⚙️ **Управление службами:**\n"
"/restart <service> - Перезапустить службу\n"
"/start <service> - Запустить службу\n"
"/stop <service> - Остановить службу\n\n"
"🔒 **Безопасность:**\n"
"/fail2ban - Статус Fail2ban\n"
"/ssh - Статус SSH\n\n"
"🔄 **Бэкапы:**\n"
"/backup - Создать бэкап\n\n"
"🔧 **Система:**\n"
"/reboot - Перезагрузка сервера\n"
"/ping - Проверка связи\n"
"/whoami - Информация о пользователе\n\n"
"❓ **Помощь:**\n"
"/help - Список команд"
)
async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Помощь"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
help_text = """
📋 **Список команд:**
**📊 Информация:**
/status - Статус сервера (CPU, RAM, диск, uptime)
/services - Активные службы
/disk - Место на диске
/ram - Использование оперативной памяти
/logs [lines] - Последние логи (по умолчанию 10)
/backups - Последние бэкапы
**📈 Мониторинг:**
/top - Топ процессов по CPU
/network - Статистика сети (порты, интерфейсы)
/domains - Список доменов (nginx)
**⚙️ Управление службами:**
/restart <service> - Перезапустить службу
/start <service> - Запустить службу
/stop <service> - Остановить службу
/enable <service> - Включить в автозапуск
/disable <service> - Отключить из автозапуска
/logs <service> [lines] - Логи службы
/journal <service> [lines] - Журнал systemd службы
*Примеры:*
/restart telegrab
/stop unisignal
/start postgresql
/logs telegrab 50
/journal ssh 30
**🔒 Безопасность:**
/fail2ban - Статус Fail2ban (заблокированные IP)
/ssh - Статус SSH (активные сессии)
**💾 Бэкапы:**
/backup - Создать полный бэкап
**🔧 Система:**
/ping - Проверка связи
/whoami - Информация о пользователе
/reboot - Перезагрузка сервера
/help - Эта справка
**📥 Загрузка файлов:**
Просто отправьте боту файл/фото/аудио/видео — он сохранит в `/root/share/`
"""
await update.message.reply_text(help_text)
async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Статус сервера"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
# Uptime
uptime = subprocess.check_output(
"/usr/bin/uptime -p",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
# Load average
uptime_full = subprocess.check_output(
"/usr/bin/uptime",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
load = uptime_full.split("load average:")[1].strip()
# CPU info
cpu = subprocess.check_output(
"/usr/bin/nproc",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
# RAM
free = subprocess.check_output(
"/usr/bin/free -h",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
ram_line = free.split("\n")[1]
# Disk
disk = subprocess.check_output(
"/bin/df -h / | /usr/bin/tail -1",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
disk_parts = disk.split()
disk_used = disk_parts[2]
disk_avail = disk_parts[3]
disk_percent = disk_parts[4]
status = f"""
🖥️ **Статус сервера**
⏱️ **Uptime:** {uptime}
📊 **Load Average:** {load}
🔢 **CPU Cores:** {cpu}
💾 **RAM:**
{ram_line}
💿 **Диск:**
Использовано: {disk_used}
Свободно: {disk_avail} ({disk_percent})
✅ Все службы работают нормально
"""
await update.message.reply_text(status)
except Exception as e:
logger.error(f"Error in cmd_status: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_services(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Список служб"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
services = ["ssh", "postgresql", "telegrab", "unisignal", "fail2ban", "ufw"]
result = ""
for service in services:
try:
status = subprocess.check_output(
f"/usr/bin/systemctl is-active {service}",
shell=True, stderr=subprocess.DEVNULL, env={'PATH': '/usr/bin:/bin'}
).decode().strip()
icon = "✅" if status == "active" else "❌"
result += f"{icon} **{service}:** {status}\n"
except Exception as e:
result += f"❓ **{service}:** неизвестно (ошибка: {e})\n"
await update.message.reply_text(f"📋 **Службы:**\n\n{result}")
except Exception as e:
logger.error(f"Error in cmd_services: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_disk(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Место на диске"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
disk = subprocess.check_output(
"/bin/df -h",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"💿 **Диск:**\n```\n{disk}\n```")
except Exception as e:
logger.error(f"Error in cmd_disk: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_ram(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Использование RAM"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
ram = subprocess.check_output(
"/usr/bin/free -h",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"💾 **RAM:**\n```\n{ram}\n```")
except Exception as e:
logger.error(f"Error in cmd_ram: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Последние логи"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
lines = context.args[0] if context.args else "10"
# Используем stderr=subprocess.STDOUT чтобы игнорировать exit code
logs = subprocess.run(
f"/usr/bin/journalctl -p 3 -xb --no-pager --lines={lines}",
shell=True,
capture_output=True,
text=True,
env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).stdout.strip()
if not logs:
logs = "✅ Ошибок не найдено"
await update.message.reply_text(f"📝 **Логи (последние {lines}):**\n```\n{logs}\n```")
except Exception as e:
logger.error(f"Error in cmd_logs: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_backups(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Последние бэкапы"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
backups = subprocess.check_output(
"/bin/ls -lht /root/backups/ | /usr/bin/head -10",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"📦 **Последние бэкапы:**\n```\n{backups}\n```")
except Exception as e:
logger.error(f"Error in cmd_backups: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_restart(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Перезапуск службы"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /restart <service>")
return
service = context.args[0]
try:
subprocess.check_output(
f"/usr/bin/systemctl restart {service}",
shell=True, stderr=subprocess.STDOUT, env={'PATH': '/usr/bin:/bin'}
).decode()
await update.message.reply_text(f"✅ Служба **{service}** перезапущена")
except Exception as e:
logger.error(f"Error in cmd_restart: {e}")
await update.message.reply_text(f"❌ Ошибка перезапуска {service}: {e}")
async def cmd_start_service(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Запуск службы"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /start <service>")
return
service = context.args[0]
try:
subprocess.check_output(
f"/usr/bin/systemctl start {service}",
shell=True, stderr=subprocess.STDOUT, env={'PATH': '/usr/bin:/bin'}
).decode()
await update.message.reply_text(f"✅ Служба **{service}** запущена")
except Exception as e:
logger.error(f"Error in cmd_start: {e}")
await update.message.reply_text(f"❌ Ошибка запуска {service}: {e}")
async def cmd_stop_service(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Остановка службы"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /stop <service>")
return
service = context.args[0]
try:
subprocess.check_output(
f"/usr/bin/systemctl stop {service}",
shell=True, stderr=subprocess.STDOUT, env={'PATH': '/usr/bin:/bin'}
).decode()
await update.message.reply_text(f"✅ Служба **{service}** остановлена")
except Exception as e:
logger.error(f"Error in cmd_stop: {e}")
await update.message.reply_text(f"❌ Ошибка остановки {service}: {e}")
async def cmd_fail2ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Статус Fail2ban"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
status = subprocess.check_output(
"/usr/bin/fail2ban-client status",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
sshd = subprocess.check_output(
"/usr/bin/fail2ban-client status sshd",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"🛡️ **Fail2ban:**\n```\n{status}\n\n{sshd}\n```")
except Exception as e:
logger.error(f"Error in cmd_fail2ban: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_ssh(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Статус SSH"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
who = subprocess.check_output(
"/usr/bin/who",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
sessions = subprocess.check_output(
"/usr/bin/ss | /usr/bin/grep ssh | /usr/bin/wc -l",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"🔐 **SSH:**\n\n👥 **Активные сессии:** {sessions}\n```\n{who if who else 'Нет активных сессий'}\n```")
except Exception as e:
logger.error(f"Error in cmd_ssh: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_backup(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Создать бэкап"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
msg = await update.message.reply_text("🔄 Начинаю бэкап...")
try:
output = subprocess.check_output(
"/root/scripts/backup-all.sh",
shell=True, stderr=subprocess.STDOUT, env={'PATH': '/usr/bin:/bin'}
).decode()
await msg.edit_text(f"✅ **Бэкап завершён:**\n```\n{output}\n```")
except Exception as e:
logger.error(f"Error in cmd_backup: {e}")
await msg.edit_text(f"❌ Ошибка бэкапа: {e}")
async def cmd_top(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Топ процессов по CPU/RAM"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
top = subprocess.check_output(
"/usr/bin/ps aux --sort=-%cpu | /usr/bin/head -11",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"🔝 **Топ процессов (CPU):**\n```\n{top}\n```")
except Exception as e:
logger.error(f"Error in cmd_top: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_network(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Статистика сети"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
# Интерфейсы
interfaces = subprocess.check_output(
"/sbin/ip -o link show | /usr/bin/awk '{{print $2}}'",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
# Статистика
netstat = subprocess.check_output(
"/bin/netstat -tulpn 2>/dev/null || /bin/ss -tulpn",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()[:3000]
await update.message.reply_text(f"🌐 **Сеть:**\n\n**Интерфейсы:**\n```\n{interfaces}\n```\n**Порты:**\n```\n{netstat}\n```")
except Exception as e:
logger.error(f"Error in cmd_network: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_domains(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Список доменов (nginx)"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
try:
# Проверка nginx
nginx_conf = "/etc/nginx/nginx.conf"
sites = subprocess.check_output(
f"/bin/grep -r 'server_name' /etc/nginx/sites-enabled/ 2>/dev/null || echo 'Nginx не настроен или нет sites-enabled'",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode().strip()
await update.message.reply_text(f"🌐 **Домены:**\n```\n{sites if sites else 'Nginx не настроен'}\n```")
except Exception as e:
logger.error(f"Error in cmd_domains: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_service_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Логи конкретной службы"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /logs <service>\nПример: /logs telegrab")
return
service = context.args[0]
lines = context.args[1] if len(context.args) > 1 else "50"
try:
logs = subprocess.run(
f"/usr/bin/journalctl -u {service} --no-pager --lines={lines}",
shell=True,
capture_output=True,
text=True,
env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).stdout.strip()
if not logs:
logs = "✅ Записей не найдено"
await update.message.reply_text(f"📝 **Логи {service} (последние {lines}):**\n```\n{logs}\n```")
except Exception as e:
logger.error(f"Error in cmd_service_logs: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_enable_service(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Включить службу в автозапуск"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /enable <service>")
return
service = context.args[0]
try:
subprocess.check_output(
f"/usr/bin/systemctl enable {service}",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode()
await update.message.reply_text(f"✅ Служба **{service}** включена в автозапуск")
except Exception as e:
logger.error(f"Error in cmd_enable: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_disable_service(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Отключить службу из автозапуска"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /disable <service>")
return
service = context.args[0]
try:
subprocess.check_output(
f"/usr/bin/systemctl disable {service}",
shell=True, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode()
await update.message.reply_text(f"✅ Служба **{service}** отключена из автозапуска")
except Exception as e:
logger.error(f"Error in cmd_disable: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_journal(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Журнал systemd службы"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
if not context.args:
await update.message.reply_text("❌ Укажите имя службы: /journal <service>")
return
service = context.args[0]
lines = context.args[1] if len(context.args) > 1 else "30"
try:
logs = subprocess.run(
f"/usr/bin/journalctl -u {service} --no-pager --lines={lines} -o cat",
shell=True,
capture_output=True,
text=True,
env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).stdout.strip()
if not logs:
logs = "✅ Записей не найдено"
await update.message.reply_text(f"📰 **Журнал {service}:**\n```\n{logs}\n```")
except Exception as e:
logger.error(f"Error in cmd_journal: {e}")
await update.message.reply_text(f"❌ Ошибка: {e}")
async def cmd_ping(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Проверка связи"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
await update.message.reply_text("🏓 Понг! Сервер на связи ✅")
async def cmd_whoami(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Информация о пользователе"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
user_info = f"""
👤 **Информация:**
**ID:** `{update.effective_user.id}`
**Имя:** {update.effective_user.first_name}
**Username:** @{update.effective_user.username or 'не указан'}
**Доступ:** {'✅ Разрешён' if is_authorized(update.effective_user.id) else '❌ Запрещён'}
"""
await update.message.reply_text(user_info)
async def cmd_reboot(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Перезагрузка сервера"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
msg = await update.message.reply_text("🔄 Перезагрузка сервера...")
try:
subprocess.check_output(
"/sbin/reboot",
shell=True, stderr=subprocess.STDOUT, env={'PATH': '/usr/bin:/usr/sbin:/bin:/sbin'}
).decode()
await msg.edit_text("✅ Сервер перезагружается...")
except Exception as e:
logger.error(f"Error in cmd_reboot: {e}")
await msg.edit_text(f"❌ Ошибка перезагрузки: {e}")
async def notify_startup(context: ContextTypes.DEFAULT_TYPE):
"""Отправка уведомления о запуске бота"""
if OWNER_ID:
try:
await context.bot.send_message(
chat_id=OWNER_ID,
text="🤖 **Бот запущен**\n\n✅ Сервер-бот успешно стартовал и готов к работе.\n\nИспользуйте /help для списка команд."
)
except Exception as e:
logger.error(f"Не удалось отправить уведомление о запуске: {e}")
async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Скачивание документов"""
if not is_authorized(update.effective_user.id):
return
file = await update.message.document.get_file()
file_name = update.message.document.file_name or f"file_{update.message.document.file_id}"
file_path = f"/root/share/{file_name}"
await file.download_to_drive(file_path)
await update.message.reply_text(f"✅ Файл сохранён:\n`{file_path}`")
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Скачивание фотографий"""
if not is_authorized(update.effective_user.id):
return
# Получаем фото в наилучшем качестве (последний в списке)
photo = update.message.photo[-1]
file = await photo.get_file()
file_path = f"/root/share/photo_{photo.file_id}.jpg"
await file.download_to_drive(file_path)
await update.message.reply_text(f"✅ Фото сохранено:\n`{file_path}`")
async def handle_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Скачивание голосовых сообщений"""
if not is_authorized(update.effective_user.id):
return
file = await update.message.voice.get_file()
file_path = f"/root/share/voice_{update.message.voice.file_id}.ogg"
await file.download_to_drive(file_path)
await update.message.reply_text(f"✅ Голосовое сохранено:\n`{file_path}`")
async def handle_audio(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Скачивание аудио файлов"""
if not is_authorized(update.effective_user.id):
return
file = await update.message.audio.get_file()
file_name = update.message.audio.file_name or f"audio_{update.message.audio.file_id}.mp3"
file_path = f"/root/share/{file_name}"
await file.download_to_drive(file_path)
await update.message.reply_text(f"✅ Аудио сохранено:\n`{file_path}`")
async def handle_video(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Скачивание видео файлов"""
if not is_authorized(update.effective_user.id):
return
file = await update.message.video.get_file()
file_name = update.message.video.file_name or f"video_{update.message.video.file_id}.mp4"
file_path = f"/root/share/{file_name}"
await file.download_to_drive(file_path)
await update.message.reply_text(f"✅ Видео сохранено:\n`{file_path}`")
async def unknown_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Неизвестная команда или текст"""
if not is_authorized(update.effective_user.id):
await update.message.reply_text("❌ Доступ запрещён")
return
# Получаем текст сообщения
text = update.message.text or ""
# Если это команда
if text.startswith('/'):
await update.message.reply_text(
"❓ Неизвестная команда\n\n"
"Используйте /help для списка доступных команд."
)
# Если это обычный текст
else:
await update.message.reply_text(
"🤖 Я понимаю только команды!\n\n"
"Отправьте /help для списка доступных команд."
)
# ========== MAIN ==========
def main():
"""Запуск бота"""
# Проверка токена
if BOT_TOKEN == "YOUR_BOT_TOKEN_HERE":
print("❌ Ошибка: Установите BOT_TOKEN в config.py")
return
# Создание приложения с поддержкой Markdown и JobQueue
application = Application.builder().token(BOT_TOKEN).defaults(Defaults(parse_mode='Markdown')).job_queue(JobQueue()).build()
# Добавление обработчиков
application.add_handler(CommandHandler("start", cmd_start))
application.add_handler(CommandHandler("help", cmd_help))
# Информация
application.add_handler(CommandHandler("status", cmd_status))
application.add_handler(CommandHandler("services", cmd_services))
application.add_handler(CommandHandler("disk", cmd_disk))
application.add_handler(CommandHandler("ram", cmd_ram))
application.add_handler(CommandHandler("logs", cmd_logs))
application.add_handler(CommandHandler("backups", cmd_backups))
# Мониторинг
application.add_handler(CommandHandler("top", cmd_top))
application.add_handler(CommandHandler("network", cmd_network))
application.add_handler(CommandHandler("domains", cmd_domains))
# Управление службами
application.add_handler(CommandHandler("restart", cmd_restart))
application.add_handler(CommandHandler("start", cmd_start_service))
application.add_handler(CommandHandler("stop", cmd_stop_service))
application.add_handler(CommandHandler("enable", cmd_enable_service))
application.add_handler(CommandHandler("disable", cmd_disable_service))
application.add_handler(CommandHandler("logs", cmd_service_logs))
application.add_handler(CommandHandler("journal", cmd_journal))
# Безопасность
application.add_handler(CommandHandler("fail2ban", cmd_fail2ban))
application.add_handler(CommandHandler("ssh", cmd_ssh))
# Бэкапы
application.add_handler(CommandHandler("backup", cmd_backup))
# Система
application.add_handler(CommandHandler("ping", cmd_ping))
application.add_handler(CommandHandler("whoami", cmd_whoami))
application.add_handler(CommandHandler("reboot", cmd_reboot))
# Обработчики файлов
application.add_handler(MessageHandler(filters.Document.ALL, handle_document))
application.add_handler(MessageHandler(filters.PHOTO, handle_photo))
application.add_handler(MessageHandler(filters.VOICE, handle_voice))
application.add_handler(MessageHandler(filters.AUDIO, handle_audio))
application.add_handler(MessageHandler(filters.VIDEO, handle_video))
# Обработчик неизвестных команд и текстовых сообщений
application.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, unknown_command))
application.add_handler(MessageHandler(filters.COMMAND, unknown_command))
# Запуск
print("🤖 Бот запущен...")
# Отправка уведомления о запуске
application.job_queue.run_once(notify_startup, when=0)
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == '__main__':
main()