From be94bfdd5cc09e3133df13b758ebcd4861029b5e Mon Sep 17 00:00:00 2001 From: kirieska Date: Fri, 2 Oct 2026 01:25:36 +0200 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20app.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.py | 819 +++++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 559 insertions(+), 260 deletions(-) diff --git a/app.py b/app.py index aacce48..9a94231 100644 --- a/app.py +++ b/app.py @@ -67,20 +67,21 @@ target_entity = None target_name = "" mute_enabled = False local_sent_ids = deque(maxlen=200) +silent_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 +_self_id = None # ID своего аккаунта (для детекта Избранного) + def cache_message(mid, chat_id, is_out, text): message_cache[mid] = (chat_id, is_out, text) @@ -99,7 +100,6 @@ def emit(line=""): def log_event(kind, text): - """Записать событие в лог-файл (если логирование включено).""" if not logging_enabled or not log_file_path: return try: @@ -127,7 +127,7 @@ def print_header(): 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(" F1 help | F2 spam | F3 log | F4 type | .select <@user|ID> | Ctrl+C exit") print("=" * 60) @@ -145,7 +145,6 @@ def set_mute(state): def toggle_logging(force=None): - """Включить/выключить логирование. force=True/False — явно.""" global logging_enabled, log_file_path if force is None: @@ -158,7 +157,9 @@ def toggle_logging(force=None): return if new_state: - # Включаем: создаём новый файл + if target_entity is None: + emit("[ERROR] No target selected for logging.") + return 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") @@ -172,40 +173,36 @@ def toggle_logging(force=None): 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([
-    "··········",
-    "··♥♥♥♥♥♥··",
-    "·♥♥♥♥♥♥♥♥·",
-    "·♥♥♥♥♥♥♥♥·",
-    "··♥♥♥♥♥♥··",
-    "···♥♥♥♥···",
-    "····♥♥····",
-    "··········",
-    "··········",
-    "··········",
+    "🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
+    "🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
+    "🤍🤍❤️❤️🤍🤍❤️❤️🤍🤍",
+    "🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
+    "🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
+    "🤍🤍❤️❤️❤️❤️❤️❤️🤍🤍",
+    "🤍🤍🤍❤️❤️❤️❤️🤍🤍🤍",
+    "🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
+    "🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
+    "🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
 ])
 
 
@@ -215,7 +212,6 @@ def _pre(text):
 
 
 def _love_sequence():
-    """Пульс 10 сек, потом удаление."""
     seq = [(BIG_HEART, 0.5)]
     for _ in range(10):
         seq.append((SMALL_HEART, 0.5))
@@ -224,10 +220,16 @@ def _love_sequence():
 
 
 async def run_love_animation():
+    if target_entity is None:
+        emit("[ERROR] No target selected.")
+        return
     seq = _love_sequence()
     try:
         msg = await client.send_message(target_entity, _pre(seq[0][0]), parse_mode='html')
         local_sent_ids.append(msg.id)
+        silent_sent_ids.append(msg.id)
+        cache_message(msg.id, target_entity.id, True, "[love]")
+
         for frame, delay in seq[1:]:
             await asyncio.sleep(delay)
             try:
@@ -249,14 +251,74 @@ async def run_love_animation():
         emit(f"[ERROR] Animation failed: {e}")
 
 
+# ==================== АНИМАЦИЯ .type ====================
+async def run_type_animation(full_text, delay=0.15, prefix=""):
+    if target_entity is None:
+        emit("[ERROR] No target selected.")
+        return
+    if not full_text:
+        emit("[ERROR] Empty text for typing animation.")
+        return
+
+    try:
+        first = prefix + full_text[0]
+        msg = await client.send_message(target_entity, first if first.strip() else "\u200b")
+        local_sent_ids.append(msg.id)
+        silent_sent_ids.append(msg.id)
+        cache_message(msg.id, target_entity.id, True, first)
+
+        current = first
+        for ch in full_text[1:]:
+            await asyncio.sleep(delay)
+            current += ch
+            try:
+                await msg.edit(current)
+            except errors.FloodWaitError as f:
+                await asyncio.sleep(f.seconds + 1)
+                try: await msg.edit(current)
+                except Exception: pass
+            except Exception:
+                pass
+
+        await asyncio.sleep(max(0.4, delay * 2))
+        emit(f"[TYPE] Sent: {prefix}{full_text}")
+
+    except Exception as e:
+        emit(f"[ERROR] Type animation failed: {e}")
+
+
+async def type_dialog():
+    s = PromptSession()
+    try:
+        msg_text = await s.prompt_async("Text to type: ")
+        if not msg_text:
+            emit("[ERROR] Empty text.")
+            return
+        delay_str = await s.prompt_async("Delay per char [0.15]: ")
+        try:
+            delay = float(delay_str.strip() or "0.15")
+        except ValueError:
+            delay = 0.15
+        if delay < 0.05: delay = 0.05
+        if delay > 5: delay = 5
+    except (KeyboardInterrupt, EOFError):
+        emit("[SYSTEM] Type cancelled.")
+        return
+
+    await run_type_animation(msg_text, delay)
+
+
 # ==================== СПАМ ====================
 async def do_spam(count, msg_text, delay=0.3):
