From 3c6508bb4ac3d4801c4e14d80384c01dd16ddc3d Mon Sep 17 00:00:00 2001 From: kirieska Date: Thu, 1 Oct 2026 17:23:41 +0300 Subject: [PATCH] =?UTF-8?q?=D1=84=D0=B8=D0=BD=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.py | 888 +++++++++++++++++++++++++++++++++++++++---------- files/.gitkeep | 0 2 files changed, 718 insertions(+), 170 deletions(-) delete mode 100644 files/.gitkeep diff --git a/app.py b/app.py index db2ac35..aacce48 100644 --- a/app.py +++ b/app.py @@ -1,20 +1,116 @@ import os import sys +import time import asyncio import configparser import subprocess +from collections import deque, OrderedDict from telethon import TelegramClient, events, errors +from telethon.tl.types import User, Chat, Channel from prompt_toolkit import PromptSession from prompt_toolkit.patch_stdout import patch_stdout from prompt_toolkit.key_binding import KeyBindings import qrcode + # ==================== СИСТЕМНЫЕ ФУНКЦИИ ==================== def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') + +# ==================== КОНФИГУРАЦИЯ ==================== +config_file = 'config.ini' +config = configparser.ConfigParser() + + +def create_blank_config(): + config['API'] = {'id': '', 'hash': ''} + with open(config_file, 'w') as f: + config.write(f) + + +if not os.path.exists(config_file): + create_blank_config() + clear_screen() + print(f"[CONFIG] File '{config_file}' was created.") + print("Please fill 'id' and 'hash' values and restart the script.") + sys.exit() + +config.read(config_file) + +try: + raw_id = config.get('API', 'id').strip() + raw_hash = config.get('API', 'hash').strip() + if not raw_id or not raw_hash: + clear_screen() + print(f"[ERROR] Empty 'id' or 'hash' in '{config_file}'. Please fill them.") + sys.exit() + API_ID = int(raw_id) + API_HASH = raw_hash +except ValueError: + clear_screen() + print(f"[ERROR] API 'id' in '{config_file}' must be an integer.") + sys.exit() +except (configparser.NoSectionError, configparser.NoOptionError): + create_blank_config() + clear_screen() + print(f"[ERROR] '{config_file}' corrupted. Recreated blank config.") + sys.exit() + +client = TelegramClient("user_session", API_ID, API_HASH) +os.makedirs("files", exist_ok=True) +os.makedirs("files/logs", exist_ok=True) + + +# ==================== СОСТОЯНИЕ ==================== +target_entity = None +target_name = "" +mute_enabled = False +local_sent_ids = deque(maxlen=200) +last_media_path = None +pending_delete_at = 0.0 +in_overlay = False + +chat_history = deque(maxlen=1500) + +# Кеш последних сообщений: {msg_id: (chat_id, is_out, text)} +message_cache = OrderedDict() +MAX_CACHE = 500 + +# Логирование в файл +logging_enabled = False +log_file_path = None + + +def cache_message(mid, chat_id, is_out, text): + message_cache[mid] = (chat_id, is_out, text) + message_cache.move_to_end(mid) + while len(message_cache) > MAX_CACHE: + message_cache.popitem(last=False) + + +def emit(line=""): + chat_history.append(line) + if not in_overlay: + try: + print(line, flush=True) + except Exception: + pass + + +def log_event(kind, text): + """Записать событие в лог-файл (если логирование включено).""" + if not logging_enabled or not log_file_path: + return + try: + ts = time.strftime('%Y-%m-%d %H:%M:%S') + with open(log_file_path, 'a', encoding='utf-8') as f: + f.write(f"[{ts}] [{kind}] {text}\n") + except Exception as e: + emit(f"[ERROR] Log write failed: {e}") + + def open_file(path): - """Открывает файл стандартными средствами системы (Windows/Mac/Linux)""" try: if sys.platform == 'win32': os.startfile(path) @@ -23,261 +119,713 @@ def open_file(path): else: subprocess.call(['xdg-open', path]) except Exception as e: - print(f"⚠️ Ошибка открытия файла: {e}") + emit(f"[ERROR] Failed to open file: {e}") -# ==================== ИНИЦИАЛИЗАЦИЯ И КОНФИГ ==================== -config_file = 'config.ini' -config = configparser.ConfigParser() -def create_blank_config(): - config['API'] = { - 'id': '', - 'hash': '' - } - with open(config_file, 'w') as f: - config.write(f) +def print_header(): + tid = target_entity.id if target_entity else '?' + log_status = "ON" if logging_enabled else "OFF" + print("=" * 60) + print(f" CHAT: {target_name} (ID: {tid}) Mute: {'ON' if mute_enabled else 'OFF'} Log: {log_status}") + print(" F1 help | F2 spam | F3 log | .clear clear | Ctrl+C exit") + print("=" * 60) -if not os.path.exists(config_file): - create_blank_config() + +def redraw(): clear_screen() - print(f"⚠️ Файл '{config_file}' был создан в папке со скриптом.") - print("Открой его любым текстовым редактором, впиши свои 'id' и 'hash', сохрани и запусти скрипт заново!") - sys.exit() - -config.read(config_file) - -try: - raw_id = config.get('API', 'id').strip() - raw_hash = config.get('API', 'hash').strip() - - if not raw_id or not raw_hash: - clear_screen() - print(f"❌ В файле '{config_file}' не указаны API ID или HASH!") - print("Пожалуйста, заполни их и запусти скрипт заново.") - sys.exit() - - API_ID = int(raw_id) - API_HASH = raw_hash -except ValueError: - clear_screen() - print(f"❌ Ошибка в '{config_file}': API 'id' должен состоять только из цифр!") - sys.exit() -except (configparser.NoSectionError, configparser.NoOptionError): - create_blank_config() - clear_screen() - print(f"❌ Файл '{config_file}' был поврежден и пересоздан заново. Пожалуйста, заполни его.") - sys.exit() - -client = TelegramClient("user_session", API_ID, API_HASH) -os.makedirs("files", exist_ok=True) - -# Глобальные переменные -target_entity = None -mute_enabled = False -local_sent_ids = [] -last_media_path = None # Сохраняем путь к последнему полученному файлу + print_header() + for line in chat_history: + print(line) -# ==================== НАСТРОЙКА ИНТЕРФЕЙСА ==================== -bindings = KeyBindings() - -@bindings.add('c-1') -@bindings.add('c-t') -def toggle_mute(event): +def set_mute(state): global mute_enabled - mute_enabled = not mute_enabled - status = "ВКЛ🔴" if mute_enabled else "ВЫКЛ🟢" - print(f"\n⚙️ Мут: {status}") + mute_enabled = state + emit(f"[SYSTEM] Mute: {'ON' if mute_enabled else 'OFF'}") -@bindings.add('c-o') -@bindings.add('c-2') -def open_last_media(event): - """Открываем последнее полученное медиа по нажатию Ctrl+O""" - global last_media_path + +def toggle_logging(force=None): + """Включить/выключить логирование. force=True/False — явно.""" + global logging_enabled, log_file_path + + if force is None: + new_state = not logging_enabled + else: + new_state = force + + if new_state == logging_enabled: + emit(f"[SYSTEM] Log already {'ON' if new_state else 'OFF'}.") + return + + if new_state: + # Включаем: создаём новый файл + ts = time.strftime('%Y%m%d_%H%M%S') + safe_name = "".join(c for c in target_name if c.isalnum() or c in "._-")[:30] or "chat" + log_file_path = os.path.abspath(f"files/logs/{safe_name}_{target_entity.id}_{ts}.txt") + try: + with open(log_file_path, 'w', encoding='utf-8') as f: + f.write(f"=== Log started at {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n") + f.write(f"=== Chat: {target_name} (ID: {target_entity.id}) ===\n\n") + logging_enabled = True + emit(f"[SYSTEM] Logging ON -> {log_file_path}") + except Exception as e: + emit(f"[ERROR] Cannot create log file: {e}") + log_file_path = None + else: + # Выключаем + emit(f"[SYSTEM] Logging OFF. Saved: {log_file_path}") + logging_enabled = False + log_file_path = None + + +# ==================== АНИМАЦИЯ .love ==================== +# Внутри
 шрифт моноширинный → любые символы по 1 клетке → идеально ровно.
