# -*- coding: utf8 -*-
import configparser
import json
import random
import time
from datetime import datetime, timedelta
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait, Select
from webdriver_manager.chrome import ChromeDriverManager
from telegram import Bot
from telegram.error import TelegramError
from selenium.common.exceptions import TimeoutException, NoSuchElementException
# Load configurations
config = configparser.ConfigParser()
config.read('config.ini') # Asegúrate de que este sea el archivo de configuración correcto que se necesita en todo el script
# Función para crear un web driver
def create_driver():
"""Crea una instancia del web driver basada en la configuración."""
options = webdriver.ChromeOptions()
if config['CHROMEDRIVER'].getboolean('LOCAL_USE'):
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
else:
driver = webdriver.Remote(command_executor=config['CHROMEDRIVER']['HUB_ADDRESS'], options=options)
return driver
# Función para enviar notificaciones vía Telegram
def send_notification(msg):
"""Envía un mensaje de notificación a través de Telegram."""
print(f"Enviando notificación: {msg}")
token = config['TELEGRAM']['TOKEN']
chat_id = config['TELEGRAM']['CHAT_ID']
bot = Bot(token=token)
try:
bot.send_message(chat_id=chat_id, text=msg)
print("Notificación enviada exitosamente vía Telegram")
except TelegramError as e:
print(f"Error al enviar notificación vía Telegram: {e}")
# Corrección: Se debe leer el archivo de configuración correcto, no el ejemplo.
config.read('config.ini')
USERNAME = config['USVISA']['USERNAME']
PASSWORD = config['USVISA']['PASSWORD']
SCHEDULE_ID = config['USVISA']['SCHEDULE_ID']
MY_SCHEDULE_DATE = config['USVISA']['MY_SCHEDULE_DATE']
COUNTRY_CODE = config['USVISA']['COUNTRY_CODE']
FACILITY_ID = config['USVISA']['FACILITY_ID']
def validate_date(input_date):
today = datetime.today()
limit_date = today + timedelta(days=120) # 120 días son aproximadamente 4 meses
return input_date <= limit_date
STEP_TIME = 0.5 # Tiempo entre pasos (interacciones con formularios): 0.5 segundos
RETRY_TIME = 60*10 # Tiempo de espera entre reintentos/chequeos de fechas disponibles: 10 minutos
EXCEPTION_TIME = 60*30 # Tiempo de espera cuando ocurre una excepción: 30 minutos
COOLDOWN_TIME = 60*60 # Tiempo de espera cuando se está temporalmente bloqueado (lista vacía): 60 minutos
DATE_URL = f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv/schedule/{SCHEDULE_ID}/appointment/days/{FACILITY_ID}.json?appointments[expedite]=false"
TIME_URL = f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv/schedule/{SCHEDULE_ID}/appointment/times/{FACILITY_ID}.json?date=%s&appointments[expedite]=false"
APPOINTMENT_URL = f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv/schedule/{SCHEDULE_ID}/appointment"
EXIT = False
def login_action(driver):
# Acción de inicio de sesión
print("Inicio de sesión...")
driver.get(f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv")
time.sleep(STEP_TIME)
try:
href = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div[1]/div[1]/div[2]/div[1]/ul/li[3]/a')
href.click()
time.sleep(STEP_TIME)
WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.NAME, "commit")))
do_login_action(driver)
except Exception as e:
print(f"Error durante el inicio de sesión: {e}")
def do_login_action(driver):
try:
print("\tIngresando email")
user = driver.find_element(By.ID, 'user_email')
user.send_keys(USERNAME)
time.sleep(random.randint(1, 3))
print("\tIngresando contraseña")
pw = driver.find_element(By.ID, 'user_password')
pw.send_keys(PASSWORD)
time.sleep(random.randint(1, 3))
print("\tAceptando privacidad")
box = driver.find_element(By.CLASS_NAME, 'icheckbox')
box.click()
time.sleep(random.randint(1, 3))
print("\tConfirmando")
btn = driver.find_element(By.NAME, 'commit')
btn.click()
time.sleep(random.randint(1, 3))
WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, '//alguna_xpath_que_indique_login_exitoso')))
print("\t¡Inicio de sesión exitoso!")
except Exception as e:
print(f"Error durante la acción de inicio de sesión: {e}")
# Corrección: Se eliminaron funciones duplicadas y se corrigieron errores menores.
def do_login_action():
print("\tinput email")
user = driver.find_element(By.ID, 'user_email')
user.send_keys(USERNAME)
time.sleep(random.randint(1, 3))
print("\tinput pwd")
pw = driver.find_element(By.ID, 'user_password')
pw.send_keys(PASSWORD)
time.sleep(random.randint(1, 3))
print("\tclick privacy")
box = driver.find_element(By.CLASS_NAME, 'icheckbox')
box .click()
time.sleep(random.randint(1, 3))
print("\tcommit")
btn = driver.find_element(By.NAME, 'commit')
btn.click()
time.sleep(random.randint(1, 3))
Wait(driver, 60).until(
EC.presence_of_element_located((By.XPATH, REGEX_CONTINUE)))
print("\tlogin successful!")
def login(driver):
driver.get(config['SITE']['BASE_URL'])
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "user_email"))).send_keys(config['USER']['USERNAME'])
driver.find_element(By.ID, 'user_password').send_keys(config['USER']['PASSWORD'])
driver.find_element(By.NAME, 'commit').click()
def schedule_appointment(driver, consulate_id, asc_id, consulate_date, asc_date, consulate_time, asc_time):
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.remote.webdriver import WebDriver
consulate_date_obj = datetime.strptime(consulate_date, "%Y-%m-%d")
asc_date_obj = datetime.strptime(asc_date, "%Y-%m-%d")
if not validate_date(consulate_date_obj) or not validate_date(asc_date_obj):
print("Una o ambas fechas exceden el límite de 4 meses")
return
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "appointments_consulate_appointment_facility_id")))
Select(driver.find_element_by_id("appointments_consulate_appointment_facility_id")).select_by_value(consulate_id)
driver.find_element_by_id("appointments_consulate_appointment_date").send_keys(consulate_date)
Select(driver.find_element_by_id("appointments_consulate_appointment_time")).select_by_visible_text(consulate_time)
Select(driver.find_element_by_id("appointments_asc_appointment_facility_id")).select_by_value(asc_id)
driver.find_element_by_id("appointments_asc_appointment_date").send_keys(asc_date)
Select(driver.find_element_by_id("appointments_asc_appointment_time")).select_by_visible_text(asc_time)
def get_date(driver: WebDriver):
def get_date():
# driver.get(DATE_URL)
driver.get(APPOINTMENT_URL)
session_cookie = driver.get_cookie("_yatri_session")
session = session_cookie["value"] if session_cookie is not None else ""
NEW_GET = driver.execute_script(
"var req = new XMLHttpRequest();req.open('GET', '"
+ str(DATE_URL)
+ "', false);req.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');req.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); req.setRequestHeader('Cookie', '_yatri_session="
+ session
+ "'); req.send(null);return req.responseText;"
)
return json.loads(NEW_GET)
def login(driver):
driver.get("https://ais.usvisa-info.com/" + config['USVISA']['COUNTRY_CODE'] + "/niv/users/sign_in")
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "user_email"))).send_keys(config['USVISA']['USERNAME'])
driver.find_element(By.ID, 'user_password').send_keys(config['USVISA']['PASSWORD'])
driver.find_element(By.NAME, 'commit').click()
def schedule_appointment(driver, consulate_id, asc_id, consulate_date, asc_date, consulate_time, asc_time):
if not (validate_date(datetime.strptime(consulate_date, "%Y-%m-%d")) and validate_date(datetime.strptime(asc_date, "%Y-%m-%d"))):
send_notification("Una o ambas fechas exceden el límite de 4 meses.")
return
driver.get("https://ais.usvisa-info.com/" + config['USVISA']['COUNTRY_CODE'] + "/niv/schedule/" + config['USVISA']['SCHEDULE_ID'] + "/appointment")
def get_time(date):
time_url = TIME_URL % date
session_cookie = driver.get_cookie("_yatri_session")
session = session_cookie["value"] if session_cookie is not None else ""
NEW_TIME = driver.execute_script(
"var req = new XMLHttpRequest();req.open('GET', '"
+ str(time_url)
+ "', false);req.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');req.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); req.setRequestHeader('Cookie', '_yatri_session="
+ session
+ "'); req.send(null);return req.responseText;"
)
data = json.loads(NEW_TIME)
time = data.get("available_times")[-1]
print(f"Got time successfully! {date} {time}")
return time
def schedule_appointment(driver, consulate_id, asc_id, consulate_date, asc_date):
# Navega a la página del formulario si no está ya ahí
driver.get("URL_DE_LA_PAGINA_DE_CITAS")
# Selección del consulado
Select(driver.find_element(By.ID, "appointments_consulate_appointment_facility_id")).select_by_value(consulate_id)
# Esperar que el calendario esté disponible y seleccionar fecha para el consulado
WebDriverWait(driver, timeout=10).until(
EC.element_to_be_clickable((By.ID, "appointments_consulate_appointment_date"))
)
consulate_date_input = driver.find_element(By.ID, "appointments_consulate_appointment_date")
consulate_date_input.clear()
consulate_date_input.send_keys(consulate_date)
consulate_date_input.clear()
consulate_date_input.send_keys(consulate_date)
# Esperar y seleccionar la hora para el consulado
WebDriverWait(driver, timeout=10).until(
EC.element_to_be_clickable((By.ID, "appointments_consulate_appointment_time"))
)
Select(driver.find_element(By.ID, "appointments_consulate_appointment_time")).select_by_index(1) # ejemplo: seleccionar la primera hora disponible
# Repetir el proceso para el CAS
Select(driver.find_element(By.ID, "appointments_asc_appointment_facility_id")).select_by_value(asc_id)
asc_date_input = driver.find_element(By.ID, "appointments_asc_appointment_date")
asc_date_input.clear()
asc_date_input.send_keys(asc_date)
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "appointments_asc_appointment_time"))
)
Select(driver.find_element(By.ID, "appointments_asc_appointment_time")).select_by_index(1) # ejemplo: seleccionar la primera hora disponible
# Enviar el formulario
driver.find_element(By.ID, "appointments_submit").click()En esta categoría se alistan las diversas máquinas y/o humanoides creados para usar la inteligencia humana dentro del Universo Cinematográfico de Marvel.
Todos los artículos (46)