Implement cron job scheduling for daily reminders and add send reminder functionality
This commit is contained in:
parent
71dbf28481
commit
9ffcf83889
12
index.js
12
index.js
@ -1,15 +1,13 @@
|
|||||||
// index.js
|
|
||||||
|
|
||||||
const { Client, LocalAuth } = require('whatsapp-web.js');
|
const { Client, LocalAuth } = require('whatsapp-web.js');
|
||||||
const qrcode = require('qrcode-terminal');
|
const qrcode = require('qrcode-terminal');
|
||||||
const dotenv = require('dotenv');
|
const dotenv = require('dotenv');
|
||||||
const weatherUtils = require('./utils/weather_utils');
|
const weatherUtils = require('./utils/weather_utils');
|
||||||
const weatherService = require('./services/weather_service');
|
const weatherService = require('./services/weather_service');
|
||||||
const logger = require('./utils/logger');
|
const logger = require('./utils/logger');
|
||||||
const { handleRecipeCommand } = require('./commands/recipes_command'); // Importar el comando de recetas
|
const { handleRecipeCommand } = require('./commands/recipes_command');
|
||||||
const { handleWeatherCommand } = require('./commands/weather_command'); // Importar el comando de clima
|
const { handleWeatherCommand } = require('./commands/weather_command');
|
||||||
|
const { initializeCronJobs } = require('./services/cron_service');
|
||||||
|
|
||||||
// Configuración inicial
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
// Constantes
|
// Constantes
|
||||||
@ -22,7 +20,6 @@ if (!AUTHORIZED_NUMBER) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Configuración del cliente
|
|
||||||
const clientConfig = {
|
const clientConfig = {
|
||||||
authStrategy: new LocalAuth(),
|
authStrategy: new LocalAuth(),
|
||||||
puppeteer: {
|
puppeteer: {
|
||||||
@ -60,6 +57,8 @@ class WhatsAppBot {
|
|||||||
this.myNumber = this.myId.split('@')[0];
|
this.myNumber = this.myId.split('@')[0];
|
||||||
logger.info(`🔑 Tu ID de WhatsApp es: ${this.myId}`);
|
logger.info(`🔑 Tu ID de WhatsApp es: ${this.myId}`);
|
||||||
logger.info(`📱 Tu número de teléfono es: ${this.myNumber}`);
|
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);
|
const chat = await this.client.getChatById(this.myId);
|
||||||
logger.info(`💭 Chat propio encontrado: ${JSON.stringify(chat, null, 2)}`);
|
logger.info(`💭 Chat propio encontrado: ${JSON.stringify(chat, null, 2)}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -121,6 +120,5 @@ class WhatsAppBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iniciar el bot
|
|
||||||
const bot = new WhatsAppBot();
|
const bot = new WhatsAppBot();
|
||||||
bot.start();
|
bot.start();
|
||||||
|
@ -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
|
// Extrae el texto traducido de la respuesta
|
||||||
const translatedText = response.data.candidates[0].content.parts[0].text;
|
const translatedText = response.data.candidates[0].content.parts[0].text;
|
||||||
return translatedText;
|
return translatedText;
|
||||||
|
56
services/cron_service.js
Normal file
56
services/cron_service.js
Normal file
@ -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
|
||||||
|
};
|
28
tasks/send_reminder.js
Normal file
28
tasks/send_reminder.js
Normal file
@ -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
|
||||||
|
};
|
Loading…
Reference in New Issue
Block a user