ya funciona al 80% el agent, es una pasada

This commit is contained in:
2025-06-07 02:00:43 -06:00
parent 9c16fb55fa
commit 40dcfe00e4
6 changed files with 170 additions and 277 deletions

View File

@@ -1,6 +1,7 @@
import express from 'express';
import dotenv from 'dotenv';
import { registerConversationRoutes } from './routes/conversationActions';
import whatsappActionsRouter from './routes/whatsappActions'; // New import
import {
registerWebhookRoutes,
clearWebhooks,
@@ -8,7 +9,6 @@ import {
waitForGateway,
WebhookConfig,
} from './webhook';
import whatsappActionsRouter from './routes/whatsappActions'; // New import
dotenv.config();
@@ -51,9 +51,9 @@ const config: WebhookConfig = {
registerConversationRoutes(app, openWaUrl);
registerWebhookRoutes(app, config, openWaUrl, agentUrl);
app.use('/whatsapp', whatsappActionsRouter); // New line
// Register new whatsappActions routes
app.use('/whatsapp', whatsappActionsRouter); // New line
app.listen(port, async () => {
console.log(`WhatsApp router listening on ${port}`);

View File

@@ -6,6 +6,7 @@ import {
buildConversation,
} from '../store/conversation';
export function registerConversationRoutes(app: Application, openWaUrl: string | undefined) {
app.get('/conversations', (req, res) => {
console.log('[routes] GET /conversations');
@@ -39,6 +40,7 @@ export function registerConversationRoutes(app: Application, openWaUrl: string |
app.delete('/conversations/:id', (req, res) => {
console.log(`[routes] DELETE /conversations/${req.params.id}`);
const deleted = deleteConversation(req.params.id);
console.log(`Conversation ${req.params.id} deleted: ${deleted}`);
res.json({ success: deleted });
});
}

View File

@@ -1,33 +1,21 @@
import express, { Router, Request, Response, NextFunction } from 'express';
import * as whatsappClient from '../whatsappClient';
// Assuming OPEN_WA_URL is set in the environment.
// For local development, dotenv would typically be used in the main app entry point (e.g., index.ts)
// require('dotenv').config(); // Potentially, but better if handled by the main application loader
import dotenv from 'dotenv';
dotenv.config();
const router = Router();
// Retrieve OpenWA URL from environment variables
// This is done once when the module is loaded.
const openWaUrl = process.env.OPEN_WA_URL;
// Middleware to check if openWaUrl is configured
// This runs for every request to this router
router.use((req: Request, res: Response, next: NextFunction) => {
if (!openWaUrl) {
console.error('[routes/whatsappActions] Service OPEN_WA_URL not configured');
return res.status(500).json({ error: 'Service OPEN_WA_URL not configured. Please set the environment variable.' });
}
// Pass openWaUrl to subsequent handlers via res.locals if preferred,
// or they can access the `openWaUrl` constant from the module scope.
// For simplicity, handlers will use the module-scoped `openWaUrl`.
next();
});
// Route implementations
// POST /send-text
// POST /sendText
router.post('/sendText', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /sendText called');
try {
const { args } = req.body;
const { to, content } = args || {};
@@ -38,19 +26,17 @@ router.post('/sendText', async (req: Request, res: Response) => {
res.json(result);
} catch (error: any) {
console.error('[routes/whatsappActions] Error in /sendText:', error.message);
// Check if the error message is already a JSON string from whatsappClient's error handling
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
// If not, send the plain error message
} catch {
res.status(500).json({ error: error.message || 'Failed to send text message' });
}
}
});
// POST /deleteChat
router.post('/deleteChat', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /deleteChat called');
try {
const { args } = req.body;
const { chatId } = args || {};
@@ -58,22 +44,22 @@ router.post('/deleteChat', async (req: Request, res: Response) => {
return res.status(400).json({ error: 'Missing "chatId" in request body' });
}
const result = await whatsappClient.deleteChat(openWaUrl!, chatId);
console.log('[routes/whatsappActions] Chat deleted successfully:', result);
res.json(result);
} catch (error: any) {
console.error('[routes/whatsappActions] Error in /deleteChat:', error.message);
try {
// Attempt to parse error message if it's from whatsappClient's structured error
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
// If not, send the plain error message
} catch {
res.status(500).json({ error: error.message || 'Failed to delete chat' });
}
}
});
// POST /deleteMessage
router.post('/deleteMessage', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /deleteMessage called');
try {
const { args } = req.body;
const { chatId, messageId, onlyLocal } = args || {};
@@ -91,14 +77,14 @@ router.post('/deleteMessage', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to delete message' });
}
}
});
// POST /editMessage
router.post('/editMessage', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /editMessage called');
try {
const { args } = req.body;
const { messageId, text } = args || {};
@@ -112,14 +98,14 @@ router.post('/editMessage', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to edit message' });
}
}
});
// POST /forwardMessages
router.post('/forwardMessages', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /forwardMessages called');
try {
const { args } = req.body;
const { to, messages, skipMyMessages } = args || {};
@@ -137,14 +123,14 @@ router.post('/forwardMessages', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to forward messages' });
}
}
});
// POST /sendImage
router.post('/sendImage', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /sendImage called');
try {
const { args } = req.body;
const { to, file, filename, caption, quotedMsgId, waitForId, hideTags } = args || {};
@@ -166,14 +152,14 @@ router.post('/sendImage', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to send image message' });
}
}
});
// POST /sendFile
router.post('/sendFile', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /sendFile called');
try {
const { args } = req.body;
const {
@@ -205,14 +191,14 @@ router.post('/sendFile', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to send file message' });
}
}
});
// POST /getChat
router.post('/getChat', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /getChat called');
try {
const { args } = req.body;
const { contactId } = args || {};
@@ -226,110 +212,14 @@ router.post('/getChat', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to retrieve chat' });
}
}
});
// POST /groups
router.post('/groups', async (req: Request, res: Response) => {
try {
const { groupName, contactIds } = req.body;
if (!groupName || !contactIds || !Array.isArray(contactIds) || contactIds.length === 0) {
return res.status(400).json({ error: 'Missing "groupName" or "contactIds" (must be a non-empty array) in request body' });
}
const result = await whatsappClient.createGroup(openWaUrl!, groupName, contactIds);
res.json(result);
} catch (error: any) {
console.error('[routes/whatsappActions] Error in /groups:', error.message);
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
res.status(500).json({ error: error.message || 'Failed to create group' });
}
}
});
// GET /contacts/:contactId
router.get('/contacts/:contactId', async (req: Request, res: Response) => {
try {
const { contactId } = req.params;
if (!contactId) {
return res.status(400).json({ error: 'Missing "contactId" in request params' });
}
const result = await whatsappClient.getContact(openWaUrl!, contactId);
res.json(result);
} catch (error: any) {
console.error(`[routes/whatsappActions] Error in /contacts/${req.params.contactId}:`, error.message);
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
res.status(500).json({ error: error.message || 'Failed to retrieve contact' });
}
}
});
// GET /blocklist
router.get('/blocklist', async (req: Request, res: Response) => {
try {
const result = await whatsappClient.getBlocklist(openWaUrl!);
res.json(result);
} catch (error: any) {
console.error('[routes/whatsappActions] Error in /blocklist:', error.message);
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
res.status(500).json({ error: error.message || 'Failed to retrieve blocklist' });
}
}
});
// POST /blocklist/block
router.post('/blocklist/block', async (req: Request, res: Response) => {
try {
const { contactId } = req.body;
if (!contactId) {
return res.status(400).json({ error: 'Missing "contactId" in request body' });
}
const result = await whatsappClient.blockContact(openWaUrl!, contactId);
res.json(result);
} catch (error: any) {
console.error('[routes/whatsappActions] Error in /blocklist/block:', error.message);
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
res.status(500).json({ error: error.message || 'Failed to block contact' });
}
}
});
// POST /blocklist/unblock
router.post('/blocklist/unblock', async (req: Request, res: Response) => {
try {
const { contactId } = req.body;
if (!contactId) {
return res.status(400).json({ error: 'Missing "contactId" in request body' });
}
const result = await whatsappClient.unblockContact(openWaUrl!, contactId);
res.json(result);
} catch (error: any) {
console.error('[routes/whatsappActions] Error in /blocklist/unblock:', error.message);
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
res.status(500).json({ error: error.message || 'Failed to unblock contact' });
}
}
});
// POST /getAllChats
router.post('/getAllChats', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /getAllChats called');
try {
const { args } = req.body;
const { withNewMessageOnly } = args || {};
@@ -340,14 +230,14 @@ router.post('/getAllChats', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to retrieve all chats' });
}
}
});
// POST /getAllChatIds
router.post('/getAllChatIds', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /getAllChatIds called');
try {
const result = await whatsappClient.getAllChatIds(openWaUrl!);
res.json(result);
@@ -356,14 +246,14 @@ router.post('/getAllChatIds', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to retrieve chat IDs' });
}
}
});
// POST /getAllMessagesInChat
router.post('/getAllMessagesInChat', async (req: Request, res: Response) => {
console.log('[routes/whatsappActions] POST /getAllMessagesInChat called');
try {
const { args } = req.body;
const { chatId, includeMe, includeNotifications } = args || {};
@@ -382,7 +272,7 @@ router.post('/getAllMessagesInChat', async (req: Request, res: Response) => {
try {
const parsedError = JSON.parse(error.message.substring(error.message.indexOf('{')));
return res.status(parsedError.status || 500).json({ error: parsedError });
} catch (e) {
} catch {
res.status(500).json({ error: error.message || 'Failed to retrieve chat messages' });
}
}

View File

@@ -62,7 +62,7 @@ export function registerWebhookRoutes(
if (chatId) {
try {
conv = await addMessageToConversation(chatId, message, openWaUrl);
console.log(`🔄 Updated conversation for ${chatId}`, conv);
console.log(`🔄 Updated conversation for ${chatId}`);
} catch (err: any) {
console.warn('Failed updating conversation:', err.message);