Files
TG/app.py
T
2026-10-01 17:23:41 +03:00

837 lines
27 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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):
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 | .clear clear | 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):
"""Включить/выключить логирование. 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 ====================
# Внутри <pre> шрифт моноширинный → любые символы по 1 клетке → идеально ровно.
# Пустые клетки заполнены "·" (U+00B7), чтобы сетка была видимой и ровной.
BIG_HEART = "\n".join([
"··♥♥··♥♥··",
"·♥♥♥♥♥♥♥♥·",
"♥♥♥♥♥♥♥♥♥♥",
"♥♥♥♥♥♥♥♥♥♥",
"♥♥♥♥♥♥♥♥♥♥",
"·♥♥♥♥♥♥♥♥·",
"··♥♥♥♥♥♥··",
"···♥♥♥♥···",
"····♥♥····",
"····♥♥····",
])
SMALL_HEART = "\n".join([
"··········",
"··♥♥♥♥♥♥··",
"·♥♥♥♥♥♥♥♥·",
"·♥♥♥♥♥♥♥♥·",
"··♥♥♥♥♥♥··",
"···♥♥♥♥···",
"····♥♥····",
"··········",
"··········",
"··········",
])
def _pre(text):
safe = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
return f"<pre>{safe}</pre>"
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):
emit(f"[SYSTEM] Opening: {last_media_path}")
open_file(last_media_path)
else:
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 <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(" 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 = "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 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 mid in local_sent_ids:
cache_message(mid, target_entity.id, True, 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 <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
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:
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)
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,
)
while True:
with patch_stdout():
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 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 <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 == "/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("[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)
clear_screen()
while True:
try:
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("[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"
)
break
except Exception as e:
clear_screen()
print(f"[ERROR] Could not resolve entity: {e}. Try again.")
redraw()
await chat_loop()
if __name__ == "__main__":
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
clear_screen()
print("[SYSTEM] Script terminated.")