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"
{safe}"
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