-    """Отправить msg_text `count` раз с задержкой delay."""
+    if target_entity is None:
+        emit("[ERROR] No target selected.")
+        return
     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)
+            silent_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:
@@ -271,7 +333,6 @@ async def do_spam(count, msg_text, delay=0.3):
 
 
 async def spam_dialog():
-    """Диалог для F2: count -> message -> delay."""
     s = PromptSession()
     try:
         count_str = await s.prompt_async("Spam count: ")
@@ -288,8 +349,7 @@ async def spam_dialog():
             delay = float(delay_str.strip() or "0.3")
         except ValueError:
             delay = 0.3
-        if delay < 0:
-            delay = 0
+        if delay < 0: delay = 0
     except (KeyboardInterrupt, EOFError):
         emit("[SYSTEM] Spam cancelled.")
         return
@@ -302,6 +362,9 @@ async def spam_dialog():
 
 # ==================== ХЕЛПЕРЫ ====================
 async def purge_chat():
+    if target_entity is None:
+        emit("[ERROR] No target selected.")
+        return
     try:
         await client.delete_dialog(target_entity, revoke=True)
         emit("[SYSTEM] Chat dialog completely deleted for both sides.")
@@ -324,6 +387,18 @@ def is_target_event(event):
     return getattr(event, 'chat_id', None) == target_entity.id
 
 
+def is_saved_messages(event):
+    """Сообщение в Избранном (Saved Messages)."""
+    if _self_id is None:
+        return False
+    if not event.out:
+        return False
+    try:
+        return event.chat_id == _self_id
+    except Exception:
+        return False
+
+
 async def open_last_media():
     if last_media_path and os.path.exists(last_media_path):
         emit(f"[SYSTEM] Opening: {last_media_path}")
@@ -332,6 +407,83 @@ async def open_last_media():
         emit("[SYSTEM] No media available to open.")
 
 
+# ==================== SELECT — СМЕНА ЦЕЛИ ====================
+async def _resolve_entity(query):
+    """Резолвит @username / ID / +phone. Возвращает (entity, error)."""
+    q = (query or "").strip()
+    if not q:
+        return None, "Пустой запрос"
+
+    arg = q
+    if q.lstrip('-').isdigit():
+        try:
+            arg = int(q)
+        except ValueError:
+            arg = q
+
+    try:
+        entity = await client.get_entity(arg)
+        return entity, None
+    except Exception as e:
+        return None, f"Не найдено: {str(e)[:120]}"
+
+
+def _apply_target(entity):
+    """Применяет новую цель + очищает историю консоли + маркер."""
+    global target_entity, target_name, logging_enabled, log_file_path, pending_delete_at
+
+    target_entity = entity
+    target_name = (
+        getattr(entity, 'first_name', None)
+        or getattr(entity, 'title', None)
+        or "Unknown"
+    )
+
+    pending_delete_at = 0.0
+    logging_enabled = False
+    log_file_path = None
+
+    chat_history.clear()
+    chat_history.append(f"[SYSTEM] Target switched: {target_name} (ID: {entity.id})")
+
+
+async def _auto_delete_msg(msg, ttl=2.0):
+    await asyncio.sleep(ttl)
+    try:
+        await msg.delete()
+    except Exception:
+        pass
+
+
+async def _send_temp_confirmation(chat_id, text, ttl=2.0):
+    """Отправить сообщение в чат и через ttl секунд удалить."""
+    try:
+        conf = await client.send_message(chat_id, text)
+        asyncio.create_task(_auto_delete_msg(conf, ttl))
+        return conf
+    except Exception:
+        return None
+
+
+async def handle_select_from_event(event, query):
+    """Обработка .select в Telegram (в цели ИЛИ в Избранном)."""
+    entity, err = await _resolve_entity(query)
+
+    # Удаляем команду из чата
+    try: await event.delete()
+    except Exception: pass
+
+    if entity is None:
+        emit(f"[ERROR] {err}")
+        await _send_temp_confirmation(event.chat_id, f"❌ {err}", 2.0)
+        return
+
+    _apply_target(entity)
+    msg = f"✅ Переключено на {target_name} (ID: {entity.id})"
+    await _send_temp_confirmation(event.chat_id, msg, 2.0)
+    redraw()
+
+
 # ==================== ЭКРАН СПРАВКИ ====================
 async def show_help_and_return():
     global in_overlay
