-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfirst_setup.py
More file actions
534 lines (432 loc) · 21.9 KB
/
Copy pathfirst_setup.py
File metadata and controls
534 lines (432 loc) · 21.9 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
"""
Первичная установка Starvell Cardinal
"""
import os
import sys
import configparser
import hashlib
import time
from pathlib import Path
try:
from colorama import Fore, Style, init, Back
init(autoreset=True)
HAS_COLOR = True
except ImportError:
# Если colorama не установлена
class Fore:
CYAN = MAGENTA = RED = BLUE = GREEN = YELLOW = WHITE = LIGHTBLUE_EX = LIGHTGREEN_EX = ""
class Style:
BRIGHT = RESET_ALL = DIM = ""
class Back:
BLACK = ""
HAS_COLOR = False
# ═══════════════════════════════════════════════════════════
# 🎨 Стилизация
# ═══════════════════════════════════════════════════════════
def clear():
"""Очистить экран"""
os.system('cls' if os.name == 'nt' else 'clear')
def print_logo():
"""Красивый ASCII логотип"""
logo = f"""
{Fore.CYAN}{Style.BRIGHT}
███████╗████████╗ █████╗ ██████╗ ██╗ ██╗███████╗██╗ ██╗
██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██║ ██║██╔════╝██║ ██║
███████╗ ██║ ███████║██████╔╝██║ ██║█████╗ ██║ ██║
╚════██║ ██║ ██╔══██║██╔══██╗╚██╗ ██╔╝██╔══╝ ██║ ██║
███████║ ██║ ██║ ██║██║ ██║ ╚████╔╝ ███████╗███████╗███████╗
╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚══════╝╚══════╝
{Style.RESET_ALL}"""
print(logo)
def print_header(step=None, total=4):
"""Красивый заголовок с индикатором прогресса"""
clear()
print_logo()
if step:
# Индикатор прогресса
progress = "█" * step + "░" * (total - step)
percentage = int((step / total) * 100)
print(f"\n{Fore.CYAN}╔{'═' * 70}╗")
print(f"║{' ' * 24}{Fore.WHITE}МАСТЕР УСТАНОВКИ{Fore.CYAN}{' ' * 30}║")
print(f"║{' ' * 70}║")
print(f"║ {Fore.LIGHTBLUE_EX}Прогресс: {Fore.GREEN}{progress}{Fore.CYAN} {percentage}% {Fore.WHITE}(Шаг {step} из {total}){Fore.CYAN}{' ' * (70 - 45 - len(str(step)) - len(str(total)))}║")
print(f"╚{'═' * 70}╝{Style.RESET_ALL}\n")
else:
print(f"\n{Fore.CYAN}╔{'═' * 70}╗")
print(f"║{' ' * 20}{Fore.WHITE}{Style.BRIGHT}ДОБРО ПОЖАЛОВАТЬ В STARVELL CARDINAL{Fore.CYAN}{Style.NORMAL}{' ' * 15}║")
print(f"║{' ' * 22}{Fore.WHITE}Made by @knowtake{Fore.CYAN}{' ' * 25}║")
print(f"╚{'═' * 70}╝{Style.RESET_ALL}\n")
def print_box(title, lines, color=Fore.CYAN):
"""Красивая рамка с текстом"""
width = 68
print(f"\n{color}┌─ {Fore.WHITE}{Style.BRIGHT}{title}{Style.RESET_ALL}")
for line in lines:
print(f"{color}│ {Fore.WHITE}{line}{Style.RESET_ALL}")
print(f"{color}└{'─' * width}{Style.RESET_ALL}\n")
def print_info(text, icon="ℹ"):
"""Информационное сообщение"""
print(f"{Fore.LIGHTBLUE_EX}{icon} {Fore.WHITE}{text}{Style.RESET_ALL}")
def print_success(text, icon="✓"):
"""Сообщение об успехе"""
print(f"{Fore.GREEN}{icon} {Fore.WHITE}{text}{Style.RESET_ALL}")
def print_error(text, icon="✗"):
"""Сообщение об ошибке"""
print(f"{Fore.RED}{icon} {Fore.WHITE}{text}{Style.RESET_ALL}")
def print_warning(text, icon="⚠"):
"""Предупреждение"""
print(f"{Fore.YELLOW}{icon} {Fore.WHITE}{text}{Style.RESET_ALL}")
def ask(prompt, default="", secret=False):
"""Запросить ввод с подсказкой"""
if default:
full_prompt = f"{Fore.CYAN}❯ {Fore.WHITE}{prompt} {Fore.GREEN}[{default}]{Fore.CYAN}: {Style.RESET_ALL}"
else:
full_prompt = f"{Fore.CYAN}❯ {Fore.WHITE}{prompt}{Fore.CYAN}: {Style.RESET_ALL}"
if secret:
import getpass
value = getpass.getpass(full_prompt)
else:
value = input(full_prompt).strip()
return value if value else default
def ask_yes_no(prompt, default=True):
"""Запросить да/нет"""
default_str = f"{Fore.GREEN}Y{Fore.WHITE}/{Fore.RED}n" if default else f"{Fore.WHITE}y{Fore.RED}/N"
while True:
full_prompt = f"{Fore.CYAN}❯ {Fore.WHITE}{prompt} ({default_str}{Fore.CYAN}): {Style.RESET_ALL}"
value = input(full_prompt).strip().lower()
if not value:
return default
if value in ['y', 'yes', 'д', 'да', '1']:
return True
if value in ['n', 'no', 'н', 'нет', '0']:
return False
print_error("Введите Y (да) или N (нет)")
def animate_dots(text, duration=1):
"""Анимация точек"""
print(f"{Fore.CYAN}{text}", end="", flush=True)
for _ in range(3):
time.sleep(duration / 3)
print(".", end="", flush=True)
print(f" {Fore.GREEN}✓{Style.RESET_ALL}")
time.sleep(0.3)
# ═══════════════════════════════════════════════════════════
# 🔧 Установка
# ═══════════════════════════════════════════════════════════
def run_setup():
"""Запустить установку"""
config = configparser.ConfigParser()
# ═══ Приветствие ═══
print_header()
print(f"{Fore.CYAN}╔{'═' * 70}╗")
print(f"║{' ' * 70}║")
print(f"║{' ' * 15}{Fore.WHITE}{Style.BRIGHT}🚀 Мастер быстрой настройки бота 🚀{Fore.CYAN}{Style.NORMAL}{' ' * 18}║")
print(f"║{' ' * 70}║")
print(f"║{' ' * 10}{Fore.WHITE}Сейчас мы за 4 простых шага настроим ваш бот{Fore.CYAN}{' ' * 16}║")
print(f"║{' ' * 15}{Fore.WHITE}Это займёт всего пару минут!{Fore.CYAN}{' ' * 27}║")
print(f"║{' ' * 70}║")
print(f"╚{'═' * 70}╝{Style.RESET_ALL}\n")
print_info("Вы можете в любой момент прервать установку нажав Ctrl+C")
print_info("Все настройки позже можно изменить через бота\n")
input(f"{Fore.GREEN}{Style.BRIGHT}❯ Нажмите Enter для начала...{Style.RESET_ALL}")
# ═══════════════════════════════════════════════════════════
# ШАГ 1: Telegram Bot Token
# ═══════════════════════════════════════════════════════════
print_header(step=1)
print_header(step=1)
print_box(
"📱 ШАГ 1: Telegram Bot Token",
[
"Для работы бота нужен токен от @BotFather",
"",
"Как получить:",
" 1️⃣ Напишите @BotFather в Telegram",
" 2️⃣ Отправьте команду /newbot",
" 3️⃣ Следуйте инструкциям",
" 4️⃣ Скопируйте полученный токен"
]
)
while True:
bot_token = ask("Введите токен бота")
if not bot_token or ':' not in bot_token:
print_error("Неверный формат токена!")
print_warning("Токен должен выглядеть так: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz\n")
continue
try:
parts = bot_token.split(':')
if not parts[0].isdigit() or len(parts[1]) < 20:
raise ValueError()
animate_dots("Проверка токена")
print_success("Токен принят!\n")
break
except:
print_error("Неверный формат токена!\n")
config['Telegram'] = {'token': bot_token}
# ═══════════════════════════════════════════════════════════
# ШАГ 2: Пароль
# ═══════════════════════════════════════════════════════════
print_header(step=2)
print_box(
"🔐 ШАГ 2: Пароль для бота",
[
"Пароль защитит бот от несанкционированного доступа",
"",
"Требования:",
" ✓ Минимум 8 символов",
" ✓ Заглавные и строчные буквы (A-z)",
" ✓ Хотя бы одна цифра (0-9)"
]
)
while True:
password = ask("Придумайте надёжный пароль")
if len(password) < 8:
print_error("Слишком короткий! Минимум 8 символов\n")
continue
if password.lower() == password or password.upper() == password:
print_error("Нужны и заглавные, и строчные буквы!\n")
continue
if not any(c.isdigit() for c in password):
print_error("Нужна хотя бы одна цифра!\n")
continue
# Подтверждение пароля
password_confirm = ask("Повторите пароль")
if password != password_confirm:
print_error("Пароли не совпадают! Попробуйте снова\n")
continue
animate_dots("Сохранение пароля")
print_success("Пароль принят!\n")
break
password_hash = hashlib.sha256(password.encode()).hexdigest()
config['Telegram']['secretkeyhash'] = password_hash
config['Telegram']['adminIds'] = '[]'
config['Telegram']['enabled'] = '1'
# ═══════════════════════════════════════════════════════════
# ШАГ 3: Starvell Session
# ═══════════════════════════════════════════════════════════
print_header(step=3)
print_box(
"🔑 ШАГ 3: Starvell Session Cookie",
[
"Session cookie нужен для доступа к API Starvell",
"",
"Как получить:",
" 1️⃣ Откройте starvell.com и войдите в аккаунт",
" 2️⃣ Нажмите F12 (открыть DevTools)",
" 3️⃣ Перейдите: Application → Cookies → starvell.com",
" 4️⃣ Найдите cookie с именем 'session'",
" 5️⃣ Скопируйте её значение (двойной клик → Ctrl+C)"
]
)
while True:
session = ask("Введите session cookie")
if not session or len(session) < 10:
print_error("Cookie не может быть пустой!\n")
continue
animate_dots("Проверка cookie")
print_success("Session сохранён!\n")
break
# User-Agent (опционально)
print()
print_info("User-Agent (опционально):")
print_info("Оставьте пустым для использования стандартного\n")
user_agent = ask("User-Agent (или Enter для пропуска)", "")
if not user_agent:
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
print_success("Используется стандартный User-Agent\n")
else:
print_success("User-Agent сохранён\n")
config['Starvell'] = {
'session_cookie': session,
'user_agent': user_agent,
'autoRaise': '0',
'autoDelivery': '0',
'autoRestore': '0',
'locale': 'ru',
'autoTicket': '0',
'autoTicketInterval': '3600',
'autoTicketMaxOrders': '5',
'autoTicketOrderAge': '48'
}
# ═══════════════════════════════════════════════════════════
# ШАГ 4: Прокси для Telegram (опционально)
# ═══════════════════════════════════════════════════════════
print_header(step=4)
print_box(
"🌐 ШАГ 4: Прокси для Telegram (необязательно)",
[
"Если Telegram заблокирован у вашего провайдера (напр. в РФ),",
"укажите прокси — бот будет ходить в Telegram через него.",
"",
"Поддерживаются: SOCKS5, SOCKS4, HTTP(S).",
"Рекомендуется SOCKS5.",
"",
"Можно пропустить (Enter) и включить позже через бота.",
]
)
proxy_cfg = {
'enabled': 'false',
'type': 'socks5',
'ip': '',
'port': '',
'login': '',
'password': '',
'check': 'false',
}
use_proxy = ask_yes_no("Использовать прокси для Telegram?", default=False)
if use_proxy:
print()
print_info("Тип прокси: 1) socks5 2) socks4 3) http 4) https")
ptype_map = {'1': 'socks5', '2': 'socks4', '3': 'http', '4': 'https',
'socks5': 'socks5', 'socks4': 'socks4',
'http': 'http', 'https': 'https'}
while True:
ptype_in = ask("Введите тип прокси", "socks5").strip().lower()
ptype = ptype_map.get(ptype_in)
if ptype:
break
print_error("Неверный тип! Введите 1-4 или socks5/socks4/http/https\n")
while True:
proxy_ip = ask("IP или хост прокси (напр. 127.0.0.1)").strip()
if proxy_ip:
break
print_error("Адрес не может быть пустым!\n")
while True:
proxy_port = ask("Порт прокси (напр. 1080)").strip()
if proxy_port.isdigit() and 0 < int(proxy_port) < 65536:
break
print_error("Порт должен быть числом 1-65535!\n")
print()
print_info("Авторизация прокси (если нужна). Enter — пропустить.")
proxy_login = ask("Логин (или Enter)", "").strip()
proxy_password = ""
if proxy_login:
proxy_password = ask("Пароль", "").strip()
proxy_cfg = {
'enabled': 'true',
'type': ptype,
'ip': proxy_ip,
'port': proxy_port,
'login': proxy_login,
'password': proxy_password,
'check': 'false',
}
animate_dots("Сохранение прокси")
_auth = f"{proxy_login}:***@" if proxy_login else ""
print_success(f"Прокси сохранён: {ptype}://{_auth}{proxy_ip}:{proxy_port}\n")
else:
print_info("Прокси не используется — подключение к Telegram напрямую.\n")
config['Proxy'] = proxy_cfg
# ═══════════════════════════════════════════════════════════
# Сохранение
# ═══════════════════════════════════════════════════════════
# Дополнительные настройки (по умолчанию)
config['Notifications'] = {
'checkInterval': '30',
'newMessages': '1',
'newOrders': '1',
'lotRestore': '1',
'botStart': '1',
'lotDeactivate': '1',
'lotBump': '1',
'autoTicket': '1'
}
config['AutoRaise'] = {
'interval': '3600',
'gameId': '1',
'categories': '[10, 11, 12]'
}
config['AutoUpdate'] = {
'enabled': '1',
'auto_install': '1'
}
config['KeepAlive'] = {
'enabled': '1',
'interval': '30'
}
config['Storage'] = {
'dir': 'storage'
}
config['Blacklist'] = {
'block_delivery': '1',
'block_response': '1',
'block_msg_notifications': '1',
'block_order_notifications': '1'
}
config['Other'] = {
'debug': '0',
'watermark': '🤖'
}
config['AutoTicket'] = {
'ticketType': '1',
'orderUserTypeId': '2',
'orderTopicId': '501'
}
# Сохраняем конфигурацию
print()
animate_dots("Сохранение конфигурации")
try:
config_path = Path("configs/_main.cfg")
config_path.parent.mkdir(parents=True, exist_ok=True)
with open(config_path, 'w', encoding='utf-8') as f:
config.write(f)
print_success("Конфигурация сохранена!\n")
time.sleep(0.5)
except Exception as e:
print_error(f"Ошибка сохранения: {e}\n")
return False
# ═══════════════════════════════════════════════════════════
# Финал - Успешное завершение
# ═══════════════════════════════════════════════════════════
clear()
print_logo()
print(f"\n{Fore.GREEN}{Style.BRIGHT}╔{'═' * 70}╗")
print(f"║{' ' * 70}║")
print(f"║{' ' * 20}🎉 УСТАНОВКА ЗАВЕРШЕНА УСПЕШНО! 🎉{' ' * 19}║")
print(f"║{' ' * 70}║")
print(f"╚{'═' * 70}╝{Style.RESET_ALL}\n")
print_box(
"📋 Сводка установки",
[
f"✓ Bot Token: {bot_token[:20]}...{bot_token[-10:]}",
f"✓ Пароль: {'*' * 16}",
f"✓ Session: {session[:25]}...{session[-15:] if len(session) > 40 else ''}",
f"✓ Конфигурация сохранена: configs/_main.cfg"
],
color=Fore.GREEN
)
print_box(
"🚀 Что дальше?",
[
"1️⃣ Запустите бота:",
f" {Fore.GREEN}python main.py{Fore.WHITE}",
"",
"2️⃣ Откройте бот в Telegram и отправьте:",
f" {Fore.GREEN}/start{Fore.WHITE}",
"",
"3️⃣ Введите пароль для авторизации:",
f" {Fore.GREEN}{password}{Fore.WHITE}",
"",
"4️⃣ Готово! Управляйте ботом через меню",
"",
f"{Fore.YELLOW}💡 Все настройки можно изменить через бота{Fore.WHITE}"
],
color=Fore.CYAN
)
print(f"{Fore.CYAN}╔{'═' * 70}╗")
print(f"║{' ' * 18}{Fore.WHITE}Документация: {Fore.GREEN}docs/PLUGINS_API.md{Fore.CYAN}{' ' * 22}║")
print(f"║{' ' * 20}{Fore.WHITE}Автор: {Fore.GREEN}@knowtake{Fore.CYAN}{' ' * 30}║")
print(f"║{' ' * 19}{Fore.WHITE}Канал: {Fore.GREEN}@starvellingbot{Fore.CYAN}{' ' * 25}║")
print(f"╚{'═' * 70}╝{Style.RESET_ALL}\n")
print(f"{Fore.YELLOW}{Style.BRIGHT}Спасибо за установку Starvell Cardinal!{Style.RESET_ALL}\n")
return True
# ═══════════════════════════════════════════════════════════
# 🚀 Запуск
# ═══════════════════════════════════════════════════════════
if __name__ == "__main__":
try:
success = run_setup()
sys.exit(0 if success else 1)
except KeyboardInterrupt:
print(f"\n\n{Fore.YELLOW}Установка прервана пользователем{Style.RESET_ALL}\n")
sys.exit(1)
except Exception as e:
print(f"\n\n{Fore.RED}Критическая ошибка: {e}{Style.RESET_ALL}\n")
sys.exit(1)