-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmsg_debug.py
More file actions
189 lines (162 loc) · 8.17 KB
/
msg_debug.py
File metadata and controls
189 lines (162 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# -*- coding: utf-8 -*-
"""
msg_debug.py — Менеджер дебага входящих сообщений на юзерботах.
Подписывается на NewMessage(incoming=True, is_private=True) для каждого
аккаунта пользователя. При получении сообщения шлёт уведомление владельцу
через бот-менеджер с кнопкой «Ответить вместо бота».
"""
import asyncio
import datetime
import logging
import time
from typing import Dict, Optional, Set, Tuple
from telethon import events
import client_pool as _client_pool
from config import API_ID, API_HASH, SESSIONS_DIR
from global_proxy import proxy_to_telethon, get_proxy_for_account
log = logging.getLogger("msg_debug")
class MsgDebugManager:
def __init__(self):
# phone -> owner_id
self._owners: Dict[str, int] = {}
# phone -> handler fn (для удаления при stop)
self._handlers: Dict[str, object] = {}
# активные телефоны
self._active: Set[str] = set()
# (phone, chat_id) -> timestamp последнего входящего
self._last_msg_ts: Dict[Tuple[str, int], float] = {}
# (phone, chat_id) -> (owner_id, bot_msg_id) последнего дебаг-уведомления
self._debug_msgs: Dict[Tuple[str, int], Tuple[int, int]] = {}
# aiogram Bot — задаётся через set_bot()
self._bot = None
self._lock = asyncio.Lock()
def set_bot(self, bot) -> None:
self._bot = bot
def is_running(self, phone: str) -> bool:
return phone in self._active
def get_last_msg_ts(self, phone: str, chat_id: int) -> float:
"""Время последнего входящего в этот чат (0.0 если не было)."""
return self._last_msg_ts.get((phone, chat_id), 0.0)
def pop_debug_msg(self, phone: str, chat_id: int) -> Optional[Tuple[int, int]]:
"""Вернуть и удалить сохранённый (owner_id, msg_id) дебаг-уведомления."""
return self._debug_msgs.pop((phone, chat_id), None)
async def mark_replied(self, phone: str, chat_id: int) -> None:
"""Обновить кнопку последнего дебаг-уведомления на «✅ Бот уже ответил»."""
info = self._debug_msgs.pop((phone, chat_id), None)
if info is None or self._bot is None:
return
owner_id, msg_id = info
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
markup = InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text="✅ Бот уже ответил", callback_data="noop")
]])
try:
await self._bot.edit_message_reply_markup(
chat_id=owner_id, message_id=msg_id, reply_markup=markup
)
except Exception:
pass
async def start(self, phone: str, owner_id: int) -> bool:
"""Запустить дебаг-слушатель для аккаунта phone."""
# Быстрая проверка под локом — без блокирующих вызовов
async with self._lock:
if phone in self._active:
self._owners[phone] = owner_id
return True
# Резервируем место: другой вызов start() для этого phone увидит active
self._active.add(phone)
self._owners[phone] = owner_id
# Тяжёлое подключение — вне лока, разные аккаунты идут параллельно
proxy = await get_proxy_for_account(phone, owner_id)
tproxy = proxy_to_telethon(proxy or "")
client = await _client_pool.get_or_connect(
phone, API_ID, API_HASH, SESSIONS_DIR,
proxy=tproxy, owner_id=owner_id, proxy_str=proxy or "",
)
if client is None:
log.warning("msg_debug.start: %s connect failed", phone)
async with self._lock:
self._active.discard(phone)
self._owners.pop(phone, None)
return False
async def _on_in(event, _phone=phone, _owner=owner_id):
if not event.is_private:
return
if _phone not in self._active:
return
if getattr(event.sender, 'bot', False):
return
try:
msg = event.message
chat_id = msg.chat_id
# Обновляем timestamp всегда — нужно для 90-сек проверки
self._last_msg_ts[(_phone, chat_id)] = time.time()
# Уведомление только если автоответ активен для этого аккаунта
from bot_globals import ar_manager
if not ar_manager.is_running(_phone):
return
# event.sender уже есть в ивенте — без дополнительного RPC
await self._send_debug(_phone, _owner, msg, event.sender)
except Exception as e:
log.warning("msg_debug handler %s: %s", _phone, e)
client.add_event_handler(_on_in, events.NewMessage(incoming=True))
async with self._lock:
self._handlers[phone] = _on_in
log.info("msg_debug started: %s (owner=%s)", phone, owner_id)
return True
async def stop(self, phone: str) -> None:
"""Остановить слушатель для аккаунта phone."""
async with self._lock:
self._active.discard(phone)
self._owners.pop(phone, None)
handler = self._handlers.pop(phone, None)
client = _client_pool.get(phone)
if client and handler:
try:
client.remove_event_handler(handler, events.NewMessage(incoming=True))
except Exception:
pass
log.info("msg_debug stopped: %s", phone)
async def stop_all(self) -> None:
for phone in list(self._active):
await self.stop(phone)
async def stop_for_owner(self, owner_id: int) -> None:
"""Остановить всех слушателей конкретного владельца."""
phones = [p for p, o in self._owners.items() if o == owner_id]
for phone in phones:
await self.stop(phone)
async def _send_debug(self, phone: str, owner_id: int, msg, sender=None) -> None:
if self._bot is None:
return
ts = datetime.datetime.now().strftime("%H:%M:%S")
if sender:
first = getattr(sender, "first_name", "") or ""
last = getattr(sender, "last_name", "") or ""
uname = getattr(sender, "username", None)
sender_name = (first + " " + last).strip() or getattr(sender, "title", None) or "?"
sender_id = sender.id
name_str = f"<b>{sender_name}</b>"
if uname:
name_str += f" @{uname}"
else:
sender_id = msg.chat_id
name_str = "<b>?</b>"
text = msg.text or msg.message or ""
preview = (text[:120] + "…") if len(text) > 120 else text
preview = preview or "—"
cb = f"mdbg_reply:{phone}:{msg.chat_id}"
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
markup = InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text="💬 Ответить вместо бота", callback_data=cb)
]])
debug_text = (
f"🔍 <b>Debug</b> | <code>{phone}</code>\n"
f"⏰ {ts} · {name_str} (id: <code>{sender_id}</code>)\n"
f"💬 {preview}"
)
try:
sent = await self._bot.send_message(owner_id, debug_text, reply_markup=markup)
# Сохраняем message_id для последующего обновления кнопки
self._debug_msgs[(phone, msg.chat_id)] = (owner_id, sent.message_id)
except Exception as e:
log.warning("msg_debug _send_debug %s: %s", phone, e)