envío automático de índices
This commit is contained in:
1
app/indices.txt
Normal file
1
app/indices.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
us-spx-500
|
@ -3,7 +3,7 @@ from contextlib import asynccontextmanager
|
|||||||
from database import Base, engine
|
from database import Base, engine
|
||||||
from routes import router
|
from routes import router
|
||||||
from apscheduler.schedulers.background import BackgroundScheduler
|
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
|
# Crear las tablas en MySQL si no existen
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
@ -12,6 +12,7 @@ Base.metadata.create_all(bind=engine)
|
|||||||
scheduler = BackgroundScheduler()
|
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=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_keywords_file, "cron", hour=18, minute=0) #Ejecutar a las 01:00
|
||||||
|
scheduler.add_job(search_from_indices_file, "interval", minutes=1)
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
|
@ -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"
|
"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):
|
def get_author_from_script(url):
|
||||||
"""
|
"""
|
||||||
Llama a autorsearcher.py con la URL de la noticia y devuelve el autor encontrado.
|
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}")
|
logging.info(f"Error al leer el archivo 'keywords.txt': {e}")
|
||||||
|
|
||||||
# Ejecutar la búsqueda desde el archivo
|
# 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}")
|
||||||
|
|
@ -18,6 +18,7 @@ repositories {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
implementation 'org.telegram:telegrambots-spring-boot-starter:6.9.7.0'
|
implementation 'org.telegram:telegrambots-spring-boot-starter:6.9.7.0'
|
||||||
implementation 'org.telegram:telegrambots-abilities:6.9.7.0'
|
implementation 'org.telegram:telegrambots-abilities:6.9.7.0'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-logging'
|
implementation 'org.springframework.boot:spring-boot-starter-logging'
|
||||||
|
@ -0,0 +1,41 @@
|
|||||||
|
package es.imunnic.inversionitasBot;
|
||||||
|
|
||||||
|
public class IndiceRequest {
|
||||||
|
private String indice;
|
||||||
|
private double valorActual;
|
||||||
|
private double cambio; // Nuevo campo agregado
|
||||||
|
private String porcentaje;
|
||||||
|
|
||||||
|
// Getters y Setters
|
||||||
|
public String getIndice() {
|
||||||
|
return indice;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIndice(String indice) {
|
||||||
|
this.indice = indice;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getValorActual() {
|
||||||
|
return valorActual;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValorActual(double valorActual) {
|
||||||
|
this.valorActual = valorActual;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getCambio() {
|
||||||
|
return cambio;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCambio(double cambio) {
|
||||||
|
this.cambio = cambio;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPorcentaje() {
|
||||||
|
return porcentaje;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPorcentaje(String porcentaje) {
|
||||||
|
this.porcentaje = porcentaje;
|
||||||
|
}
|
||||||
|
}
|
@ -25,6 +25,8 @@ public class TelegramBot extends TelegramLongPollingBot {
|
|||||||
//@Value("${telegram.bot.token}")
|
//@Value("${telegram.bot.token}")
|
||||||
private String BOT_TOKEN = "7626026035:AAHEMp_iIN3y8AwywL0R6OTQvNi7EcJZ0iY";
|
private String BOT_TOKEN = "7626026035:AAHEMp_iIN3y8AwywL0R6OTQvNi7EcJZ0iY";
|
||||||
|
|
||||||
|
protected String CHAT_ID = "-1002289752202";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getBotUsername() {
|
public String getBotUsername() {
|
||||||
return BOT_USERNAME;
|
return BOT_USERNAME;
|
||||||
@ -49,7 +51,7 @@ public class TelegramBot extends TelegramLongPollingBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendMessage(String chatId, String text) {
|
protected void sendMessage(String chatId, String text) {
|
||||||
// Primero dividimos el mensaje si es necesario
|
// Primero dividimos el mensaje si es necesario
|
||||||
List<String> partes = dividirMensaje(text);
|
List<String> partes = dividirMensaje(text);
|
||||||
|
|
||||||
@ -70,7 +72,7 @@ public class TelegramBot extends TelegramLongPollingBot {
|
|||||||
|
|
||||||
@Scheduled(cron = "0 0 13,20 * * ?", zone = "Europe/Paris")
|
@Scheduled(cron = "0 0 13,20 * * ?", zone = "Europe/Paris")
|
||||||
private void mensajeProgramado(){
|
private void mensajeProgramado(){
|
||||||
this.construirResumenNoticias("-1002289752202");
|
this.construirResumenNoticias(this.CHAT_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void construirResumenNoticias(String chatid) {
|
private void construirResumenNoticias(String chatid) {
|
||||||
|
@ -0,0 +1,27 @@
|
|||||||
|
package es.imunnic.inversionitasBot;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/telegram")
|
||||||
|
public class TelegramController {
|
||||||
|
|
||||||
|
private final TelegramBot telegramBot;
|
||||||
|
|
||||||
|
public TelegramController(TelegramBot telegramBot) {
|
||||||
|
this.telegramBot = telegramBot;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/send")
|
||||||
|
public void sendMessage(@RequestBody IndiceRequest request) {
|
||||||
|
String mensaje = String.format(
|
||||||
|
"*📊 Índice:* `%s`\n" +
|
||||||
|
"*💰 Valor Actual:* `%,.2f`\n" +
|
||||||
|
"*📉 Cambio:* `%,.2f`\n" +
|
||||||
|
"*📈 Cambio(%):* `%s`",
|
||||||
|
request.getIndice(), request.getValorActual(), request.getPorcentaje()
|
||||||
|
);
|
||||||
|
telegramBot.sendMessage(telegramBot.CHAT_ID, mensaje );
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Reference in New Issue
Block a user