Introduction to Baileys: WhatsApp Web API
Baileys is a powerful JavaScript library that allows developers to interact with WhatsApp Web APIs effortlessly. This tutorial provides an in-depth introduction to Baileys along with dozens of useful API explanations and sample codes to help you get started quickly.
Setup and Installation
npm install @adiwajshing/baileys
Connecting to WhatsApp Web
const { WAConnection } = require('@adiwajshing/baileys');
async function connectToWhatsApp() {
const conn = new WAConnection();
conn.on('open', () => {
console.log('Connected to WhatsApp Web');
});
await conn.connect();
}
connectToWhatsApp();
Sending a Text Message
async function sendMessage(jid, message) {
await conn.sendMessage(jid, message, MessageType.text);
}
sendMessage('123456789@s.whatsapp.net', 'Hello, this is a test message!');
Receiving Messages
conn.on('chat-update', chatUpdate => {
if (chatUpdate.messages && chatUpdate.count) {
const message = chatUpdate.messages.all()[0];
console.log('Received message: ', message);
}
});
Handling Media Files
async function sendMedia(jid, filePath) {
const buffer = fs.readFileSync(filePath);
await conn.sendMessage(jid, buffer, MessageType.image);
}
sendMedia('123456789@s.whatsapp.net', 'path/to/image.jpg');
Creating a Simple WhatsApp Bot
Here’s a basic example of a WhatsApp bot using Baileys, integrating received messages and automatically responding:
const { WAConnection, MessageType } = require('@adiwajshing/baileys');
const fs = require('fs');
const conn = new WAConnection();
conn.on('open', () => {
const authInfo = conn.base64EncodedAuthInfo();
fs.writeFileSync('auth_info.json', JSON.stringify(authInfo));
});
conn.loadAuthInfo('auth_info.json');
await conn.connect();
conn.on('chat-update', async chatUpdate => {
if (!chatUpdate.hasNewMessage) return;
const message = chatUpdate.messages.all()[0];
if (!message.message || message.key.fromMe) return;
const content = message.message.conversation;
console.log('Received message:', content);
if (content.toLowerCase() === 'hello') {
await conn.sendMessage(message.key.remoteJid, 'Hello! How can I assist you today?', MessageType.text);
}
});
And there you have it, a basic yet functional WhatsApp bot using Baileys. From sending text messages to handling media files, Baileys is an invaluable tool for any developer looking to build WhatsApp integrations efficiently. Happy coding!
Hash: 2159433528245352a3663c5405452df39cace0656e871a5c76d48e1261373c09