Repository navigation
Expand file tree
/
Copy pathwizard.py
More file actions
208 lines (166 loc) · 7.46 KB
/
Copy pathwizard.py
File metadata and controls
208 lines (166 loc) · 7.46 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
#!/usr/bin/env python3
"""Интерактивный мастер MessageLab — для пользователей без опыта в коде."""
from __future__ import annotations
import asyncio
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm, Prompt
from rich.table import Table
from version import __app_name__, __version__
ROOT = Path(__file__).resolve().parent
ENV_PATH = ROOT / ".env"
REPORTS_DIR = ROOT / "reports"
console = Console()
def clear_screen() -> None:
os.system("cls" if os.name == "nt" else "clear")
def banner() -> None:
console.print(
Panel(
f"[bold magenta]{__app_name__}[/bold magenta] v{__version__}\n"
"[dim]Анализ переписки Telegram: слова, стикеры, активность[/dim]",
border_style="magenta",
)
)
def env_exists() -> bool:
if not ENV_PATH.exists():
return False
load_dotenv(ENV_PATH)
return bool(os.getenv("TELEGRAM_API_ID") and os.getenv("TELEGRAM_API_HASH"))
def run_setup_wizard() -> None:
clear_screen()
banner()
console.print(
"[bold]Первичная настройка[/bold]\n\n"
"Нужны ключи Telegram API — это [bold]не пароль[/bold], а бесплатные ключи приложения.\n"
"1. Откройте [link=https://my.telegram.org/apps]my.telegram.org/apps[/link]\n"
"2. Войдите по номеру телефона\n"
"3. Создайте приложение (любое название)\n"
"4. Скопируйте [bold]api_id[/bold] и [bold]api_hash[/bold]\n"
)
api_id = Prompt.ask("Введите API ID (число)")
while not api_id.strip().isdigit():
console.print("[red]API ID — это число, например 12345678[/red]")
api_id = Prompt.ask("Введите API ID")
api_hash = Prompt.ask("Введите API Hash (длинная строка)")
while len(api_hash.strip()) < 10:
console.print("[red]API Hash слишком короткий[/red]")
api_hash = Prompt.ask("Введите API Hash")
phone = Prompt.ask("Телефон для входа (+7999...)", default="")
password = Prompt.ask("2FA пароль (если есть, иначе Enter)", default="", password=True)
default_chat = Prompt.ask("Чат по умолчанию (@username, Enter — пропустить)", default="")
lines = [
"# MessageLab — настройки",
"# Получить ключи: https://my.telegram.org/apps",
f"TELEGRAM_API_ID={api_id.strip()}",
f"TELEGRAM_API_HASH={api_hash.strip()}",
]
if phone.strip():
lines.append(f"TELEGRAM_PHONE={phone.strip()}")
if password.strip():
lines.append(f"TELEGRAM_PASSWORD={password.strip()}")
if default_chat.strip():
lines.append(f"TELEGRAM_CHAT={default_chat.strip()}")
ENV_PATH.write_text("\n".join(lines) + "\n", encoding="utf-8")
REPORTS_DIR.mkdir(exist_ok=True)
console.print(f"\n[green]Настройки сохранены:[/green] {ENV_PATH}")
console.print("[dim]Файл .env хранится только на вашем компьютере.[/dim]\n")
Prompt.ask("Нажмите Enter для продолжения", default="")
async def list_chats_interactive() -> None:
from main import run_list_chats
await run_list_chats(list_limit=50)
console.print()
Prompt.ask("Нажмите Enter", default="")
async def analyze_interactive() -> None:
from main import run_analyze
clear_screen()
banner()
console.print("[bold]Анализ чата[/bold]\n")
if Confirm.ask("Показать список ваших чатов перед выбором?", default=True):
from main import run_list_chats
await run_list_chats(list_limit=30)
console.print()
chat = Prompt.ask(
"Кого анализируем? (@username, имя контакта или ID из списка)"
).strip()
if not chat:
console.print("[red]Чат не указан[/red]")
Prompt.ask("Enter", default="")
return
limit_str = Prompt.ask(
"Сколько последних сообщений? (Enter = вся история)", default=""
).strip()
limit = int(limit_str) if limit_str.isdigit() else None
export = Confirm.ask("Сохранить отчёт в папку reports/?", default=True)
export_json = None
export_html = None
if export:
REPORTS_DIR.mkdir(exist_ok=True)
safe_name = re.sub(r"[^\w\-]+", "_", chat)[:40]
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
export_json = REPORTS_DIR / f"{safe_name}_{stamp}.json"
export_html = REPORTS_DIR / f"{safe_name}_{stamp}.html"
console.print()
await run_analyze(
chat_ref=chat,
limit=limit,
export=str(export_json) if export_json else None,
export_html_path=str(export_html) if export_html else None,
)
console.print()
Prompt.ask("Нажмите Enter для возврата в меню", default="")
def show_help() -> None:
clear_screen()
banner()
table = Table(title="Как пользоваться", show_header=False, border_style="blue")
table.add_column("Шаг", style="bold")
table.add_column("Действие")
table.add_row("1", "Запустите SETUP.bat (один раз) или пункт «Настройка» в меню")
table.add_row("2", "Получите api_id и api_hash на my.telegram.org/apps")
table.add_row("3", "Запустите START.bat → «Анализировать чат»")
table.add_row("4", "При первом входе введите код из Telegram")
table.add_row("5", "Отчёты сохраняются в папку reports/")
console.print(table)
console.print(
"\n[dim]Поддерживаются: личные чаты, @username, имя контакта, ID из списка чатов.[/dim]\n"
)
Prompt.ask("Enter", default="")
async def main_menu() -> None:
if not env_exists():
run_setup_wizard()
while True:
clear_screen()
banner()
console.print("[bold]Главное меню[/bold]\n")
console.print(" [cyan]1[/cyan] — Анализировать чат")
console.print(" [cyan]2[/cyan] — Показать список чатов")
console.print(" [cyan]3[/cyan] — Настройка (API ключи)")
console.print(" [cyan]4[/cyan] — Инструкция")
console.print(" [cyan]0[/cyan] — Выход\n")
choice = Prompt.ask("Выберите пункт", default="1").strip()
if choice == "1":
await analyze_interactive()
elif choice == "2":
await list_chats_interactive()
elif choice == "3":
run_setup_wizard()
elif choice == "4":
show_help()
elif choice == "0":
console.print("[dim]До встречи![/dim]")
break
else:
console.print("[yellow]Неизвестный пункт[/yellow]")
def main() -> None:
try:
asyncio.run(main_menu())
except KeyboardInterrupt:
console.print("\n[yellow]Выход[/yellow]")
sys.exit(0)
if __name__ == "__main__":
main()