+# Пустые клетки заполнены "·" (U+00B7), чтобы сетка была видимой и ровной.
+
+BIG_HEART = "\n".join([
+    "··♥♥··♥♥··",
+    "·♥♥♥♥♥♥♥♥·",
+    "♥♥♥♥♥♥♥♥♥♥",
+    "♥♥♥♥♥♥♥♥♥♥",
+    "♥♥♥♥♥♥♥♥♥♥",
+    "·♥♥♥♥♥♥♥♥·",
+    "··♥♥♥♥♥♥··",
+    "···♥♥♥♥···",
+    "····♥♥····",
+    "····♥♥····",
+])
+
+SMALL_HEART = "\n".join([
+    "··········",
+    "··♥♥♥♥♥♥··",
+    "·♥♥♥♥♥♥♥♥·",
+    "·♥♥♥♥♥♥♥♥·",
+    "··♥♥♥♥♥♥··",
+    "···♥♥♥♥···",
+    "····♥♥····",
+    "··········",
+    "··········",
+    "··········",
+])
+
+
+def _pre(text):
+    safe = text.replace("&", "&").replace("<", "<").replace(">", ">")
+    return f"
{safe}
" + + +def _love_sequence(): + """Пульс 10 сек, потом удаление.""" + seq = [(BIG_HEART, 0.5)] + for _ in range(10): + seq.append((SMALL_HEART, 0.5)) + seq.append((BIG_HEART, 0.5)) + return seq + + +async def run_love_animation(): + seq = _love_sequence() + try: + msg = await client.send_message(target_entity, _pre(seq[0][0]), parse_mode='html') + local_sent_ids.append(msg.id) + for frame, delay in seq[1:]: + await asyncio.sleep(delay) + try: + await msg.edit(_pre(frame), parse_mode='html') + except errors.FloodWaitError as f: + await asyncio.sleep(f.seconds + 1) + try: await msg.edit(_pre(frame), parse_mode='html') + except Exception: pass + except Exception: + pass + + await asyncio.sleep(0.5) + try: + await msg.delete() + emit("[SYSTEM] Love animation finished, message deleted.") + except Exception as e: + emit(f"[ERROR] Failed to delete love message: {e}") + except Exception as e: + emit(f"[ERROR] Animation failed: {e}") + + +# ==================== СПАМ ==================== +async def do_spam(count, msg_text, delay=0.3): + """Отправить msg_text `count` раз с задержкой delay.""" + emit(f"[SPAM] Sending {count} messages (delay {delay}s)...") + for i in range(count): + try: + m = await client.send_message(target_entity, msg_text) + local_sent_ids.append(m.id) + cache_message(m.id, target_entity.id, True, msg_text) + log_event("OUT-SPAM", msg_text) + except errors.FloodWaitError as f: + emit(f"[SPAM] FloodWait {f.seconds}s, skipping one...") + await asyncio.sleep(f.seconds + 1) + except Exception as e: + emit(f"[SPAM] Error at #{i+1}: {e}") + break + if i < count - 1: + await asyncio.sleep(delay) + emit(f"[SPAM] Done ({count} messages).") + + +async def spam_dialog(): + """Диалог для F2: count -> message -> delay.""" + s = PromptSession() + try: + count_str = await s.prompt_async("Spam count: ") + count = int(count_str.strip()) + if count <= 0 or count > 500: + emit("[ERROR] Count must be between 1 and 500.") + return + msg_text = await s.prompt_async("Message: ") + if not msg_text: + emit("[ERROR] Empty message.") + return + delay_str = await s.prompt_async("Delay in sec [0.3]: ") + try: + delay = float(delay_str.strip() or "0.3") + except ValueError: + delay = 0.3 + if delay < 0: + delay = 0 + except (KeyboardInterrupt, EOFError): + emit("[SYSTEM] Spam cancelled.") + return + except ValueError: + emit("[ERROR] Invalid input.") + return + + await do_spam(count, msg_text, delay) + + +# ==================== ХЕЛПЕРЫ ==================== +async def purge_chat(): + try: + await client.delete_dialog(target_entity, revoke=True) + emit("[SYSTEM] Chat dialog completely deleted for both sides.") + log_event("PURGE", "Chat wiped (delete_dialog revoke=True)") + except Exception as e: + emit(f"[ERROR] Failed to delete chat: {e}") + + +def is_target_event(event): + if target_entity is None: + return False + peer = getattr(event.message, 'peer_id', None) if hasattr(event, 'message') and event.message else None + if peer is not None: + if isinstance(target_entity, User): + return getattr(peer, 'user_id', None) == target_entity.id + if isinstance(target_entity, Chat): + return getattr(peer, 'chat_id', None) == target_entity.id + if isinstance(target_entity, Channel): + return getattr(peer, 'channel_id', None) == target_entity.id + return getattr(event, 'chat_id', None) == target_entity.id + + +async def open_last_media(): if last_media_path and os.path.exists(last_media_path): - print(f"\n📂 Открываю: {last_media_path}") + emit(f"[SYSTEM] Opening: {last_media_path}") open_file(last_media_path) else: - print("\n⚠️ Нет медиа для открытия!") + emit("[SYSTEM] No media available to open.") + + +# ==================== ЭКРАН СПРАВКИ ==================== +async def show_help_and_return(): + global in_overlay + in_overlay = True + try: + clear_screen() + print("=" * 60) + print(" COMMAND REFERENCE") + print("=" * 60) + print(" .mute Auto-delete incoming messages") + print(" .unmute Disable auto-delete") + print(" .delete Request chat wipe (then confirm in 20s)") + print(" .delete confirm Confirm chat wipe for both sides") + print(" .love Pulsing heart animation (10 sec, self-deletes)") + print(" .log [on|off] Toggle/control chat logging to file") + print(" .spam N TEXT Send TEXT N times (e.g. .spam 5 hello)") + print(" .clear Clear console chat history") + print(" .status Show current status") + print(" .help Show this screen") + print(" /send Send file/photo") + print(" /open Open last received media") + print(" --- HOTKEYS ---") + print(" F1 Help") + print(" F2 Spam dialog (count -> message -> delay)") + print(" F3 Toggle logging to file") + print(" Ctrl+O Open last media") + print(" Ctrl+T Toggle mute") + print(" Ctrl+L Clear console history") + print(" Ctrl+C Exit") + print("=" * 60) + await asyncio.to_thread(input, "\nPress Enter to return to chat...") + finally: + in_overlay = False + redraw() + + +# ==================== ГОРЯЧИЕ КЛАВИШИ ==================== +bindings = KeyBindings() + + +@bindings.add('c-t') +def _(event): + event.app.exit(result="__MUTE__") + + +@bindings.add('c-o') +def _(event): + event.app.exit(result="__OPEN__") + + +@bindings.add('c-l') +def _(event): + event.app.exit(result="__CLEAR__") + + +@bindings.add('f1') +def _(event): + event.app.exit(result="__HELP__") + + +@bindings.add('f2') +def _(event): + event.app.exit(result="__SPAM__") + + +@bindings.add('f3') +def _(event): + event.app.exit(result="__LOG__") + def bottom_toolbar(): - status = "ВКЛ🔴" if mute_enabled else "ВЫКЛ🟢" - return f" [Ctrl+1] Мут: {status} | [Ctrl+O] Открыть медиа | [Ctrl+C] Выход " + status = "ON" if mute_enabled else "OFF" + log_status = "ON" if logging_enabled else "OFF" + return f" Mute:{status} Log:{log_status} | F1 Help | F2 Spam | F3 Log | Ctrl+O Open | Ctrl+T Mute | Ctrl+C Exit " -# ==================== ОБРАБОТЧИК СООБЩЕНИЙ ==================== +# ==================== ОБРАБОТЧИК НОВЫХ СООБЩЕНИЙ ==================== @client.on(events.NewMessage) async def message_handler(event): - global target_entity, mute_enabled, last_media_path - - if not target_entity or event.chat_id != target_entity.id: + global mute_enabled, last_media_path, pending_delete_at + + if not is_target_event(event): return text = event.text or "" + mid = event.message.id - # === ИСХОДЯЩИЕ (Твои сообщения) === + # === ИСХОДЯЩИЕ === if event.out: - if event.message.id in local_sent_ids: + if mid in local_sent_ids: + cache_message(mid, target_entity.id, True, text) return - - print(f"📱 [Я (с телефона)]: {text}") + + cmd = text.lower().strip() + + if cmd == ".mute": + try: await event.delete() + except Exception: pass + set_mute(True) + return + elif cmd in (".unmute", ".umute"): + try: await event.delete() + except Exception: pass + set_mute(False) + return + elif cmd == ".delete": + try: await event.delete() + except Exception: pass + pending_delete_at = time.monotonic() + emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat for both sides.") + return + elif cmd == ".delete confirm": + try: await event.delete() + except Exception: pass + if pending_delete_at and (time.monotonic() - pending_delete_at) < 20: + pending_delete_at = 0.0 + await purge_chat() + else: + emit("[SYSTEM] Nothing to confirm. Send `.delete` first.") + return + elif cmd == ".love": + try: await event.delete() + except Exception: pass + asyncio.create_task(run_love_animation()) + return + elif cmd == ".clear": + try: await event.delete() + except Exception: pass + chat_history.clear() + emit("[SYSTEM] Console history cleared.") + return + elif cmd == ".log": + try: await event.delete() + except Exception: pass + toggle_logging() + return + elif cmd == ".log on": + try: await event.delete() + except Exception: pass + toggle_logging(True) + return + elif cmd == ".log off": + try: await event.delete() + except Exception: pass + toggle_logging(False) + return + elif cmd.startswith(".spam "): + try: await event.delete() + except Exception: pass + rest = text[6:].strip() + parts = rest.split(maxsplit=1) + if len(parts) < 2: + emit("[ERROR] Format: .spam ") + return + try: + count = int(parts[0]) + except ValueError: + emit("[ERROR] Count must be a number.") + return + if count <= 0 or count > 500: + emit("[ERROR] Count must be between 1 and 500.") + return + asyncio.create_task(do_spam(count, parts[1], 0.3)) + return + elif cmd == ".status": + try: await event.delete() + except Exception: pass + last = last_media_path or '—' + log_info = log_file_path if logging_enabled else 'OFF' + emit(f"[STATUS] Target: {target_name} (ID: {target_entity.id}) | " + f"Mute: {'ON' if mute_enabled else 'OFF'} | Log: {log_info} | Last media: {last}") + return + + # Обычное исходящее (с телефона или из другого клиента) + cache_message(mid, target_entity.id, True, text) if event.media: - print("📎 [Прикреплено медиа]") + emit(f"[ME (phone)]: {text} [media]") + log_event("OUT", f"{text} [media]") + else: + emit(f"[ME (phone)]: {text}") + log_event("OUT", text) return - # === ВХОДЯЩИЕ (От таргета) === + # === ВХОДЯЩИЕ === + # Кешируем ВСЕГДА, до любых действий + cache_message(mid, target_entity.id, False, text) + if mute_enabled: try: await event.delete(revoke=True) - print(f"🚫 [Удалено входящее от таргета]") - except: - pass + emit(f"[SYSTEM] Auto-deleted (mute): {text or '[media]'}") + log_event("DEL-MUTE", text or "[media]") + except Exception as e: + emit(f"[ERROR] Failed to delete message: {e}") return - # Если мут выключен — обрабатываем контент if event.media: - # Скачиваем файл в фоне - path = await event.download_media(file="files/") - last_media_path = path # Запоминаем путь для кнопки открытия - ext = path.lower().split('.')[-1] if '.' in path else '' + try: + path = await event.download_media(file="files/") + except Exception as e: + emit(f"[ERROR] Download failed: {e}") + return - if ext in ['jpg', 'jpeg', 'png', 'mp4']: - print(f"📩 [Таргет]: {text} 🖼 [Фото/Видео сохранено] ➔ Нажми Ctrl+O чтобы посмотреть") - elif ext in ['ogg', 'mp3', 'wav', 'm4a']: - print(f"📩 [Таргет]: {text} 🎤 [Голосовое сохранено] ➔ Нажми Ctrl+O чтобы послушать") - else: - print(f"📩 [Таргет]: {text} 📁 [Файл: {path}] ➔ Нажми Ctrl+O чтобы открыть") + if path: + last_media_path = path + ext = path.lower().rsplit('.', 1)[-1] if '.' in path else '' + if ext in ('jpg', 'jpeg', 'png', 'webp'): + emit(f"[TARGET]: {text} [Photo saved -> Ctrl+O]") + log_event("IN", f"{text} [photo: {path}]") + elif ext in ('mp4', 'mov', 'mkv'): + emit(f"[TARGET]: {text} [Video saved -> Ctrl+O]") + log_event("IN", f"{text} [video: {path}]") + elif ext in ('ogg', 'mp3', 'wav', 'm4a'): + emit(f"[TARGET]: {text} [Voice/Audio saved -> Ctrl+O]") + log_event("IN", f"{text} [audio: {path}]") + else: + emit(f"[TARGET]: {text} [File: {path} -> Ctrl+O]") + log_event("IN", f"{text} [file: {path}]") else: - text = text or "[Пустое сообщение]" - print(f"📩 [Таргет]: {text}") + emit(f"[TARGET]: {text or '[Empty message]'}") + log_event("IN", text or "[empty]") + + +# ==================== ОБРАБОТЧИК РЕДАКТИРОВАНИЙ ==================== +@client.on(events.MessageEdited) +async def edit_handler(event): + if not is_target_event(event): + return + + mid = event.message.id + if mid in local_sent_ids: + # Наше собственное редактирование (например, анимация) — не логируем как чужое + cache_message(mid, target_entity.id, event.out, event.text or "") + return + + new_text = event.text or "" + cached = message_cache.get(mid) + old_text = cached[2] if cached else "" + + direction = "OUT" if event.out else "IN" + if event.out: + emit(f"[EDIT (phone)] before: {old_text}") + emit(f"[EDIT (phone)] after: {new_text}") + else: + emit(f"[EDIT] before: {old_text}") + emit(f"[EDIT] after: {new_text}") + log_event(f"EDIT-{direction}", f"before: {old_text} || after: {new_text}") + + cache_message(mid, target_entity.id, event.out, new_text) + + +# ==================== ОБРАБОТЧИК УДАЛЕНИЙ ==================== +@client.on(events.MessageDeleted) +async def delete_handler(event): + if not event.deleted_ids: + return + for mid in event.deleted_ids: + cached = message_cache.pop(mid, None) + if not cached: + continue + cached_chat_id, is_out, text = cached + if target_entity and cached_chat_id != target_entity.id: + continue + direction = "OUT" if is_out else "IN" + emit(f"[DEL] <{direction}> {text or '[media/empty]'}") + log_event(f"DEL-{direction}", text or "[media/empty]") # ==================== ЦИКЛ ЧАТА ==================== async def chat_loop(): - global last_media_path + global pending_delete_at + session = PromptSession( - message="Вы ➔ ", + message="You > ", key_bindings=bindings, - bottom_toolbar=bottom_toolbar + bottom_toolbar=bottom_toolbar, ) - + while True: with patch_stdout(): try: text = await session.prompt_async() - text = text.strip() - - if text: - # Команда ручного открытия (если горячие клавиши не нравятся) - if text.lower() == "/open": - if last_media_path and os.path.exists(last_media_path): - print(f"📂 Открываю: {last_media_path}") - open_file(last_media_path) - else: - print("⚠️ Нет медиа для открытия!") - continue - - # Отправка файла - if text.startswith("/send "): - filepath = text[6:].strip().strip('"').strip("'") - - if os.path.exists(filepath): - print("⏳ Отправка файла...") - msg = await client.send_file(target_entity, filepath) - local_sent_ids.append(msg.id) - print("✅ Отправлено") - else: - print("❌ Файл не найден") - - # Отправка обычного сообщения - else: - msg = await client.send_message(target_entity, text) - local_sent_ids.append(msg.id) - - if len(local_sent_ids) > 50: - local_sent_ids.pop(0) - except (KeyboardInterrupt, EOFError): clear_screen() - print("\n🛑 Выход...") - await client.disconnect() - break + print("\n[SYSTEM] Disconnecting...") + try: + await client.disconnect() + except Exception: + pass + return + + if text is None: + continue + + text = text.strip() + + # === Результаты хоткеев === + if text == "__MUTE__": + set_mute(not mute_enabled) + continue + if text == "__OPEN__": + await open_last_media() + continue + if text == "__CLEAR__": + chat_history.clear() + redraw() + continue + if text == "__HELP__": + await show_help_and_return() + continue + if text == "__SPAM__": + await spam_dialog() + redraw() + continue + if text == "__LOG__": + toggle_logging() + continue + + if not text: + continue + + cmd = text.lower() + + if cmd == ".help": + await show_help_and_return() + continue + if cmd == ".mute": + set_mute(True) + continue + if cmd in (".unmute", ".umute"): + set_mute(False) + continue + if cmd == ".clear": + chat_history.clear() + redraw() + continue + if cmd == ".log": + toggle_logging() + continue + if cmd == ".log on": + toggle_logging(True) + continue + if cmd == ".log off": + toggle_logging(False) + continue + if cmd == ".status": + last = last_media_path or '—' + log_info = log_file_path if logging_enabled else 'OFF' + emit(f"[STATUS] Target: {target_name} (ID: {target_entity.id}) | " + f"Mute: {'ON' if mute_enabled else 'OFF'} | Log: {log_info} | Last media: {last}") + continue + if cmd == ".delete": + pending_delete_at = time.monotonic() + emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat for both sides.") + continue + if cmd == ".delete confirm": + if pending_delete_at and (time.monotonic() - pending_delete_at) < 20: + pending_delete_at = 0.0 + await purge_chat() + else: + emit("[SYSTEM] Nothing to confirm. Send `.delete` first.") + continue + if cmd == ".love": + asyncio.create_task(run_love_animation()) + continue + + # .spam N text + if cmd.startswith(".spam "): + rest = text[6:].strip() + parts = rest.split(maxsplit=1) + if len(parts) < 2: + emit("[ERROR] Format: .spam ") + continue + try: + count = int(parts[0]) + except ValueError: + emit("[ERROR] Count must be a number.") + continue + if count <= 0 or count > 500: + emit("[ERROR] Count must be between 1 and 500.") + continue + asyncio.create_task(do_spam(count, parts[1], 0.3)) + continue + + if cmd == "/open": + await open_last_media() + continue + + if text.lower().startswith("/send "): + filepath = text[6:].strip().strip('"').strip("'") + if os.path.exists(filepath): + emit(f"[SYSTEM] Sending: {filepath}") + try: + msg = await client.send_file(target_entity, filepath) + local_sent_ids.append(msg.id) + cache_message(msg.id, target_entity.id, True, f"[file: {filepath}]") + log_event("OUT", f"[file: {filepath}]") + emit("[SYSTEM] File sent.") + except Exception as e: + emit(f"[ERROR] Send failed: {e}") + else: + emit(f"[ERROR] File does not exist: {filepath}") + continue + + # Обычное сообщение + try: + msg = await client.send_message(target_entity, text) + local_sent_ids.append(msg.id) + cache_message(msg.id, target_entity.id, True, text) + log_event("OUT", text) + emit(f"[ME]: {text}") + except Exception as e: + emit(f"[ERROR] Send failed: {e}") # ==================== ОСНОВНОЙ ЗАПУСК ==================== async def main(): + global target_entity, target_name + clear_screen() - print("🔄 Подключение к серверам...\n") + print("[SYSTEM] Connecting to Telegram...\n") await client.connect() - + if not await client.is_user_authorized(): def print_qr(url): qr = qrcode.QRCode(version=1, box_size=1, border=2) qr.add_data(url) qr.make(fit=True) qr.print_ascii(invert=True) - + qr_login = await client.qr_login() - + while True: clear_screen() - print("⚠️ Требуется авторизация. Отсканируйте QR в Telegram:\n") + print("[AUTH] Scan the QR code via Telegram (Settings -> Devices -> Link Device):\n") print_qr(qr_login.url) - print("\n⏳ Ожидание (обновится через 10 сек)...") - + print("\nWaiting for scan (refreshing every 10s)...") + try: await qr_login.wait(10) break except asyncio.TimeoutError: try: await qr_login.recreate() - except: - qr_login = await client.qr_login() + except Exception as e: + print(f"[AUTH] Recreate failed: {e}") + try: + qr_login = await client.qr_login() + except Exception as e2: + print(f"[AUTH] QR login failed: {e2}") + await asyncio.sleep(3) except errors.SessionPasswordNeededError: clear_screen() while True: - pwd = input("🔒 Введите облачный пароль: ") + pwd = await asyncio.to_thread(input, "[AUTH] Enter 2FA Password: ") try: await client.sign_in(password=pwd) break - except: - print("❌ Неверный пароль!") + except Exception as e: + print(f"[ERROR] {e}") break - except Exception: - qr_login = await client.qr_login() - - global target_entity + except Exception as e: + print(f"[AUTH] {e}") + try: + qr_login = await client.qr_login() + except Exception as e2: + print(f"[AUTH] QR login failed: {e2}") + await asyncio.sleep(3) + clear_screen() - while True: try: - print("✅ Вход выполнен!\n") - target_input = input("👤 Введи ID, @username или номер собеседника: ").strip() + print("[AUTH] Authorized successfully.\n") + target_input = input("Enter target ID, @username or phone: ").strip() if not target_input: clear_screen() continue - + if target_input.lstrip('-').isdigit(): target_input = int(target_input) - - print("⏳ Поиск...") + + print("[SYSTEM] Resolving target...") target_entity = await client.get_entity(target_input) - target_name = getattr(target_entity, 'first_name', None) or getattr(target_entity, 'title', None) or "Пользователь" + target_name = ( + getattr(target_entity, 'first_name', None) + or getattr(target_entity, 'title', None) + or "Unknown" + ) break - - except Exception: + except Exception as e: clear_screen() - print("❌ Не найдено. Попробуй еще раз.") - - clear_screen() - print("="*55) - print(f"💬 ЧАТ: {target_name}") - print("💡 /send <путь> - отправить файл/фото") - print("💡 Ctrl+O (или команда /open) - открыть последнее фото/ГС") - print("💡 Ctrl+1 - вкл/выкл автоудаление") - print("💡 Ctrl+C - выход") - print("="*55 + "\n") - + print(f"[ERROR] Could not resolve entity: {e}. Try again.") + + redraw() await chat_loop() @@ -286,4 +834,4 @@ if __name__ == "__main__": asyncio.run(main()) except (KeyboardInterrupt, SystemExit): clear_screen() - print("Скрипт остановлен.") \ No newline at end of file + print("[SYSTEM] Script terminated.") \ No newline at end of file diff --git a/files/.gitkeep b/files/.gitkeep deleted file mode 100644 index e69de29..0000000