1136 lines
38 KiB
Python
1136 lines
38 KiB
Python
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)
|
|
silent_sent_ids = deque(maxlen=200)
|
|
last_media_path = None
|
|
pending_delete_at = 0.0
|
|
in_overlay = False
|
|
|
|
chat_history = deque(maxlen=1500)
|
|
|
|
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)
|
|
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):
|
|
try:
|
|
if sys.platform == 'win32':
|
|
os.startfile(path)
|
|
elif sys.platform == 'darwin':
|
|
subprocess.call(['open', path])
|
|
else:
|
|
subprocess.call(['xdg-open', path])
|
|
except Exception as e:
|
|
emit(f"[ERROR] Failed to open file: {e}")
|
|
|
|
|
|
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 | F4 type | .select <@user|ID> | Ctrl+C exit")
|
|
print("=" * 60)
|
|
|
|
|
|
def redraw():
|
|
clear_screen()
|
|
print_header()
|
|
for line in chat_history:
|
|
print(line)
|
|
|
|
|
|
def set_mute(state):
|
|
global mute_enabled
|
|
mute_enabled = state
|
|
emit(f"[SYSTEM] Mute: {'ON' if mute_enabled else 'OFF'}")
|
|
|
|
|
|
def toggle_logging(force=None):
|
|
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:
|
|
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")
|
|
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 ====================
|
|
BIG_HEART = "\n".join([
|
|
"🤍🤍❤️❤️🤍🤍❤️❤️🤍🤍",
|
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
|
"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️",
|
|
"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️",
|
|
"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️",
|
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
|
"🤍🤍❤️❤️❤️❤️❤️❤️🤍🤍",
|
|
"🤍🤍🤍❤️❤️❤️❤️🤍🤍🤍",
|
|
"🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
|
|
"🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
|
|
])
|
|
|
|
SMALL_HEART = "\n".join([
|
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
|
"🤍🤍❤️❤️🤍🤍❤️❤️🤍🤍",
|
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
|
"🤍🤍❤️❤️❤️❤️❤️❤️🤍🤍",
|
|
"🤍🤍🤍❤️❤️❤️❤️🤍🤍🤍",
|
|
"🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
|
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
|
])
|
|
|
|
|
|
def _pre(text):
|
|
safe = text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
return f"<pre>{safe}</pre>"
|
|
|
|
|
|
def _love_sequence():
|
|
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():
|
|
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:
|
|
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}")
|
|
|
|
|
|
# ==================== АНИМАЦИЯ .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):
|
|
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:
|
|
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():
|
|
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():
|
|
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.")
|
|
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
|
|
|
|
|
|
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}")
|
|
open_file(last_media_path)
|
|
else:
|
|
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
|
|
in_overlay = True
|
|
try:
|
|
clear_screen()
|
|
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")
|
|
print(" .status Show current status")
|
|
print(" .help Show this screen")
|
|
print(" /send <path> 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(" F4 Typewriter dialog (text -> delay)")
|
|
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__")
|
|
|
|
|
|
@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"
|
|
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 "
|
|
|
|
|
|
# ==================== ОБРАБОТЧИК НОВЫХ СООБЩЕНИЙ ====================
|
|
@client.on(events.NewMessage)
|
|
async def message_handler(event):
|
|
global mute_enabled, last_media_path, pending_delete_at
|
|
|
|
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:
|
|
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()
|
|
|
|
# ============ .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
|
|
await handle_select_from_event(event, query)
|
|
return
|
|
|
|
# ============ ОСТАЛЬНЫЕ КОМАНДЫ — ТОЛЬКО В ЦЕЛИ ============
|
|
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 <count> <message>")
|
|
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 <text> or .type <delay> <text>")
|
|
return
|
|
parts = rest.split(maxsplit=1)
|
|
try:
|
|
delay = float(parts[0])
|
|
if len(parts) < 2:
|
|
emit("[ERROR] Format: .type <delay> <text>")
|
|
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 <t> .spam <N> <t> .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:
|
|
try:
|
|
await event.delete(revoke=True)
|
|
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:
|
|
try:
|
|
path = await event.download_media(file="files/")
|
|
except Exception as e:
|
|
emit(f"[ERROR] Download failed: {e}")
|
|
return
|
|
|
|
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:
|
|
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 "<unknown>"
|
|
|
|
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 pending_delete_at
|
|
|
|
session = PromptSession(
|
|
message="You > ",
|
|
key_bindings=bindings,
|
|
bottom_toolbar=bottom_toolbar,
|
|
)
|
|
|
|
with patch_stdout():
|
|
while True:
|
|
try:
|
|
text = await session.prompt_async()
|
|
except (KeyboardInterrupt, EOFError):
|
|
clear_screen()
|
|
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 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 <count> <message>")
|
|
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.startswith(".type "):
|
|
rest = text[6:].strip()
|
|
if not rest:
|
|
emit("[ERROR] Format: .type <text> or .type <delay> <text>")
|
|
continue
|
|
parts = rest.split(maxsplit=1)
|
|
try:
|
|
delay = float(parts[0])
|
|
if len(parts) < 2:
|
|
emit("[ERROR] Format: .type <delay> <text>")
|
|
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, _self_id
|
|
|
|
clear_screen()
|
|
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("[AUTH] Scan the QR code via Telegram (Settings -> Devices -> Link Device):\n")
|
|
print_qr(qr_login.url)
|
|
print("\nWaiting for scan (refreshing every 10s)...")
|
|
|
|
try:
|
|
await qr_login.wait(10)
|
|
break
|
|
except asyncio.TimeoutError:
|
|
try:
|
|
await qr_login.recreate()
|
|
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 = await asyncio.to_thread(input, "[AUTH] Enter 2FA Password: ")
|
|
try:
|
|
await client.sign_in(password=pwd)
|
|
break
|
|
except Exception as e:
|
|
print(f"[ERROR] {e}")
|
|
break
|
|
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)
|
|
|
|
# Узнаём свой 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 (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
|
|
|
|
_apply_target(entity)
|
|
break
|
|
except Exception as e:
|
|
clear_screen()
|
|
print(f"[ERROR] {e}. Try again.")
|
|
|
|
redraw()
|
|
await chat_loop()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
asyncio.run(main())
|
|
except (KeyboardInterrupt, SystemExit):
|
|
clear_screen()
|
|
print("[SYSTEM] Script terminated.") |