Files
whatsapp-simple-bot/index.js
2025-12-19 17:19:03 +08:00

81 lines
1.8 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const express = require('express');
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const app = express();
app.use(express.json());
// WhatsApp client
const client = new Client({
authStrategy: new LocalAuth(),
puppeteer: {
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
}
});
// Show QR in terminal
client.on('qr', (qr) => {
console.log('Scan this QR code:');
qrcode.generate(qr, { small: true });
});
// When WhatsApp is ready
client.on('ready', () => {
console.log('WhatsApp client ready');
});
// 4⃣ ✅ MESSAGE LISTENER (PUT IT HERE)
client.on('message', async (message) => {
console.log('--- New Message ---');
console.log('From:', message.from); // chat ID
console.log('Body:', message.body);
console.log('Is Group:', message.from.endsWith('@g.us'));
// Example: auto-reply
if (message.body.toLowerCase() === 'ping') {
await message.reply('pong');
}
});
// Initialize WhatsApp
client.initialize();
/**
* POST /send
* {
* "number": "62822932xxxx",
* "message": "hello"
* }
*/
app.get('/send', async (req, res) => {
//const { number, message } = req.body;
let number= "6281336138742";
let message ="hello ini dia";
const chatId = number + '@c.us';
try {
await client.sendMessage(chatId, message);
return res.json({
success: true,
to: number,
message
});
} catch (err) {
console.error(err);
return res.status(500).json({
success: false,
error: 'Failed to send message'
});
}
});
// Start Express server
const PORT = 3019;
app.listen(PORT, () => {
console.log(`Express server running on http://localhost:${PORT}`);
});