@@ -341,11 +493,14 @@ async def show_help_and_return():
         print("=" * 60)
         print("                COMMAND REFERENCE")
         print("=" * 60)
+        print("  .select <@user|ID|+phone>  Switch target (works in Saved Msgs too)")
         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("  .type TEXT       Type TEXT character-by-character")
+        print("  .type D TEXT     Same, D = delay per char (sec)")
         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")
@@ -357,6 +512,7 @@ async def show_help_and_return():
         print("  F1               Help")
         print("  F2               Spam dialog (count -> message -> delay)")
         print("  F3               Toggle logging to file")
+        print("  F4               Typewriter dialog (text -> delay)")
         print("  Ctrl+O           Open last media")
         print("  Ctrl+T           Toggle mute")
         print("  Ctrl+L           Clear console history")
@@ -402,10 +558,16 @@ def _(event):
     event.app.exit(result="__LOG__")
 
 
+@bindings.add('f4')
+def _(event):
+    event.app.exit(result="__TYPE__")
+
+
 def bottom_toolbar():
     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 "
+    target = target_name[:24] if target_name else "(no target)"
+    return f" Target: {target} | Mute:{status} Log:{log_status} | F1 Help | Ctrl+O Open | Ctrl+C Exit "
 
 
 # ==================== ОБРАБОТЧИК НОВЫХ СООБЩЕНИЙ ====================
@@ -413,110 +575,191 @@ def bottom_toolbar():
 async def message_handler(event):
     global mute_enabled, last_media_path, pending_delete_at
 
-    if not is_target_event(event):
-        return
-
     text = event.text or ""
     mid = event.message.id
 
-    # === ИСХОДЯЩИЕ ===
+    in_target = is_target_event(event)
+    in_saved = is_saved_messages(event)
+
+    # ============ ИСХОДЯЩИЕ ============
     if event.out:
+        # silent (анимации / спам) — только пометить в кэш
+        if mid in silent_sent_ids:
+            if in_target:
+                cache_message(mid, target_entity.id, True, text)
+            return
+
+        # наш обычный send из консоли
         if mid in local_sent_ids:
-            cache_message(mid, target_entity.id, True, text)
+            if in_target:
+                cache_message(mid, target_entity.id, True, text)
+                if event.media:
+                    emit(f"[ME]: {text} [media]")
+                    log_event("OUT", f"{text} [media]")
+                else:
+                    emit(f"[ME]: {text}")
+                    log_event("OUT", text)
             return
 
         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  ")
+        # ============ .select — РАБОТАЕТ ВЕЗДЕ (цель + Избранное) ============
+        if (in_target or in_saved) and cmd.startswith(".select"):
+            parts = text.split(maxsplit=1)
+            query = parts[1].strip() if len(parts) > 1 else ""
+            if not query:
+                try: await event.delete()
+                except Exception: pass
+                await _send_temp_confirmation(
+                    event.chat_id,
+                    "❌ Формат: .select @user | ID | +phone",
+                    2.0,
+                )
                 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}")
+            await handle_select_from_event(event, query)
             return
 
