Prerequisites
Before you begin, make sure you have:- Node.js 20.0.0 or higher installed
- Baileys installed in your project (see Installation)
- A WhatsApp account on your phone
Basic Connection Setup
Follow these steps to create your first WhatsApp bot:1
Create a new file
Create a new file called
bot.ts (or bot.js for JavaScript):bot.ts
2
Define the connection function
Create an async function to handle the connection:
useMultiFileAuthState saves your session credentials in the auth_info_baileys folder so you don’t have to scan the QR code every time.3
Handle connection events
Add event handlers for connection updates:
4
Save credentials on update
Save authentication credentials whenever they update:
5
Handle incoming messages
Listen for incoming messages and send a reply:
6
Start the connection
Return the socket and start the connection:
Complete Example
Here’s the complete working code:bot.ts
Running Your Bot
1
Run the script
Execute your bot file:
2
Scan the QR code
A QR code will appear in your terminal. Open WhatsApp on your phone:
- Go to Settings > Linked Devices
- Tap Link a Device
- Scan the QR code displayed in your terminal
The QR code expires after a short time. If it expires, restart your script to generate a new one.
3
Test your bot
Once connected, send a message to your own WhatsApp number from another contact. Your bot should automatically reply!
Using Pairing Code (Alternative)
If you prefer using a pairing code instead of QR code:Phone numbers for pairing must include the country code with no
+, (), or - symbols. For example: 1234567890 for US numbers.Sending Your First Message
Once connected, you can send messages programmatically:WhatsApp ID Format
WhatsApp IDs (JIDs) follow these formats:
- Individual:
[country code][phone number]@s.whatsapp.net - Group:
[group-id]@g.us - Broadcast:
[timestamp]@broadcast - Status:
status@broadcast
What’s Next?
Authentication Guide
Learn about session management and authentication states
Handling Events
Master the event system for messages, groups, and more
Sending Messages
Explore all message types: media, polls, reactions, and more
Complete Example
View the full example with advanced features
Common Issues
QR code not appearing
QR code not appearing
Make sure
printQRInTerminal: true is set in your socket configuration. Also ensure your terminal supports rendering QR codes.Connection keeps closing
Connection keeps closing
Check your internet connection. Also verify that you’re not logged out from WhatsApp. The bot will automatically reconnect unless you’ve been logged out.
Messages not being received
Messages not being received
Make sure you’re saving credentials with
sock.ev.on('creds.update', saveCreds). Without this, message decryption will fail.Cannot send messages to myself
Cannot send messages to myself
Use the
!msg.key.fromMe check to filter out your own messages and avoid loops.