listo procesamiento y enrutamiento de mensajes de whatsapp

This commit is contained in:
2025-06-04 23:45:48 -06:00
parent 37c4384dec
commit b154e74538
2 changed files with 20 additions and 29 deletions

View File

@@ -19,6 +19,8 @@ services:
environment:
- OPEN_WA_URL=http://openwa:8080
- LLM_AGENT_URL=http://llm-agent:8000
- WEBHOOK_URL=http://whatsapp-router:3001/webhook
- NODE_ENV=production
ports:
- "3001:3001"
networks:

View File

@@ -85,7 +85,7 @@ async function registerWebhook() {
const eventConfig = {
onAck: false,
onAddedToGroup: true,
onAnyMessage: true,
onAnyMessage: false,
onBattery: true,
onBroadcast: true,
onButton: true,
@@ -100,7 +100,7 @@ async function registerWebhook() {
onIncomingCall: false,
onLabel: true,
onLogout: true,
onMessage: false,
onMessage: true,
onMessageDeleted: true,
onNewProduct: true,
onOrder: true,
@@ -126,51 +126,40 @@ async function registerWebhook() {
app.use(express.json());
app.post('/webhook', async (req: express.Request, res: express.Response) => {
log('debug', 'Received webhook request:', req.body);
let message: WhatsAppMessage | undefined;
let text: string | undefined;
let from: string | undefined;
if (req.body && req.body.data) {
// New webhook format from nucleo-whatsapp
message = req.body.data as WhatsAppMessage;
text = (req.body.data.body as string) || req.body.data.text;
from = req.body.data.from;
} else {
({ message, text, from } = req.body as {
message?: WhatsAppMessage;
text?: string;
from?: string;
});
}
try {
if (req.body && req.body.data) {
// New webhook format from nucleo-whatsapp
message = req.body.data as WhatsAppMessage;
text = (req.body.data.body as string) || req.body.data.text;
from = req.body.data.from;
} else {
throw new Error('Invalid webhook format');
}
}catch{}
const incoming = message || text;
log('debug', 'Webhook received:', {
message: incoming,
from,
chatId: message?.chatId,
type: typeof incoming
});
if (incoming) {
const tipo = typeof incoming === 'string' ? 'texto' : 'objeto';
if (message) {
const tipo = typeof message === 'string' ? 'texto' : 'objeto';
const origen = from || (message?.chatId ?? 'desconocido');
log('info', `📩 Mensaje recibido (${tipo}) de ${origen}`);
log('info', `📩 Mensaje recibido (${message?.text}) de ${origen}`);
}
try {
if (!incoming) return res.sendStatus(200);
if (!message) return res.sendStatus(200);
if (!openWaUrl) throw new Error('Service URLs not configured');
const chatId = (message && message.chatId) || from;
const handler = getHandler(chatId, agentUrl);
if (!handler) throw new Error('No handler configured');
let reply: string;
if (typeof handler === 'string') {
const agentRes = await axios.post(handler, { message: incoming });
const agentRes = await axios.post(handler, {message});
reply = agentRes.data.reply || agentRes.data;
} else {
reply = await handler(incoming);
reply = await handler(message);
}
await axios.post(`${openWaUrl}/sendText`, { args: { to: from, content: reply } });
} catch (err: any) {