whatsappConnector.js•2.54 kB
// src/services/whatsappConnector.js
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
// Read the session name from environment variables to build the path
const sessionName = process.env.WHATSAPP_SESSION_NAME;
let client;
async function initialize() {
console.log('Initializing WhatsApp Connector...');
client = new Client({
authStrategy: new LocalAuth({
// Use the session name from .env to create a unique session folder
dataPath: `./sessions/${sessionName}`
}),
puppeteer: {
executablePath: '/usr/bin/chromium', // Make sure this path is correct for your system!
args: [
'--no-sandbox',
'--disable-setuid-sandbox'
]
}
});
client.on('qr', qr => {
console.log('--- SCAN WHATSAPP QR CODE ---');
qrcode.generate(qr, { small: true });
console.log('-----------------------------');
});
client.on('ready', () => {
console.log('✅ WhatsApp Connector is ready!');
});
await client.initialize();
return true; // Signal that initialization is complete
}
// 2. Tools Definition: An array of objects describing the tools.
// This is what the AI agent will see.
const tools = [
{
name: 'whatsapp.sendMessage',
description: 'Sends a text message to a specified WhatsApp chat ID.',
parameters: {
type: 'object',
properties: {
chatId: { type: 'string', description: 'The chat ID to send the message to (e.g., "1234567890@c.us").' },
message: { type: 'string', description: 'The content of the message to send.' }
},
required: ['chatId', 'message']
}
},
{
name: 'whatsapp.getChats',
description: 'Retrieves a list of the most recent chats.',
parameters: {}
}
];
// 3. Tool Implementations: The actual logic for each tool.
const implementations = {
'whatsapp.sendMessage': async ({ chatId, message }) => {
await client.sendMessage(chatId, message);
return `Message sent to ${chatId}.`;
},
'whatsapp.getChats': async () => {
const chats = await client.getChats();
// Filter and map to return only the necessary info (e.g., name and id)
return chats.slice(0, 10).map(chat => ({ id: chat.id._serialized, name: chat.name }));
}
};
module.exports = {
initialize,
tools,
implementations
};