envío automático de índices

This commit is contained in:
2025-03-16 18:20:02 +01:00
parent 3dd835f9fa
commit 1cf4ac6138
7 changed files with 134 additions and 3 deletions

1
app/indices.txt Normal file
View File

@ -0,0 +1 @@
us-spx-500

View File

@ -3,7 +3,7 @@ from contextlib import asynccontextmanager
from database import Base, engine
from routes import router
from apscheduler.schedulers.background import BackgroundScheduler
from webscrapper import search_from_keywords_file
from webscrapper import search_from_keywords_file, search_from_indices_file
# Crear las tablas en MySQL si no existen
Base.metadata.create_all(bind=engine)
@ -12,6 +12,7 @@ Base.metadata.create_all(bind=engine)
scheduler = BackgroundScheduler()
scheduler.add_job(search_from_keywords_file, "cron", hour=11, minute=0) #Ejecutar a las 01:00
scheduler.add_job(search_from_keywords_file, "cron", hour=18, minute=0) #Ejecutar a las 01:00
scheduler.add_job(search_from_indices_file, "interval", minutes=1)
@asynccontextmanager

View File

@ -23,6 +23,8 @@ HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
TELEGRAM_BOT_URL = "http://telegrambot_app:8080/telegram/send"
def get_author_from_script(url):
"""
Llama a autorsearcher.py con la URL de la noticia y devuelve el autor encontrado.
@ -184,3 +186,59 @@ def search_from_keywords_file():
logging.info(f"Error al leer el archivo 'keywords.txt': {e}")
# Ejecutar la búsqueda desde el archivo
def search_from_indices_file():
all_indices=[]
try:
with open("app/indices.txt", "r", encondig="utf-8") as file:
indices = file.readlines()
indices = [indice.strip() for indice in indices]
for indice in indices:
logging.info(f"\nAnalizando indice: {indice}")
search_indice(indice)
time.sleep(2)
except FileNotFoundError:
logging.info("No se encontró el archivo 'indices.txt'.")
except Exception as e:
logging.info(f"Error al leer el archivo 'indices.txt': {e}")
def search_indice(indice):
base_url = f"https://www.investing.com/indices/{indice}"
try:
response = requests.get(base_url, headers=HEADERS)
if response.status_code != 200:
logging.info(f"Error al acceder a la página para la consulta '{indice}': {response.status_code}")
return
soup = BeautifulSoup(response.content, 'html.parser')
# Buscar los valores dentro del HTML
price = soup.find("div", {"data-test": "instrument-price-last"})
price_change = soup.find("span", {"data-test": "instrument-price-change"})
price_change_percent = soup.find("span", {"data-test": "instrument-price-change-percent"})
if price and price_change and price_change_percent:
data = {
"indice": indice,
"valorActual": float(price.text.replace(",", "").strip()), # Convertir a número
"cambio": float(price_change.text.replace(",", "").strip()), # Convertir a número
"porcentaje": price_change_percent.text.strip()
}
# Enviar los datos al bot de Telegram
response_telegram = requests.post(TELEGRAM_BOT_URL, json=data)
if response_telegram.status_code == 200:
logging.info(f"Mensaje enviado a Telegram correctamente para '{indice}'")
else:
logging.error(f"Error enviando mensaje a Telegram: {response_telegram.status_code} - {response_telegram.text}")
else:
logging.info(f"No se encontraron datos para el índice '{indice}'.")
except requests.RequestException as e:
logging.error(f"Error en la solicitud: {e}")