cambios para adaptar
This commit is contained in:
@ -8,7 +8,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
load_dotenv()
|
||||
|
||||
# Configuración de MySQL desde variables de entorno
|
||||
MYSQL_HOST = os.getenv("MYSQL_HOST", "mysql")
|
||||
MYSQL_HOST = os.getenv("MYSQL_HOST", "localhost")
|
||||
MYSQL_USER = os.getenv("MYSQL_USER", "investionitas")
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "inversionitas")
|
||||
MYSQL_DATABASE = os.getenv("MYSQL_DATABASE", "news")
|
||||
|
@ -1,7 +1,8 @@
|
||||
Defensa
|
||||
Fuerzas Armadas
|
||||
CNI
|
||||
Guardia Civil
|
||||
Inteligencia
|
||||
Policia
|
||||
Ejercito
|
||||
Economía nacional
|
||||
Economía internacional
|
||||
Finanzas
|
||||
Bitcoin
|
||||
Inversiones
|
||||
Wall Street
|
||||
IBEX
|
||||
SP500
|
22
app/main.py
22
app/main.py
@ -1,29 +1,27 @@
|
||||
from fastapi import FastAPI
|
||||
from contextlib import asynccontextmanager
|
||||
from database import Base, engine
|
||||
from routes import router
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from contextlib import asynccontextmanager
|
||||
from telegrambot import enviar_mensaje_sync
|
||||
#from webscrapper import ejecutar_scrapper
|
||||
from telegrambot import enviar_resumen_diario
|
||||
from webscrapper import search_from_keywords_file
|
||||
|
||||
# Crear las tablas en MySQL si no existen
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Inicializar FastAPI
|
||||
app = FastAPI()
|
||||
# Configurar el scheduler
|
||||
scheduler = BackgroundScheduler()
|
||||
|
||||
def tarea_programada():
|
||||
enviar_mensaje_sync("¡Buenos días! Aquí tienes tu mensaje diario.")
|
||||
|
||||
scheduler.add_job(tarea_programada, "cron", hour=8, minute=0)
|
||||
scheduler.add_job(enviar_resumen_diario, "cron", hour=8, minute=0) # Ejecutar a las 08:00
|
||||
scheduler.add_job(search_from_keywords_file, "cron", hour=1, minute=0) #Ejecutar a las 01:00
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
scheduler.start() # Iniciar el scheduler cuando la app arranca
|
||||
scheduler.start()
|
||||
yield
|
||||
scheduler.shutdown() # Apagar el scheduler al cerrar la app
|
||||
scheduler.shutdown()
|
||||
|
||||
# Inicializar FastAPI con lifespan
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
# Incluir rutas
|
||||
app.include_router(router)
|
||||
|
@ -1,15 +0,0 @@
|
||||
fastapi
|
||||
uvicorn
|
||||
requests
|
||||
beautifulsoup4
|
||||
googlenewsdecoder
|
||||
pytz
|
||||
logging
|
||||
sqlalchemy
|
||||
pydantic
|
||||
python-dotenv
|
||||
mysql-connector-python
|
||||
pymysql
|
||||
cryptography
|
||||
lxml
|
||||
apscheduler
|
@ -1,15 +1,78 @@
|
||||
from telegram import Bot
|
||||
import asyncio
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from models import NewsItem
|
||||
from datetime import datetime, timedelta
|
||||
import asyncio
|
||||
|
||||
# Configura tu bot con el token de BotFather
|
||||
TOKEN = "7626026035:AAHEMp_iIN3y8AwywL0R6OTQvNi7EcJZ0iY"
|
||||
CHAT_ID = "-123456789" # Reemplaza con el ID del grupo
|
||||
CHAT_ID = "-4731993289" # Reemplaza con el ID del grupo
|
||||
|
||||
bot = Bot(token=TOKEN)
|
||||
|
||||
async def enviar_mensaje(mensaje: str):
|
||||
await bot.send_message(chat_id=CHAT_ID, text=mensaje)
|
||||
|
||||
# Para ejecutar la función de forma síncrona cuando sea necesario
|
||||
def enviar_mensaje_sync(mensaje: str):
|
||||
def obtener_titulares_por_keyword():
|
||||
"""
|
||||
Consulta la base de datos para obtener titulares agrupados por keywords del día anterior.
|
||||
"""
|
||||
db: Session = next(get_db()) # Obtener la sesión de la DB
|
||||
try:
|
||||
# Calcular el rango de fechas (ayer)
|
||||
hoy = datetime.now()
|
||||
ayer = hoy - timedelta(days=1)
|
||||
|
||||
# Obtener todas las keywords disponibles
|
||||
keywords = (
|
||||
db.query(NewsItem.keyword)
|
||||
.filter(NewsItem.fecha >= ayer.date(), NewsItem.fecha < hoy.date())
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
keywords = [k[0] for k in keywords if k[0] is not None] # Extraer valores y filtrar None
|
||||
|
||||
# Obtener titulares por keyword
|
||||
resumen = {}
|
||||
for keyword in keywords:
|
||||
resultados = (
|
||||
db.query(NewsItem.titulo)
|
||||
.filter(
|
||||
NewsItem.keyword == keyword,
|
||||
NewsItem.fecha >= ayer.date(),
|
||||
NewsItem.fecha < hoy.date()
|
||||
)
|
||||
.all()
|
||||
)
|
||||
resumen[keyword] = [r[0] for r in resultados] # Convertir en lista de strings
|
||||
|
||||
return resumen
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al obtener titulares: {e}")
|
||||
return {}
|
||||
|
||||
finally:
|
||||
db.close() # Cerrar la conexión
|
||||
|
||||
def enviar_resumen_diario():
|
||||
"""
|
||||
Construye el mensaje con los titulares por keyword y lo envía por Telegram.
|
||||
"""
|
||||
resumen = obtener_titulares_por_keyword()
|
||||
|
||||
if not resumen:
|
||||
mensaje = "¡Hola! No se encontraron noticias relevantes ayer. ¡Mañana volvemos con más información!"
|
||||
else:
|
||||
mensaje = "¡Hola! Estos son los titulares más relevantes de las noticias de ayer:\n\n"
|
||||
for keyword, titulares in resumen.items():
|
||||
mensaje += f"🔹 *{keyword}*:\n"
|
||||
for titulo in titulares:
|
||||
mensaje += f" - {titulo}\n"
|
||||
mensaje += "\n"
|
||||
mensaje += "📢 ¡Mañana volveremos con más información!"
|
||||
|
||||
# Enviar mensaje de forma asíncrona
|
||||
asyncio.run(enviar_mensaje(mensaje))
|
||||
|
@ -110,7 +110,17 @@ def search_news(query):
|
||||
# Obtener el autor usando autorsearcher.py
|
||||
author = get_author_from_script(final_url)
|
||||
content = get_article_content(final_url)
|
||||
|
||||
|
||||
news_item = {
|
||||
"titulo": title,
|
||||
"contenido": content,
|
||||
"autor": author,
|
||||
"fuente": source_info,
|
||||
"fecha": date_parsed.isoformat(),
|
||||
"link": final_url, # Guardamos la URL final en lugar de la de Google News,
|
||||
"keyword": query
|
||||
}
|
||||
insertar_datos(news_item)
|
||||
|
||||
# Verificar si el artículo es válido usando iacorrector
|
||||
# if is_economy_related(content): # Solo si el artículo es válido
|
||||
|
Reference in New Issue
Block a user