From 9ffcf838898ad0025aaede1eb5d1cd200eb1b225 Mon Sep 17 00:00:00 2001 From: DavidDevGt Date: Wed, 6 Nov 2024 09:00:36 -0600 Subject: [PATCH] Implement cron job scheduling for daily reminders and add send reminder functionality --- index.js | 12 ++++----- plugins/translator.js | 3 --- services/cron_service.js | 56 ++++++++++++++++++++++++++++++++++++++++ tasks/send_reminder.js | 28 ++++++++++++++++++++ 4 files changed, 89 insertions(+), 10 deletions(-) create mode 100644 services/cron_service.js create mode 100644 tasks/send_reminder.js diff --git a/index.js b/index.js index b2781a7..043a221 100644 --- a/index.js +++ b/index.js @@ -1,15 +1,13 @@ -// index.js - const { Client, LocalAuth } = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const dotenv = require('dotenv'); const weatherUtils = require('./utils/weather_utils'); const weatherService = require('./services/weather_service'); const logger = require('./utils/logger'); -const { handleRecipeCommand } = require('./commands/recipes_command'); // Importar el comando de recetas -const { handleWeatherCommand } = require('./commands/weather_command'); // Importar el comando de clima +const { handleRecipeCommand } = require('./commands/recipes_command'); +const { handleWeatherCommand } = require('./commands/weather_command'); +const { initializeCronJobs } = require('./services/cron_service'); -// Configuración inicial dotenv.config(); // Constantes @@ -22,7 +20,6 @@ if (!AUTHORIZED_NUMBER) { process.exit(1); } -// Configuración del cliente const clientConfig = { authStrategy: new LocalAuth(), puppeteer: { @@ -60,6 +57,8 @@ class WhatsAppBot { this.myNumber = this.myId.split('@')[0]; logger.info(`🔑 Tu ID de WhatsApp es: ${this.myId}`); logger.info(`📱 Tu número de teléfono es: ${this.myNumber}`); + const initCron = await initializeCronJobs(this.client); + if (initCron) logger.info('⏰ Tareas programadas inicializadas correctamente'); const chat = await this.client.getChatById(this.myId); logger.info(`💭 Chat propio encontrado: ${JSON.stringify(chat, null, 2)}`); } catch (error) { @@ -121,6 +120,5 @@ class WhatsAppBot { } } -// Iniciar el bot const bot = new WhatsAppBot(); bot.start(); diff --git a/plugins/translator.js b/plugins/translator.js index ed8e242..30c575c 100644 --- a/plugins/translator.js +++ b/plugins/translator.js @@ -28,9 +28,6 @@ const translateText = async (text, targetLang = 'es') => { } ); - console.log('Respuesta de la API de traducción:', response.data); - console.log('Texto original:', text); - // Extrae el texto traducido de la respuesta const translatedText = response.data.candidates[0].content.parts[0].text; return translatedText; diff --git a/services/cron_service.js b/services/cron_service.js new file mode 100644 index 0000000..b74b413 --- /dev/null +++ b/services/cron_service.js @@ -0,0 +1,56 @@ +const cron = require('node-cron'); +const { sendReminder } = require('../tasks/send_reminder'); +const config = require('../config.json'); + +/** + * Convierte el intervalo en horas o minutos a minutos. + * @param {String} intervalo - Intervalo en el formato "2 horas" o "45 minutos". + * @returns {Number} - Intervalo en minutos. + */ +const getIntervalInMinutes = (intervalo) => { + const [amount, unit] = intervalo.split(' '); + return unit.includes('hora') ? parseInt(amount) * 60 : parseInt(amount); +}; + +/** + * Programa las tareas de recordatorio basadas en el horario y el intervalo. + * @param {Object} client - Instancia del cliente de WhatsApp. + */ +const initializeCronJobs = (client) => { + const dailyRoutines = config.rutinas.diarias; + + dailyRoutines.forEach((routine) => { + const { actividad, detalles } = routine; + const { intervalo, horario, que, hora } = detalles; + + if (intervalo && horario) { + const intervalInMinutes = getIntervalInMinutes(intervalo); + const [startHour, startMinute] = horario.inicio.split(':').map(Number); + const [endHour, endMinute] = horario.fin.split(':').map(Number); + + cron.schedule(`*/${intervalInMinutes} * * * *`, () => { + const now = new Date(); + const isWithinTimeFrame = + now.getHours() >= startHour && + now.getHours() <= endHour && + (now.getHours() < endHour || now.getMinutes() <= endMinute); + + if (isWithinTimeFrame) { + sendReminder(client, actividad, que); + } + }); + } + else if (hora) { + const [hour, minute] = hora.split(':'); + cron.schedule(`${minute} ${hour} * * *`, () => { + sendReminder(client, actividad, que); + }); + } + }); + + console.log('⏰ Recordatorios programados según configuración en config.json'); +}; + +module.exports = { + initializeCronJobs +}; \ No newline at end of file diff --git a/tasks/send_reminder.js b/tasks/send_reminder.js new file mode 100644 index 0000000..0e0da92 --- /dev/null +++ b/tasks/send_reminder.js @@ -0,0 +1,28 @@ +const { MessageMedia } = require('whatsapp-web.js'); +const config = require('../config.json'); +const dotenv = require('dotenv'); + +dotenv.config(); + +const AUTHORIZED_NUMBER = process.env.AUTHORIZED_NUMBER; + +/** + * Enviar un recordatorio de actividad diaria al número autorizado. + * @param {Object} client - Instancia del cliente de WhatsApp. + * @param {String} actividad - Nombre de la actividad. + * @param {String} mensaje - Mensaje personalizado para la actividad. + */ +const sendReminder = async (client, actividad, mensaje) => { + const formattedMessage = `🔔 Recordatorio: ${actividad}\n📝 ${mensaje}`; + + try { + await client.sendMessage(AUTHORIZED_NUMBER, formattedMessage); + console.log(`📤 Recordatorio de ${actividad} enviado a ${AUTHORIZED_NUMBER}`); + } catch (error) { + console.error(`❌ Error al enviar recordatorio de ${actividad}:`, error); + } +}; + +module.exports = { + sendReminder +}; \ No newline at end of file