Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be94bfdd5c |
@@ -67,20 +67,21 @@ target_entity = None
|
|||||||
target_name = ""
|
target_name = ""
|
||||||
mute_enabled = False
|
mute_enabled = False
|
||||||
local_sent_ids = deque(maxlen=200)
|
local_sent_ids = deque(maxlen=200)
|
||||||
|
silent_sent_ids = deque(maxlen=200)
|
||||||
last_media_path = None
|
last_media_path = None
|
||||||
pending_delete_at = 0.0
|
pending_delete_at = 0.0
|
||||||
in_overlay = False
|
in_overlay = False
|
||||||
|
|
||||||
chat_history = deque(maxlen=1500)
|
chat_history = deque(maxlen=1500)
|
||||||
|
|
||||||
# Кеш последних сообщений: {msg_id: (chat_id, is_out, text)}
|
|
||||||
message_cache = OrderedDict()
|
message_cache = OrderedDict()
|
||||||
MAX_CACHE = 500
|
MAX_CACHE = 500
|
||||||
|
|
||||||
# Логирование в файл
|
|
||||||
logging_enabled = False
|
logging_enabled = False
|
||||||
log_file_path = None
|
log_file_path = None
|
||||||
|
|
||||||
|
_self_id = None # ID своего аккаунта (для детекта Избранного)
|
||||||
|
|
||||||
|
|
||||||
def cache_message(mid, chat_id, is_out, text):
|
def cache_message(mid, chat_id, is_out, text):
|
||||||
message_cache[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):
|
def log_event(kind, text):
|
||||||
"""Записать событие в лог-файл (если логирование включено)."""
|
|
||||||
if not logging_enabled or not log_file_path:
|
if not logging_enabled or not log_file_path:
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
@@ -127,7 +127,7 @@ def print_header():
|
|||||||
log_status = "ON" if logging_enabled else "OFF"
|
log_status = "ON" if logging_enabled else "OFF"
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print(f" CHAT: {target_name} (ID: {tid}) Mute: {'ON' if mute_enabled else 'OFF'} Log: {log_status}")
|
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)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
@@ -145,7 +145,6 @@ def set_mute(state):
|
|||||||
|
|
||||||
|
|
||||||
def toggle_logging(force=None):
|
def toggle_logging(force=None):
|
||||||
"""Включить/выключить логирование. force=True/False — явно."""
|
|
||||||
global logging_enabled, log_file_path
|
global logging_enabled, log_file_path
|
||||||
|
|
||||||
if force is None:
|
if force is None:
|
||||||
@@ -158,7 +157,9 @@ def toggle_logging(force=None):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if new_state:
|
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')
|
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"
|
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")
|
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}")
|
emit(f"[ERROR] Cannot create log file: {e}")
|
||||||
log_file_path = None
|
log_file_path = None
|
||||||
else:
|
else:
|
||||||
# Выключаем
|
|
||||||
emit(f"[SYSTEM] Logging OFF. Saved: {log_file_path}")
|
emit(f"[SYSTEM] Logging OFF. Saved: {log_file_path}")
|
||||||
logging_enabled = False
|
logging_enabled = False
|
||||||
log_file_path = None
|
log_file_path = None
|
||||||
|
|
||||||
|
|
||||||
# ==================== АНИМАЦИЯ .love ====================
|
# ==================== АНИМАЦИЯ .love ====================
|
||||||
# Внутри <pre> шрифт моноширинный → любые символы по 1 клетке → идеально ровно.
|
|
||||||
# Пустые клетки заполнены "·" (U+00B7), чтобы сетка была видимой и ровной.
|
|
||||||
|
|
||||||
BIG_HEART = "\n".join([
|
BIG_HEART = "\n".join([
|
||||||
"··♥♥··♥♥··",
|
"🤍🤍❤️❤️🤍🤍❤️❤️🤍🤍",
|
||||||
"·♥♥♥♥♥♥♥♥·",
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
||||||
"♥♥♥♥♥♥♥♥♥♥",
|
"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️",
|
||||||
"♥♥♥♥♥♥♥♥♥♥",
|
"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️",
|
||||||
"♥♥♥♥♥♥♥♥♥♥",
|
"❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️",
|
||||||
"·♥♥♥♥♥♥♥♥·",
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
||||||
"··♥♥♥♥♥♥··",
|
"🤍🤍❤️❤️❤️❤️❤️❤️🤍🤍",
|
||||||
"···♥♥♥♥···",
|
"🤍🤍🤍❤️❤️❤️❤️🤍🤍🤍",
|
||||||
"····♥♥····",
|
"🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
|
||||||
"····♥♥····",
|
"🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
|
||||||
])
|
])
|
||||||
|
|
||||||
SMALL_HEART = "\n".join([
|
SMALL_HEART = "\n".join([
|
||||||
"··········",
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
||||||
"··♥♥♥♥♥♥··",
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
||||||
"·♥♥♥♥♥♥♥♥·",
|
"🤍🤍❤️❤️🤍🤍❤️❤️🤍🤍",
|
||||||
"·♥♥♥♥♥♥♥♥·",
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
||||||
"··♥♥♥♥♥♥··",
|
"🤍❤️❤️❤️❤️❤️❤️❤️❤️🤍",
|
||||||
"···♥♥♥♥···",
|
"🤍🤍❤️❤️❤️❤️❤️❤️🤍🤍",
|
||||||
"····♥♥····",
|
"🤍🤍🤍❤️❤️❤️❤️🤍🤍🤍",
|
||||||
"··········",
|
"🤍🤍🤍🤍❤️❤️🤍🤍🤍🤍",
|
||||||
"··········",
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
||||||
"··········",
|
"🤍🤍🤍🤍🤍🤍🤍🤍🤍🤍",
|
||||||
])
|
])
|
||||||
|
|
||||||
|
|
||||||
@@ -215,7 +212,6 @@ def _pre(text):
|
|||||||
|
|
||||||
|
|
||||||
def _love_sequence():
|
def _love_sequence():
|
||||||
"""Пульс 10 сек, потом удаление."""
|
|
||||||
seq = [(BIG_HEART, 0.5)]
|
seq = [(BIG_HEART, 0.5)]
|
||||||
for _ in range(10):
|
for _ in range(10):
|
||||||
seq.append((SMALL_HEART, 0.5))
|
seq.append((SMALL_HEART, 0.5))
|
||||||
@@ -224,10 +220,16 @@ def _love_sequence():
|
|||||||
|
|
||||||
|
|
||||||
async def run_love_animation():
|
async def run_love_animation():
|
||||||
|
if target_entity is None:
|
||||||
|
emit("[ERROR] No target selected.")
|
||||||
|
return
|
||||||
seq = _love_sequence()
|
seq = _love_sequence()
|
||||||
try:
|
try:
|
||||||
msg = await client.send_message(target_entity, _pre(seq[0][0]), parse_mode='html')
|
msg = await client.send_message(target_entity, _pre(seq[0][0]), parse_mode='html')
|
||||||
local_sent_ids.append(msg.id)
|
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:]:
|
for frame, delay in seq[1:]:
|
||||||
await asyncio.sleep(delay)
|
await asyncio.sleep(delay)
|
||||||
try:
|
try:
|
||||||
@@ -249,14 +251,74 @@ async def run_love_animation():
|
|||||||
emit(f"[ERROR] Animation failed: {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):
|
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)...")
|
emit(f"[SPAM] Sending {count} messages (delay {delay}s)...")
|
||||||
for i in range(count):
|
for i in range(count):
|
||||||
try:
|
try:
|
||||||
m = await client.send_message(target_entity, msg_text)
|
m = await client.send_message(target_entity, msg_text)
|
||||||
local_sent_ids.append(m.id)
|
local_sent_ids.append(m.id)
|
||||||
|
silent_sent_ids.append(m.id)
|
||||||
cache_message(m.id, target_entity.id, True, msg_text)
|
cache_message(m.id, target_entity.id, True, msg_text)
|
||||||
log_event("OUT-SPAM", msg_text)
|
log_event("OUT-SPAM", msg_text)
|
||||||
except errors.FloodWaitError as f:
|
except errors.FloodWaitError as f:
|
||||||
@@ -271,7 +333,6 @@ async def do_spam(count, msg_text, delay=0.3):
|
|||||||
|
|
||||||
|
|
||||||
async def spam_dialog():
|
async def spam_dialog():
|
||||||
"""Диалог для F2: count -> message -> delay."""
|
|
||||||
s = PromptSession()
|
s = PromptSession()
|
||||||
try:
|
try:
|
||||||
count_str = await s.prompt_async("Spam count: ")
|
count_str = await s.prompt_async("Spam count: ")
|
||||||
@@ -288,8 +349,7 @@ async def spam_dialog():
|
|||||||
delay = float(delay_str.strip() or "0.3")
|
delay = float(delay_str.strip() or "0.3")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
delay = 0.3
|
delay = 0.3
|
||||||
if delay < 0:
|
if delay < 0: delay = 0
|
||||||
delay = 0
|
|
||||||
except (KeyboardInterrupt, EOFError):
|
except (KeyboardInterrupt, EOFError):
|
||||||
emit("[SYSTEM] Spam cancelled.")
|
emit("[SYSTEM] Spam cancelled.")
|
||||||
return
|
return
|
||||||
@@ -302,6 +362,9 @@ async def spam_dialog():
|
|||||||
|
|
||||||
# ==================== ХЕЛПЕРЫ ====================
|
# ==================== ХЕЛПЕРЫ ====================
|
||||||
async def purge_chat():
|
async def purge_chat():
|
||||||
|
if target_entity is None:
|
||||||
|
emit("[ERROR] No target selected.")
|
||||||
|
return
|
||||||
try:
|
try:
|
||||||
await client.delete_dialog(target_entity, revoke=True)
|
await client.delete_dialog(target_entity, revoke=True)
|
||||||
emit("[SYSTEM] Chat dialog completely deleted for both sides.")
|
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
|
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():
|
async def open_last_media():
|
||||||
if last_media_path and os.path.exists(last_media_path):
|
if last_media_path and os.path.exists(last_media_path):
|
||||||
emit(f"[SYSTEM] Opening: {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.")
|
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():
|
async def show_help_and_return():
|
||||||
global in_overlay
|
global in_overlay
|
||||||
@@ -341,11 +493,14 @@ async def show_help_and_return():
|
|||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print(" COMMAND REFERENCE")
|
print(" COMMAND REFERENCE")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
print(" .select <@user|ID|+phone> Switch target (works in Saved Msgs too)")
|
||||||
print(" .mute Auto-delete incoming messages")
|
print(" .mute Auto-delete incoming messages")
|
||||||
print(" .unmute Disable auto-delete")
|
print(" .unmute Disable auto-delete")
|
||||||
print(" .delete Request chat wipe (then confirm in 20s)")
|
print(" .delete Request chat wipe (then confirm in 20s)")
|
||||||
print(" .delete confirm Confirm chat wipe for both sides")
|
print(" .delete confirm Confirm chat wipe for both sides")
|
||||||
print(" .love Pulsing heart animation (10 sec, self-deletes)")
|
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(" .log [on|off] Toggle/control chat logging to file")
|
||||||
print(" .spam N TEXT Send TEXT N times (e.g. .spam 5 hello)")
|
print(" .spam N TEXT Send TEXT N times (e.g. .spam 5 hello)")
|
||||||
print(" .clear Clear console chat history")
|
print(" .clear Clear console chat history")
|
||||||
@@ -357,6 +512,7 @@ async def show_help_and_return():
|
|||||||
print(" F1 Help")
|
print(" F1 Help")
|
||||||
print(" F2 Spam dialog (count -> message -> delay)")
|
print(" F2 Spam dialog (count -> message -> delay)")
|
||||||
print(" F3 Toggle logging to file")
|
print(" F3 Toggle logging to file")
|
||||||
|
print(" F4 Typewriter dialog (text -> delay)")
|
||||||
print(" Ctrl+O Open last media")
|
print(" Ctrl+O Open last media")
|
||||||
print(" Ctrl+T Toggle mute")
|
print(" Ctrl+T Toggle mute")
|
||||||
print(" Ctrl+L Clear console history")
|
print(" Ctrl+L Clear console history")
|
||||||
@@ -402,10 +558,16 @@ def _(event):
|
|||||||
event.app.exit(result="__LOG__")
|
event.app.exit(result="__LOG__")
|
||||||
|
|
||||||
|
|
||||||
|
@bindings.add('f4')
|
||||||
|
def _(event):
|
||||||
|
event.app.exit(result="__TYPE__")
|
||||||
|
|
||||||
|
|
||||||
def bottom_toolbar():
|
def bottom_toolbar():
|
||||||
status = "ON" if mute_enabled else "OFF"
|
status = "ON" if mute_enabled else "OFF"
|
||||||
log_status = "ON" if logging_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,37 +575,106 @@ def bottom_toolbar():
|
|||||||
async def message_handler(event):
|
async def message_handler(event):
|
||||||
global mute_enabled, last_media_path, pending_delete_at
|
global mute_enabled, last_media_path, pending_delete_at
|
||||||
|
|
||||||
if not is_target_event(event):
|
|
||||||
return
|
|
||||||
|
|
||||||
text = event.text or ""
|
text = event.text or ""
|
||||||
mid = event.message.id
|
mid = event.message.id
|
||||||
|
|
||||||
# === ИСХОДЯЩИЕ ===
|
in_target = is_target_event(event)
|
||||||
|
in_saved = is_saved_messages(event)
|
||||||
|
|
||||||
|
# ============ ИСХОДЯЩИЕ ============
|
||||||
if event.out:
|
if event.out:
|
||||||
if mid in local_sent_ids:
|
# silent (анимации / спам) — только пометить в кэш
|
||||||
|
if mid in silent_sent_ids:
|
||||||
|
if in_target:
|
||||||
cache_message(mid, target_entity.id, True, text)
|
cache_message(mid, target_entity.id, True, text)
|
||||||
return
|
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()
|
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":
|
if cmd == ".mute":
|
||||||
try: await event.delete()
|
try: await event.delete()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
set_mute(True)
|
set_mute(True)
|
||||||
return
|
return
|
||||||
elif cmd in (".unmute", ".umute"):
|
|
||||||
|
# .unmute
|
||||||
|
if cmd in (".unmute", ".umute"):
|
||||||
try: await event.delete()
|
try: await event.delete()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
set_mute(False)
|
set_mute(False)
|
||||||
return
|
return
|
||||||
elif cmd == ".delete":
|
|
||||||
|
# .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()
|
try: await event.delete()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
pending_delete_at = time.monotonic()
|
pending_delete_at = time.monotonic()
|
||||||
emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat for both sides.")
|
emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat.")
|
||||||
return
|
return
|
||||||
elif cmd == ".delete confirm":
|
if cmd == ".delete confirm":
|
||||||
try: await event.delete()
|
try: await event.delete()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
if pending_delete_at and (time.monotonic() - pending_delete_at) < 20:
|
if pending_delete_at and (time.monotonic() - pending_delete_at) < 20:
|
||||||
@@ -452,33 +683,9 @@ async def message_handler(event):
|
|||||||
else:
|
else:
|
||||||
emit("[SYSTEM] Nothing to confirm. Send `.delete` first.")
|
emit("[SYSTEM] Nothing to confirm. Send `.delete` first.")
|
||||||
return
|
return
|
||||||
elif cmd == ".love":
|
|
||||||
try: await event.delete()
|
# .spam
|
||||||
except Exception: pass
|
if cmd.startswith(".spam "):
|
||||||
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()
|
try: await event.delete()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
rest = text[6:].strip()
|
rest = text[6:].strip()
|
||||||
@@ -496,7 +703,32 @@ async def message_handler(event):
|
|||||||
return
|
return
|
||||||
asyncio.create_task(do_spam(count, parts[1], 0.3))
|
asyncio.create_task(do_spam(count, parts[1], 0.3))
|
||||||
return
|
return
|
||||||
elif cmd == ".status":
|
|
||||||
|
# .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()
|
try: await event.delete()
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
last = last_media_path or '—'
|
last = last_media_path or '—'
|
||||||
@@ -505,7 +737,15 @@ async def message_handler(event):
|
|||||||
f"Mute: {'ON' if mute_enabled else 'OFF'} | Log: {log_info} | Last media: {last}")
|
f"Mute: {'ON' if mute_enabled else 'OFF'} | Log: {log_info} | Last media: {last}")
|
||||||
return
|
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)
|
cache_message(mid, target_entity.id, True, text)
|
||||||
if event.media:
|
if event.media:
|
||||||
emit(f"[ME (phone)]: {text} [media]")
|
emit(f"[ME (phone)]: {text} [media]")
|
||||||
@@ -513,10 +753,13 @@ async def message_handler(event):
|
|||||||
else:
|
else:
|
||||||
emit(f"[ME (phone)]: {text}")
|
emit(f"[ME (phone)]: {text}")
|
||||||
log_event("OUT", text)
|
log_event("OUT", text)
|
||||||
|
# если сообщение в Избранном и это НЕ .select — просто молча игнор
|
||||||
|
return
|
||||||
|
|
||||||
|
# ============ ВХОДЯЩИЕ ============
|
||||||
|
if not in_target:
|
||||||
return
|
return
|
||||||
|
|
||||||
# === ВХОДЯЩИЕ ===
|
|
||||||
# Кешируем ВСЕГДА, до любых действий
|
|
||||||
cache_message(mid, target_entity.id, False, text)
|
cache_message(mid, target_entity.id, False, text)
|
||||||
|
|
||||||
if mute_enabled:
|
if mute_enabled:
|
||||||
@@ -549,7 +792,7 @@ async def message_handler(event):
|
|||||||
log_event("IN", f"{text} [audio: {path}]")
|
log_event("IN", f"{text} [audio: {path}]")
|
||||||
else:
|
else:
|
||||||
emit(f"[TARGET]: {text} [File: {path} -> Ctrl+O]")
|
emit(f"[TARGET]: {text} [File: {path} -> Ctrl+O]")
|
||||||
log_event("IN", f"{text} [file: {path}]")
|
log_event("IN", f"[text] [file: {path}]")
|
||||||
else:
|
else:
|
||||||
emit(f"[TARGET]: {text or '[Empty message]'}")
|
emit(f"[TARGET]: {text or '[Empty message]'}")
|
||||||
log_event("IN", text or "[empty]")
|
log_event("IN", text or "[empty]")
|
||||||
@@ -563,7 +806,6 @@ async def edit_handler(event):
|
|||||||
|
|
||||||
mid = event.message.id
|
mid = event.message.id
|
||||||
if mid in local_sent_ids:
|
if mid in local_sent_ids:
|
||||||
# Наше собственное редактирование (например, анимация) — не логируем как чужое
|
|
||||||
cache_message(mid, target_entity.id, event.out, event.text or "")
|
cache_message(mid, target_entity.id, event.out, event.text or "")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -610,8 +852,8 @@ async def chat_loop():
|
|||||||
bottom_toolbar=bottom_toolbar,
|
bottom_toolbar=bottom_toolbar,
|
||||||
)
|
)
|
||||||
|
|
||||||
while True:
|
|
||||||
with patch_stdout():
|
with patch_stdout():
|
||||||
|
while True:
|
||||||
try:
|
try:
|
||||||
text = await session.prompt_async()
|
text = await session.prompt_async()
|
||||||
except (KeyboardInterrupt, EOFError):
|
except (KeyboardInterrupt, EOFError):
|
||||||
@@ -628,7 +870,6 @@ async def chat_loop():
|
|||||||
|
|
||||||
text = text.strip()
|
text = text.strip()
|
||||||
|
|
||||||
# === Результаты хоткеев ===
|
|
||||||
if text == "__MUTE__":
|
if text == "__MUTE__":
|
||||||
set_mute(not mute_enabled)
|
set_mute(not mute_enabled)
|
||||||
continue
|
continue
|
||||||
@@ -649,6 +890,10 @@ async def chat_loop():
|
|||||||
if text == "__LOG__":
|
if text == "__LOG__":
|
||||||
toggle_logging()
|
toggle_logging()
|
||||||
continue
|
continue
|
||||||
|
if text == "__TYPE__":
|
||||||
|
await type_dialog()
|
||||||
|
redraw()
|
||||||
|
continue
|
||||||
|
|
||||||
if not text:
|
if not text:
|
||||||
continue
|
continue
|
||||||
@@ -658,6 +903,21 @@ async def chat_loop():
|
|||||||
if cmd == ".help":
|
if cmd == ".help":
|
||||||
await show_help_and_return()
|
await show_help_and_return()
|
||||||
continue
|
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":
|
if cmd == ".mute":
|
||||||
set_mute(True)
|
set_mute(True)
|
||||||
continue
|
continue
|
||||||
@@ -680,12 +940,13 @@ async def chat_loop():
|
|||||||
if cmd == ".status":
|
if cmd == ".status":
|
||||||
last = last_media_path or '—'
|
last = last_media_path or '—'
|
||||||
log_info = log_file_path if logging_enabled else 'OFF'
|
log_info = log_file_path if logging_enabled else 'OFF'
|
||||||
emit(f"[STATUS] Target: {target_name} (ID: {target_entity.id}) | "
|
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}")
|
f"Mute: {'ON' if mute_enabled else 'OFF'} | Log: {log_info} | Last media: {last}")
|
||||||
continue
|
continue
|
||||||
if cmd == ".delete":
|
if cmd == ".delete":
|
||||||
pending_delete_at = time.monotonic()
|
pending_delete_at = time.monotonic()
|
||||||
emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat for both sides.")
|
emit("[SYSTEM] Send `.delete confirm` within 20s to wipe chat.")
|
||||||
continue
|
continue
|
||||||
if cmd == ".delete confirm":
|
if cmd == ".delete confirm":
|
||||||
if pending_delete_at and (time.monotonic() - pending_delete_at) < 20:
|
if pending_delete_at and (time.monotonic() - pending_delete_at) < 20:
|
||||||
@@ -698,7 +959,6 @@ async def chat_loop():
|
|||||||
asyncio.create_task(run_love_animation())
|
asyncio.create_task(run_love_animation())
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# .spam N text
|
|
||||||
if cmd.startswith(".spam "):
|
if cmd.startswith(".spam "):
|
||||||
rest = text[6:].strip()
|
rest = text[6:].strip()
|
||||||
parts = rest.split(maxsplit=1)
|
parts = rest.split(maxsplit=1)
|
||||||
@@ -716,17 +976,41 @@ async def chat_loop():
|
|||||||
asyncio.create_task(do_spam(count, parts[1], 0.3))
|
asyncio.create_task(do_spam(count, parts[1], 0.3))
|
||||||
continue
|
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":
|
if cmd == "/open":
|
||||||
await open_last_media()
|
await open_last_media()
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if text.lower().startswith("/send "):
|
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("'")
|
filepath = text[6:].strip().strip('"').strip("'")
|
||||||
if os.path.exists(filepath):
|
if os.path.exists(filepath):
|
||||||
emit(f"[SYSTEM] Sending: {filepath}")
|
emit(f"[SYSTEM] Sending: {filepath}")
|
||||||
try:
|
try:
|
||||||
msg = await client.send_file(target_entity, filepath)
|
msg = await client.send_file(target_entity, filepath)
|
||||||
local_sent_ids.append(msg.id)
|
local_sent_ids.append(msg.id)
|
||||||
|
silent_sent_ids.append(msg.id)
|
||||||
cache_message(msg.id, target_entity.id, True, f"[file: {filepath}]")
|
cache_message(msg.id, target_entity.id, True, f"[file: {filepath}]")
|
||||||
log_event("OUT", f"[file: {filepath}]")
|
log_event("OUT", f"[file: {filepath}]")
|
||||||
emit("[SYSTEM] File sent.")
|
emit("[SYSTEM] File sent.")
|
||||||
@@ -736,20 +1020,30 @@ async def chat_loop():
|
|||||||
emit(f"[ERROR] File does not exist: {filepath}")
|
emit(f"[ERROR] File does not exist: {filepath}")
|
||||||
continue
|
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:
|
try:
|
||||||
msg = await client.send_message(target_entity, text)
|
msg = await client.send_message(target_entity, text)
|
||||||
local_sent_ids.append(msg.id)
|
local_sent_ids.append(msg.id)
|
||||||
cache_message(msg.id, target_entity.id, True, text)
|
cache_message(msg.id, target_entity.id, True, text)
|
||||||
log_event("OUT", text)
|
log_event("OUT", text)
|
||||||
emit(f"[ME]: {text}")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
emit(f"[ERROR] Send failed: {e}")
|
emit(f"[ERROR] Send failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
# ==================== ОСНОВНОЙ ЗАПУСК ====================
|
# ==================== ОСНОВНОЙ ЗАПУСК ====================
|
||||||
async def main():
|
async def main():
|
||||||
global target_entity, target_name
|
global target_entity, target_name, _self_id
|
||||||
|
|
||||||
clear_screen()
|
clear_screen()
|
||||||
print("[SYSTEM] Connecting to Telegram...\n")
|
print("[SYSTEM] Connecting to Telegram...\n")
|
||||||
@@ -801,29 +1095,34 @@ async def main():
|
|||||||
print(f"[AUTH] QR login failed: {e2}")
|
print(f"[AUTH] QR login failed: {e2}")
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
|
|
||||||
|
# Узнаём свой ID (для детекта Избранного)
|
||||||
|
try:
|
||||||
|
me = await client.get_me()
|
||||||
|
if me:
|
||||||
|
_self_id = me.id
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
clear_screen()
|
clear_screen()
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
print("[AUTH] Authorized successfully.\n")
|
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:
|
if not target_input:
|
||||||
|
break
|
||||||
|
|
||||||
|
entity, err = await _resolve_entity(target_input)
|
||||||
|
if entity is None:
|
||||||
clear_screen()
|
clear_screen()
|
||||||
|
print(f"[ERROR] {err}")
|
||||||
|
print("Try again, or press Enter to skip (select later via .select).\n")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if target_input.lstrip('-').isdigit():
|
_apply_target(entity)
|
||||||
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
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
clear_screen()
|
clear_screen()
|
||||||
print(f"[ERROR] Could not resolve entity: {e}. Try again.")
|
print(f"[ERROR] {e}. Try again.")
|
||||||
|
|
||||||
redraw()
|
redraw()
|
||||||
await chat_loop()
|
await chat_loop()
|
||||||
|
|||||||
Reference in new issue
Block a user