Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from selenium import webdriver
- from selenium.webdriver.chrome.service import Service
- from selenium.webdriver.common.by import By
- from selenium.webdriver.common.action_chains import ActionChains
- from selenium.webdriver.support.ui import WebDriverWait
- from selenium.webdriver.support import expected_conditions as EC
- import datetime
- import time
- import requests
- # ------------------ CONFIGURACIÓN ------------------
- chrome_driver_path = r"C:\Downloads\chromedriver-win64\chromedriver.exe"
- chrome_binary_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
- user_data_dir = r"C:\Documents\ChromeProfile" # carpeta para guardar sesión
- user_to_track = "Prueba" # reemplaza con el contacto que quieres seguir
- # Telegram
- BOT_TOKEN = "8156257450:AAEsjajsajskai5acs8a96ca5c1sctdñclacl"
- CHAT_ID = "2085145625"
- # ------------------ FUNCIONES ------------------
- def send_telegram_message(text):
- url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
- data = {"chat_id": CHAT_ID, "text": text}
- try:
- response = requests.post(url, data=data)
- if response.status_code != 200:
- print(f"❌ Error enviando mensaje: {response.text}")
- except Exception as e:
- print(f"❌ Excepción enviando mensaje: {e}")
- def find_user_chat(user_name):
- """Busca y entra al chat del usuario"""
- try:
- search_box = driver.find_element(By.XPATH, '//*[@id="side"]/div[1]/div/div[2]/div/div/div[1]/p')
- search_box.click()
- actions = ActionChains(driver)
- actions.send_keys(user_name).perform()
- time.sleep(2) # espera que aparezcan resultados
- user_element = driver.find_element(By.XPATH, '//*[@id="pane-side"]/div[1]/div/div/div[2]/div/div')
- user_element.click()
- print(f"✅ Chat encontrado y abierto: {user_name}")
- return True
- except Exception as e:
- print(f"❌ No se pudo encontrar el usuario: {e}")
- return False
- def check_online_status():
- """Verifica si el usuario está en línea"""
- try:
- online_span = driver.find_element(By.XPATH, "//span[@title='en línea']") # Español
- return True
- except:
- return False
- # ------------------ INICIALIZAR CHROME ------------------
- options = webdriver.ChromeOptions()
- options.binary_location = chrome_binary_path
- options.add_argument(f"user-data-dir={user_data_dir}") # Guarda sesión
- options.add_experimental_option('excludeSwitches', ['enable-logging'])
- service = Service(executable_path=chrome_driver_path)
- driver = webdriver.Chrome(service=service, options=options)
- driver.get("https://web.whatsapp.com")
- # Espera hasta que cargue la barra lateral de chats
- WebDriverWait(driver, 60).until(
- EC.presence_of_element_located((By.XPATH, '//*[@id="side"]/div[1]/div/div[2]/div/div/div[1]/p'))
- )
- print("✅ WhatsApp Web cargado y listo")
- # ------------------ SEGUIMIENTO ------------------
- if find_user_chat(user_to_track):
- print(f"⏱ Comenzando seguimiento de {user_to_track}...")
- previous_state = "OFFLINE"
- first_online_time = None
- while True:
- try:
- is_online = check_online_status()
- now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- if is_online and previous_state == "OFFLINE":
- print(f"[{now}] ✅ {user_to_track} está ONLINE")
- send_telegram_message(f"✅ {user_to_track} está ONLINE ({now})")
- first_online_time = time.time()
- previous_state = "ONLINE"
- elif not is_online and previous_state == "ONLINE":
- total_online = time.time() - first_online_time
- print(f"[{now}] ❌ {user_to_track} se desconectó. Duración: {int(total_online)} segundos")
- send_telegram_message(f"❌ {user_to_track} se desconectó. Duración: {int(total_online)} segundos ({now})")
- previous_state = "OFFLINE"
- time.sleep(5) # espera 5 segundos antes de la siguiente comprobación
- except Exception as e:
- print(f"❌ Error durante seguimiento: {e}")
- break
Advertisement
Add Comment
Please, Sign In to add comment