From efa038faa6aed678e0b87ac4aad2495bb03a4cda Mon Sep 17 00:00:00 2001 From: Meveliq Date: Sat, 19 Sep 2026 20:29:30 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20monitor.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- monitor.py | 211 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 monitor.py diff --git a/monitor.py b/monitor.py new file mode 100644 index 0000000..96beb2c --- /dev/null +++ b/monitor.py @@ -0,0 +1,211 @@ +import vk_api +from datetime import datetime +import sys +import time +import threading + +# --- НАСТРОЙКИ --- +VK_TOKEN = 'vk1.a.KP3dkQIe5m4WLDB0NzxclTGs0v3JUjconaVkf6pAfQ2DHnzLyJFIVqh4CG60kWH0zoJ-khveJ7usosxpxr7XQHJl_XJgBWFgzngBYsZ9dtcNXl2b058SLofrtM2cI-lNzOb-PmMVOZTbBwYmu3x7spUJLKDaXq2LKf7gfBu8VvNCKlpl700-lcAX1InCA_Z9tSpTgQF2Zn-A4BW2NWnNmg' +USER_IDS = ['ilyadlav', 'lisak144'] # Диана удалена +LOG_FILE = 'online_log.txt' +CHECK_INTERVAL = 3 +# EXCLUDED_FROM_INTERSECTION больше не нужен +# ----------------- + +APP_DEVICES = { + 0: "🌐 Веб-версия (ПК)", + 1: "📱 Мобильное приложение (официальное)", + 2: "📱 Мобильная версия сайта", + 3: "📱 iPad приложение", + 4: "📱 Android приложение", + 5: "📱 Windows Phone приложение", + 6: "📱 iOS приложение", + 7: "💻 Windows 10/11 приложение", + 8: "💻 MacOS приложение", + 9: "📱 Samsung Galaxy приложение", + 10: "💬 VK Мессенджер", + 11: "📱 VK Mobile Lite", +} + +online_status = {} +session_start = {} +intersection_active = False +intersection_start = None +user_names = {} +user_ids = [] + +def get_app_name(app_id): + return APP_DEVICES.get(app_id, f"❓ Неизвестное приложение (ID: {app_id})") + +def get_user_full_name(uid): + if uid in user_names: + return user_names[uid] + return str(uid) + +def write_log(message): + timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + full_msg = f"[{timestamp}] {message}" + print(full_msg) + try: + with open(LOG_FILE, 'a', encoding='utf-8') as f: + f.write(full_msg + '\n') + except Exception as e: + print(f"Ошибка записи в лог: {e}") + +def get_user_ids(vk_session, usernames): + global user_names, user_ids + + try: + users = vk_session.method('users.get', { + 'user_ids': ','.join(usernames), + 'fields': 'id' + }) + + result_ids = [] + for user in users: + uid = user['id'] + full_name = f"{user.get('first_name', '')} {user.get('last_name', '')}".strip() + if not full_name: + full_name = str(uid) + user_names[uid] = full_name + result_ids.append(uid) + + return result_ids + except Exception as e: + write_log(f"Ошибка получения ID: {e}") + return [] + +def check_intersection(): + global intersection_active, intersection_start + + online_users = [uid for uid, status in online_status.items() if status] + online_count = len(online_users) + names = [get_user_full_name(uid) for uid in online_users] + + if online_count >= 2: + if not intersection_active: + intersection_active = True + intersection_start = datetime.now() + names_str = ", ".join(names) + write_log(f"🔔🔔🔔 [ПЕРЕСЕЧЕНИЕ] {online_count} пользователей одновременно в сети: {names_str}") + write_log(f"⏱️ Начало пересечения: {intersection_start.strftime('%H:%M:%S')}") + else: + if intersection_active: + intersection_active = False + duration = (datetime.now() - intersection_start).total_seconds() + duration_min = duration / 60 + write_log(f"🔔 [ПЕРЕСЕЧЕНИЕ ЗАВЕРШЕНО] Длилось {duration_min:.1f} минут") + intersection_start = None + +def check_online_periodically(vk_session, user_ids): + global online_status, session_start + + while True: + try: + time.sleep(CHECK_INTERVAL) + + users = vk_session.method('users.get', { + 'user_ids': ','.join(map(str, user_ids)), + 'fields': 'online, online_app' + }) + + status_changed = False + + for user in users: + uid = user['id'] + is_online = bool(user.get('online', 0)) + online_app = user.get('online_app', 0) + app_name = get_app_name(online_app) + + if uid not in online_status: + online_status[uid] = None + + if online_status[uid] != is_online: + status_changed = True + status_text = "ВОШЁЛ В СЕТЬ 🟢" if is_online else "ВЫШЕЛ ИЗ СЕТИ 🔴" + full_name = get_user_full_name(uid) + + if is_online: + session_start[uid] = datetime.now() + write_log(f"🔔 [Проверка] {full_name} {status_text} ({app_name})") + else: + if uid in session_start: + duration = (datetime.now() - session_start[uid]).total_seconds() + duration_min = duration / 60 + write_log(f"🔔 [Проверка] {full_name} {status_text} (был в сети {duration_min:.1f} мин, {app_name})") + del session_start[uid] + else: + write_log(f"🔔 [Проверка] {full_name} {status_text} ({app_name})") + + online_status[uid] = is_online + + if status_changed: + check_intersection() + + except Exception as e: + write_log(f"⚠️ Ошибка периодической проверки: {e}") + time.sleep(5) + +def main(): + global online_status, session_start, user_names, user_ids + + write_log("=== МОНИТОРИНГ ОНЛАЙНА ЗАПУЩЕН ===") + write_log(f"Отслеживаем пользователей: {USER_IDS}") + write_log(f"Периодическая проверка каждые {CHECK_INTERVAL} сек") + + try: + vk_session = vk_api.VkApi(token=VK_TOKEN) + write_log("✅ Авторизация по токену успешна!") + except Exception as e: + write_log(f"❌ Ошибка авторизации: {e}") + sys.exit(1) + + user_ids = get_user_ids(vk_session, USER_IDS) + if not user_ids: + write_log("❌ Не удалось получить ID пользователей") + sys.exit(1) + + names_list = [get_user_full_name(uid) for uid in user_ids] + write_log(f"🔍 Отслеживаем: {', '.join(names_list)}") + + online_status = {uid: None for uid in user_ids} + session_start = {} + + try: + users = vk_session.method('users.get', { + 'user_ids': ','.join(map(str, user_ids)), + 'fields': 'online, online_app' + }) + for user in users: + uid = user['id'] + is_online = bool(user.get('online', 0)) + online_app = user.get('online_app', 0) + app_name = get_app_name(online_app) + online_status[uid] = is_online + full_name = get_user_full_name(uid) + status_text = "В СЕТИ 🟢" if is_online else "НЕ В СЕТИ 🔴" + write_log(f"📊 {full_name} -> {status_text} ({app_name})") + if is_online: + session_start[uid] = datetime.now() + except Exception as e: + write_log(f"Ошибка проверки статуса: {e}") + + check_intersection() + + check_thread = threading.Thread( + target=check_online_periodically, + args=(vk_session, user_ids), + daemon=True + ) + check_thread.start() + write_log(f"✅ Запущена периодическая проверка (каждые {CHECK_INTERVAL} сек)") + + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + write_log("\n=== МОНИТОРИНГ ОСТАНОВЛЕН ПОЛЬЗОВАТЕЛЕМ ===") + sys.exit(0) + +if __name__ == '__main__': + main()