whatsapp/index.js
2025-05-06 11:58:51 +02:00

72 lines
1.8 KiB
JavaScript

import pkg from 'whatsapp-web.js';
const { Client, LocalAuth, Buttons } = pkg;
import express from 'express';
import qrcode from 'qrcode';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
app.use(express.static('public'));
app.use(express.json());
let qrCodeData = null;
let clientReady = false;
const client = new Client({
authStrategy: new LocalAuth(),
puppeteer: {
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
}
});
client.on('qr', async (qr) => {
qrCodeData = await qrcode.toDataURL(qr);
clientReady = false;
});
client.on('ready', () => {
console.log('✅ WhatsApp prêt');
clientReady = true;
});
client.initialize();
// --- QR PAGE ---
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
app.get('/connected', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'connected.html'));
});
app.get('/api/qrcode', (req, res) => {
res.json({ qr: qrCodeData, connected: clientReady });
});
// --- API ENVOI TEXTE ---
app.post('/sendText', async (req, res) => {
const { phone, message } = req.body;
try {
await client.sendMessage(`${phone}@c.us`, message);
res.json({ success: true });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// --- API ENVOI BOUTONS ---
app.post('/sendButtons', async (req, res) => {
const { phone, title, message, buttons } = req.body;
try {
const formatted = new Buttons(message, buttons.map(b => b.text), title, '');
await client.sendMessage(`${phone}@c.us`, formatted);
res.json({ success: true });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.listen(3000, () => console.log('🚀 Serveur démarré sur http://localhost:3000/login'));