-        # Обычное исходящее (с телефона или из другого клиента)
-        cache_message(mid, target_entity.id, True, text)
-        if event.media:
-            emit(f"[ME (phone)]: {text} [media]")
-            log_event("OUT", f"{text} [media]")
-        else:
-            emit(f"[ME (phone)]: {text}")
-            log_event("OUT", text)
+        # ============ ОСТАЛЬНЫЕ КОМАНДЫ — ТОЛЬКО В ЦЕЛИ ============
+        if in_target:
+            # .mute
+            if cmd == ".mute":
+                try: await event.delete()
+                except Exception: pass
+                set_mute(True)
+                return
+
+            # .unmute
+            if cmd in (".unmute", ".umute"):
+                try: await event.delete()
+                except Exception: pass
+                set_mute(False)
+                return
+
+            # .log
+            if cmd == ".log":
+                try: await event.delete()
+                except Exception: pass
+                toggle_logging()
+                return
+            if cmd == ".log on":
+                try: await event.delete()
+                except Exception: pass
+                toggle_logging(True)
+                return
+            if cmd == ".log off":
+                try: await event.delete()
+                except Exception: pass
+                toggle_logging(False)
+                return
+
+            # .love
+            if cmd == ".love":
+                try: await event.delete()
+                except Exception: pass
+                asyncio.create_task(run_love_animation())
+                return
+
+            # .clear
+            if cmd == ".clear":
+                try: await event.delete()
+                except Exception: pass
+                chat_history.clear()
+                emit("[SYSTEM] Console history cleared.")
+                return
+
+            # .delete
+            if cmd == ".delete":
+                try: await event.delete()
+                except Exception: pass
+                pending_delete_at = time.monotonic()
+                emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat.")
+                return
+            if 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
+
+            # .spam
+            if 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
+
+            # .type
+            if cmd.startswith(".type "):
+                try: await event.delete()
+                except Exception: pass
+                rest = text[6:].strip()
+                if not rest:
+                    emit("[ERROR] Format: .type  or .type  ")
+                    return
+                parts = rest.split(maxsplit=1)
+                try:
+                    delay = float(parts[0])
+                    if len(parts) < 2:
+                        emit("[ERROR] Format: .type  ")
+                        return
+                    body = parts[1]
+                except ValueError:
+                    delay = 0.15
+                    body = rest
+                if delay < 0.05: delay = 0.05
+                if delay > 5: delay = 5
+                asyncio.create_task(run_type_animation(body, delay))
+                return
+
+            # .status
+            if 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
+
+            # .help — тоже только в цели
+            if cmd == ".help":
+                try: await event.delete()
+                except Exception: pass
+                emit("[SYSTEM] Commands: .select .mute .unmute .log [on|off] .love "
+                     ".type  .spam   .status .delete .clear")
+                return
+
+            # обычное исходящее с телефона в цели
+            cache_message(mid, target_entity.id, True, text)
+            if event.media:
+                emit(f"[ME (phone)]: {text} [media]")
+                log_event("OUT", f"{text} [media]")
+            else:
+                emit(f"[ME (phone)]: {text}")
+                log_event("OUT", text)
+        # если сообщение в Избранном и это НЕ .select — просто молча игнор
+        return
+
+    # ============ ВХОДЯЩИЕ ============
+    if not in_target:
         return
 
-    # === ВХОДЯЩИЕ ===
-    # Кешируем ВСЕГДА, до любых действий
     cache_message(mid, target_entity.id, False, text)
 
     if mute_enabled:
@@ -549,7 +792,7 @@ async def message_handler(event):
                 log_event("IN", f"{text} [audio: {path}]")
             else:
                 emit(f"[TARGET]: {text} [File: {path} -> Ctrl+O]")
-                log_event("IN", f"{text} [file: {path}]")
+                log_event("IN", f"[text] [file: {path}]")
     else:
         emit(f"[TARGET]: {text or '[Empty message]'}")
         log_event("IN", text or "[empty]")
@@ -563,7 +806,6 @@ async def edit_handler(event):
 
     mid = event.message.id
     if mid in local_sent_ids:
-        # Наше собственное редактирование (например, анимация) — не логируем как чужое
         cache_message(mid, target_entity.id, event.out, event.text or "")
         return
 
@@ -610,8 +852,8 @@ async def chat_loop():
         bottom_toolbar=bottom_toolbar,
     )
 
-    while True:
-        with patch_stdout():
+    with patch_stdout():
+        while True:
             try:
                 text = await session.prompt_async()
             except (KeyboardInterrupt, EOFError):
@@ -623,133 +865,185 @@ async def chat_loop():
                     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  ")
