UNPKG

@smartuy/builderbot-provider-waha

Version:

WAHA (WhatsApp HTTP API) provider for BuilderBot desarrollado por SmartUY

261 lines (260 loc) 11.8 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WahaProvider = void 0; const bot_1 = require("@builderbot/bot"); const axios_1 = __importStar(require("axios")); const events_1 = require("events"); class WahaProvider extends bot_1.ProviderClass { constructor(config) { super(); this.globalVendorArgs = {}; this.vendorInitialized = false; this.config = config; this.vendor = new events_1.EventEmitter(); console.log('WahaProvider constructor called'); // Initialize vendor automatically when provider is created this.initVendor().then(success => { if (success) { console.log('Vendor initialized in constructor'); } else { console.error('Failed to initialize vendor in constructor'); } }); } // This is called by BuilderBot to initialize the provider initVendor() { return __awaiter(this, void 0, void 0, function* () { try { console.log('Initializing Waha provider...'); console.log('Using configuration:', { url: this.config.url, session: this.config.session }); // Check if the session is active using the correct endpoint // According to the WAHA API documentation, the correct endpoint is /api/sessions/{session} const statusUrl = `${this.config.url}/api/sessions/${this.config.session}`; console.log('Checking session status at:', statusUrl); const response = yield axios_1.default.get(statusUrl, { headers: { 'X-Api-Key': this.config.token } }); console.log('Session status response:', response.data); // If session is not active or stopped, try to start it if (!response.data || response.data.status === 'STOPPED') { console.log('Session not active, attempting to start...'); yield this.startSession(); } // Mark vendor as initialized this.vendorInitialized = true; console.log('Waha provider initialized successfully'); return true; } catch (error) { console.error('Error initializing Waha provider:', error); // If we get a 404, the session might not exist, so try to start it if (error instanceof axios_1.AxiosError && error.response && error.response.status === 404) { try { console.log('Session not found, attempting to start a new session...'); yield this.startSession(); this.vendorInitialized = true; return true; } catch (startError) { console.error('Failed to start session:', startError); return false; } } return false; } }); } // Start a session if it's not already active startSession() { return __awaiter(this, void 0, void 0, function* () { try { console.log('Starting session...'); const startUrl = `${this.config.url}/api/sessions/${this.config.session}/start`; console.log('Starting session at:', startUrl); const response = yield axios_1.default.post(startUrl, { session: this.config.session }, { headers: { 'X-Api-Key': this.config.token } }); console.log('Session start response:', response.data); } catch (error) { console.error('Error starting session:', error); throw error; } }); } // Handle incoming messages via webhook initWebhook(app) { app.post('/webhook/waha', (req, res) => { try { const message = req.body; console.log('Received message from Waha webhook:', JSON.stringify(message, null, 2)); if (!message || !message.payload) { console.error('Invalid message format received'); res.status(400).send('Invalid message format'); return; } // Format the message to match what BuilderBot expects const formattedMessage = { from: message.payload.from, body: message.payload.body, hasMedia: message.payload.hasMedia || false, type: 'text', isGroupMsg: false, _data: message.payload._data || {} }; console.log(`Processing message: "${formattedMessage.body}" from ${formattedMessage.from}`); // Emit the message to the vendor if (this.vendor && this.vendorInitialized) { console.log('Emitting message to vendor:', formattedMessage.body); this.vendor.emit('message', formattedMessage); // Also emit directly to the provider's message handler this.handleMessage(formattedMessage); } else { console.error('Vendor not initialized, cannot process message'); } res.status(200).send('OK'); } catch (error) { console.error('Error processing webhook message:', error); res.status(500).send('Internal server error'); } }); } // Define event handlers - required by ProviderClass busEvents() { return [ { event: 'message', func: (payload) => { console.log('Message received in busEvents handler:', (payload === null || payload === void 0 ? void 0 : payload.body) || payload); this.handleMessage(payload); } } ]; } // Handle incoming messages and emit them to the bot handleMessage(message) { try { console.log('Handling message in provider:', message.body); // Emit the message to the bot if (this.vendorInitialized) { // This is the key method that passes messages to the BuilderBot flows this.emit('message', message); console.log('Message emitted to bot flows'); } else { console.error('Cannot handle message, vendor not initialized'); } } catch (error) { console.error('Error handling message:', error); } } // Send a message via the Waha API sendMessage(to_1, message_1) { return __awaiter(this, arguments, void 0, function* (to, message, extraOptions = {}) { try { console.log(`Sending message to ${to}: ${message}`); // According to the WAHA API documentation, the correct endpoint is /api/sendText const sendUrl = `${this.config.url}/api/sendText`; console.log('Sending message via:', sendUrl); const response = yield axios_1.default.post(sendUrl, Object.assign({ chatId: to, text: message, session: this.config.session, linkPreview: false }, extraOptions), { headers: { 'X-Api-Key': this.config.token } }); console.log('Message sent successfully:', response.data); return response.data; } catch (error) { console.error('Error sending message:', error); throw error; } }); } // Send a location via the WAHA API sendLocation(to_1, latitude_1, longitude_1) { return __awaiter(this, arguments, void 0, function* (to, latitude, longitude, title = 'Ubicación', replyTo = null) { try { console.log(`Sending location to ${to}: (${latitude}, ${longitude})`); const sendUrl = `${this.config.url}/api/sendLocation`; console.log('Sending location via:', sendUrl); const response = yield axios_1.default.post(sendUrl, { chatId: to, latitude, longitude, title, session: this.config.session, reply_to: replyTo }, { headers: { 'X-Api-Key': this.config.token } }); console.log('Location sent successfully:', response.data); return response.data; } catch (error) { console.error('Error sending location:', error); throw error; } }); } // Required method for file handling (stub implementation) saveFile(ctx, options) { return __awaiter(this, void 0, void 0, function* () { console.log('saveFile() called (stub implementation)'); return ''; }); } // Called before HTTP server initialization beforeHttpServerInit() { console.log('beforeHttpServerInit() called'); } // Called after HTTP server initialization afterHttpServerInit() { console.log('afterHttpServerInit() called'); console.log('Provider state:', { vendorInitialized: this.vendorInitialized, vendorEvents: this.vendor ? Object.keys(this.vendor._events || {}) : [] }); } } exports.WahaProvider = WahaProvider;