127 lines
4.0 KiB
JavaScript
127 lines
4.0 KiB
JavaScript
// 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
|
|
|
|
// Configuración inicial
|
|
dotenv.config();
|
|
|
|
// Constantes
|
|
const CHROME_PATH = process.env.CHROME_PATH;
|
|
const AUTHORIZED_NUMBER = process.env.AUTHORIZED_NUMBER;
|
|
|
|
// Validación inicial
|
|
if (!AUTHORIZED_NUMBER) {
|
|
console.error('❌ Debes establecer el número autorizado en el archivo .env');
|
|
process.exit(1);
|
|
}
|
|
|
|
// Configuración del cliente
|
|
const clientConfig = {
|
|
authStrategy: new LocalAuth(),
|
|
puppeteer: {
|
|
headless: true,
|
|
executablePath: CHROME_PATH,
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
|
|
}
|
|
};
|
|
|
|
class WhatsAppBot {
|
|
constructor() {
|
|
this.client = new Client(clientConfig);
|
|
this.myId = null;
|
|
this.myNumber = null;
|
|
this.initializeEventHandlers();
|
|
}
|
|
|
|
initializeEventHandlers() {
|
|
this.client.on('qr', this.handleQR);
|
|
this.client.on('ready', this.handleReady.bind(this));
|
|
this.client.on('message_create', this.handleMessage.bind(this));
|
|
this.client.on('message', this.logMessage);
|
|
this.client.on('group_join', this.handleGroupJoin);
|
|
}
|
|
|
|
handleQR(qr) {
|
|
qrcode.generate(qr, { small: true });
|
|
logger.info('🔍 Escanea el QR code con tu WhatsApp.');
|
|
}
|
|
|
|
async handleReady() {
|
|
logger.info('✅ Cliente de WhatsApp está listo!');
|
|
try {
|
|
this.myId = this.client.info.wid._serialized;
|
|
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 chat = await this.client.getChatById(this.myId);
|
|
logger.info(`💭 Chat propio encontrado: ${JSON.stringify(chat, null, 2)}`);
|
|
} catch (error) {
|
|
logger.error(`❌ Error al obtener información: ${error}`);
|
|
}
|
|
}
|
|
|
|
isChatAllowed(messageFrom) {
|
|
const isAllowed = messageFrom === AUTHORIZED_NUMBER;
|
|
if (isAllowed) console.log('🎯 Mensaje detectado desde el número autorizado');
|
|
return isAllowed;
|
|
}
|
|
|
|
async handleMessage(message) {
|
|
if (!this.myId || !this.isChatAllowed(message.from)) return;
|
|
|
|
console.log('📨 Mensaje creado:', {
|
|
from: message.from,
|
|
fromMe: message.fromMe,
|
|
body: message.body,
|
|
type: message.type,
|
|
timestamp: message.timestamp
|
|
});
|
|
|
|
const command = message.body.trim().toLowerCase();
|
|
|
|
if (command === '!ping') {
|
|
await this.handlePingCommand(message);
|
|
} else if (command.startsWith('!clima')) {
|
|
await handleWeatherCommand(this.client, message);
|
|
} else if (command.startsWith('!receta')) {
|
|
await handleRecipeCommand(this.client, message);
|
|
}
|
|
}
|
|
|
|
async handlePingCommand(message) {
|
|
try {
|
|
await this.client.sendMessage(message.from, 'pong');
|
|
console.log(`📤 Respondido 'pong' al número autorizado ${message.from}`);
|
|
} catch (error) {
|
|
console.error('❌ Error al enviar respuesta:', error);
|
|
}
|
|
}
|
|
|
|
logMessage(message) {
|
|
console.log('📩 Mensaje recibido:', {
|
|
from: message.from,
|
|
fromMe: message.fromMe,
|
|
body: message.body
|
|
});
|
|
}
|
|
|
|
handleGroupJoin(notification) {
|
|
console.log('👥 Bot añadido a un nuevo grupo:', notification.id.remote);
|
|
}
|
|
|
|
start() {
|
|
this.client.initialize();
|
|
}
|
|
}
|
|
|
|
// Iniciar el bot
|
|
const bot = new WhatsAppBot();
|
|
bot.start();
|