+            if text is None:
                 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
+            text = text.strip()
 
-        if text.lower().startswith("/send "):
-            filepath = text[6:].strip().strip('"').strip("'")
-            if os.path.exists(filepath):
-                emit(f"[SYSTEM] Sending: {filepath}")
+            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 text == "__TYPE__":
+                await type_dialog()
+                redraw()
+                continue
+
+            if not text:
+                continue
+
+            cmd = text.lower()
+
+            if cmd == ".help":
+                await show_help_and_return()
+                continue
+
+            # .select <@user|ID|+phone>
+            if cmd.startswith(".select"):
+                parts = text.split(maxsplit=1)
+                if len(parts) < 2 or not parts[1].strip():
+                    emit("[ERROR] Format: .select @user | ID | +phone")
+                    continue
+                entity, err = await _resolve_entity(parts[1])
+                if entity is None:
+                    emit(f"[ERROR] {err}")
+                    continue
+                _apply_target(entity)
+                redraw()
+                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'
+                tid = target_entity.id if target_entity else '—'
+                emit(f"[STATUS] {target_name or '—'} ({tid}) | "
+                     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.")
+                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
+
+            if cmd.startswith(".spam "):
+                rest = text[6:].strip()
+                parts = rest.split(maxsplit=1)
+                if len(parts) < 2:
+                    emit("[ERROR] Format: .spam  ")
+                    continue
                 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
+                    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
 
-        # Обычное сообщение
-        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}")
+            if cmd.startswith(".type "):
+                rest = text[6:].strip()
+                if not rest:
+                    emit("[ERROR] Format: .type  or .type  ")
+                    continue
+                parts = rest.split(maxsplit=1)
+                try:
+                    delay = float(parts[0])
+                    if len(parts) < 2:
+                        emit("[ERROR] Format: .type  ")
+                        continue
+                    body = parts[1]
+                except ValueError:
+                    delay = 0.15
+                    body = rest
+                if delay < 0.05: delay = 0.05
+                if delay > 5: delay = 5
+                asyncio.create_task(run_type_animation(body, delay))
+                continue
+
+            if cmd == "/open":
+                await open_last_media()
+                continue
+
+            if text.lower().startswith("/send "):
+                if target_entity is None:
+                    emit("[ERROR] No target selected. Use .select <@user|ID>.")
+                    continue
+                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)
+                        silent_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
+
+            # если цели нет — пробуем как цель
+            if target_entity is None:
+                entity, err = await _resolve_entity(text)
+                if entity is None:
+                    emit(f"[ERROR] {err}")
+                    emit("[SYSTEM] Use .select <@user|ID|+phone> to pick a target.")
+                else:
+                    _apply_target(entity)
+                    redraw()
+                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)
+            except Exception as e:
+                emit(f"[ERROR] Send failed: {e}")
 
 
 # ==================== ОСНОВНОЙ ЗАПУСК ====================
 async def main():
-    global target_entity, target_name
+    global target_entity, target_name, _self_id
 
     clear_screen()
     print("[SYSTEM] Connecting to Telegram...\n")
@@ -801,29 +1095,34 @@ async def main():
                     print(f"[AUTH] QR login failed: {e2}")
                     await asyncio.sleep(3)
 
+    # Узнаём свой ID (для детекта Избранного)
+    try:
+        me = await client.get_me()
+        if me:
+            _self_id = me.id
+    except Exception:
+        pass
+
     clear_screen()
     while True:
         try:
             print("[AUTH] Authorized successfully.\n")
-            target_input = input("Enter target ID, @username or phone: ").strip()
+            target_input = input("Enter target ID, @username or phone (or Enter to skip): ").strip()
             if not target_input:
+                break
+
+            entity, err = await _resolve_entity(target_input)
+            if entity is None:
                 clear_screen()
+                print(f"[ERROR] {err}")
+                print("Try again, or press Enter to skip (select later via .select).\n")
                 continue
 
-            if target_input.lstrip('-').isdigit():
-                target_input = int(target_input)
-
-            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 "Unknown"
-            )
+            _apply_target(entity)
             break
         except Exception as e:
             clear_screen()
-            print(f"[ERROR] Could not resolve entity: {e}. Try again.")
+            print(f"[ERROR] {e}. Try again.")
 
     redraw()
     await chat_loop()