If you'd like to financially support this project, you can do so by supporting the current maintainer here.
Disclaimer
This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or its affiliates.
The official WhatsApp website can be found at whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
The maintainers of Baileys do not in any way condone the use of this application in practices that violate the Terms of Service of WhatsApp. The maintainers of this application call upon the personal responsibility of its users to use this application in a fair way, as it is intended to be used.
Use at your own discretion. Do not spam people with this. We discourage any stalkerware, bulk or automated messaging usage.
Baileys does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a WebSocket.
Not running Selenium or Chromium saves you like half a gig of ram :/
Baileys supports interacting with the multi-device & web versions of WhatsApp.
Thank you to @pokearaujo for writing his observations on the workings of WhatsApp Multi-Device. Also, thank you to @Sigalor for writing his observations on the workings of WhatsApp Web and thanks to @Rhymen for the go implementation.
[!IMPORTANT]
The original repository had to be removed by the original author - we now continue development in this repository here.
This is the only official repository and is maintained by the community.
Join the Discord here
Example
Do check out & run example.ts to see an example usage of the library.
The script covers most common use cases.
To run the example script, download or clone the repo and then type the following in a terminal:
cd path/to/Baileys
yarn
yarn example
Install
Use the stable version:
yarn add @whiskeysockets/baileys
Use the edge version (no guarantee of stability, but latest fixes + features)
yarn add github:WhiskeySockets/Baileys
Then import your code using:
import makeWASocket from '@whiskeysockets/baileys'
WhatsApp provides a multi-device API that allows Baileys to be authenticated as a second WhatsApp client by scanning a QR code or Pairing Code with WhatsApp on your phone.
[!NOTE]
Here is a simple example of event handling
[!TIP]
You can see all supported socket configs here (Recommended)
Starting socket with QR-CODE
[!TIP]
You can customize browser name if you connect with QR-CODE, with Browser constant, we have some browsers config, see here
ts
1importmakeWASocketfrom'@whiskeysockets/baileys'23const sock =makeWASocket({4// can provide additional config here5 browser:Browsers.ubuntu('My App'),6 printQRInTerminal:true7})
If the connection is successful, you will see a QR code printed on your terminal screen, scan it with WhatsApp on your phone and you'll be logged in!
Starting socket with Pairing Code
[!IMPORTANT]
Pairing Code isn't Mobile API, it's a method to connect Whatsapp Web without QR-CODE, you can connect only with one device, see here
The phone number can't have + or () or -, only numbers, you must provide country code
ts
1importmakeWASocketfrom'@whiskeysockets/baileys'23const sock =makeWASocket({4// can provide additional config here5 printQRInTerminal:false//need to be false6})78if(!sock.authState.creds.registered){9constnumber='XXXXXXXXXXX'10const code =await sock.requestPairingCode(number)11console.log(code)12}
Receive Full History
Set syncFullHistory as true
Baileys, by default, use chrome browser config
If you'd like to emulate a desktop connection (and receive more message history), this browser setting to your Socket config:
ts
1const sock =makeWASocket({2...otherOpts,3// can use Windows, Ubuntu here too4 browser:Browsers.macOS('Desktop'),5 syncFullHistory:true6})
Important Notes About Socket Config
Caching Group Metadata (Recommended)
If you use baileys for groups, we recommend you to set cachedGroupMetadata in socket config, you need to implement a cache like this:
If you want to improve sending message, retrying when error occurs and decrypt poll votes, you need to have a store and set getMessage config in socket like this:
You obviously don't want to keep scanning the QR code every time you want to connect.
So, you can load the credentials to log back in:
ts
1importmakeWASocket,{ useMultiFileAuthState }from'@whiskeysockets/baileys'23const{ state, saveCreds }=awaituseMultiFileAuthState('auth_info_baileys')45// will use the given state to connect6// so if valid credentials are available -- it'll connect without QR7const sock =makeWASocket({ auth: state })89// this will be called as soon as the credentials are updated10sock.ev.on('creds.update', saveCreds)
[!IMPORTANT]
useMultiFileAuthState is a utility function to help save the auth state in a single folder, this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system.
[!NOTE]
When a message is received/sent, due to signal sessions needing updating, the auth keys (authState.keys) will update. Whenever that happens, you must save the updated keys (authState.keys.set() is called). Not doing so will prevent your messages from reaching the recipient & cause other unexpected consequences. The useMultiFileAuthState function automatically takes care of that, but for any other serious implementation -- you will need to be very careful with the key state management.
Handling Events
Baileys uses the EventEmitter syntax for events.
They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
[!IMPORTANT]
The events are these, it's important you see all events
[!NOTE]
This example includes basic auth storage too
ts
1importmakeWASocket,{DisconnectReason, useMultiFileAuthState }from'@whiskeysockets/baileys'2import{Boom}from'@hapi/boom'34asyncfunctionconnectToWhatsApp(){5const{ state, saveCreds }=awaituseMultiFileAuthState('auth_info_baileys')6const sock =makeWASocket({7// can provide additional config here8 auth: state,9 printQRInTerminal:true10})11 sock.ev.on('connection.update',(update)=>{12const{ connection, lastDisconnect }= update
13if(connection ==='close'){14const shouldReconnect =(lastDisconnect.errorasBoom)?.output?.statusCode !==DisconnectReason.loggedOut15console.log('connection closed due to ', lastDisconnect.error,', reconnecting ', shouldReconnect)16// reconnect if not logged out17if(shouldReconnect){18connectToWhatsApp()19}20}elseif(connection ==='open'){21console.log('opened connection')22}23})24 sock.ev.on('messages.upsert', event =>{25for(const m of event.messages){26console.log(JSON.stringify(m,undefined,2))2728console.log('replying to', m.key.remoteJid)29await sock.sendMessage(m.key.remoteJid!,{ text:'Hello Word'})30}31})3233// to storage creds (session info) when it updates34 sock.ev.on('creds.update', saveCreds)35}36// run in main file37connectToWhatsApp()
[!IMPORTANT]
In messages.upsert it's recommended to use a loop like for (const message of event.messages) to handle all messages in array
Decrypt Poll Votes
By default poll votes are encrypted and handled in messages.update
getMessage is a store implementation (in your end)
Summary of Events on First Connection
When you connect first time, connection.update will be fired requesting you to restart sock
Then, history messages will be received in messaging.history-set
Implementing a Data Store
Baileys does not come with a defacto storage for chats, contacts, or messages. However, a simple in-memory implementation has been provided. The store listens for chat updates, new messages, message updates, etc., to always have an up-to-date version of the data.
[!IMPORTANT]
I highly recommend building your own data store, as storing someone's entire chat history in memory is a terrible waste of RAM.
It can be used as follows:
ts
1importmakeWASocket,{ makeInMemoryStore }from'@whiskeysockets/baileys'2// the store maintains the data of the WA connection in memory3// can be written out to a file & read from it4const store =makeInMemoryStore({})5// can be read from a file6store.readFromFile('./baileys_store.json')7// saves the state to a file every 10s8setInterval(()=>{9 store.writeToFile('./baileys_store.json')10},10_000)1112const sock =makeWASocket({})13// will listen from this socket14// the store can listen from a new socket once the current socket outlives its lifetime15store.bind(sock.ev)1617sock.ev.on('chats.upsert',()=>{18// can use 'store.chats' however you want, even after the socket dies out19// 'chats' => a KeyedDB instance20console.log('got chats', store.chats.all())21})2223sock.ev.on('contacts.upsert',()=>{24console.log('got contacts',Object.values(store.contacts))25})26
The store also provides some simple functions such as loadMessages that utilize the store to speed up data retrieval.
Whatsapp IDs Explain
id is the WhatsApp ID, called jid too, of the person or group you're sending the message to.
It must be in the format [country code][phone number]@s.whatsapp.net
Example for people: +19999999999@s.whatsapp.net.
For groups, it must be in the format 123456789-123345@g.us.
For broadcast lists, it's [timestamp of creation]@broadcast.
For stories, the ID is status@broadcast.
Utility Functions
getContentType, returns the content type for any message
getDevice, returns the device from message
makeCacheableSignalKeyStore, make auth store more fast
downloadContentFromMessage, download content from any message
Sending Messages
Send all types of messages with a single function
Here you can see all message contents supported, like text message
Here you can see all options supported, like quote message
1const vcard ='BEGIN:VCARD\n'// metadata of the contact card2+'VERSION:3.0\n'3+'FN:Jeff Singh\n'// full name4+'ORG:Ashoka Uni;\n'// the organization of the contact5+'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n'// WhatsApp ID + phone number6+'END:VCARD'78await sock.sendMessage(9 id,10{11 contacts:{12 displayName:'Jeff',13 contacts:[{ vcard }]14}15}16)
Reaction Message
You need to pass the key of message, you can retrieve from store or use a key object
ts
1await sock.sendMessage(2 jid,3{4 react:{5 text:'💖',// use an empty string to remove the reaction6 key: message.key7}8}9)
Pin Message
You need to pass the key of message, you can retrieve from store or use a key object
1await sock.sendMessage(2 id,3{4 video:{5 url:'./Media/ma_gif.mp4'6},7 caption:'hello word',8 ptv:false// if set to true, will send as a `video note`9}10)
Audio Message
To audio message work in all devices you need to convert with some tool like ffmpeg with this flags:
Note: deleting for oneself is supported via chatModify, see in this section
Editing Messages
You can pass all editable contents here
ts
1await sock.sendMessage(jid,{2 text:'updated text goes here',3 edit: response.key,4});
Manipulating Media Messages
Thumbnail in Media Messages
For media messages, the thumbnail can be generated automatically for images & stickers provided you add jimp or sharp as a dependency in your project using yarn add jimp or yarn add sharp.
Thumbnails for videos can also be generated automatically, though, you need to have ffmpeg installed on your system.
Downloading Media Messages
If you want to save the media you received
ts
1import{ createWriteStream }from'fs'2import{ downloadMediaMessage, getContentType }from'@whiskeysockets/baileys'34sock.ev.on('messages.upsert',async({[m]})=>{5if(!m.message)return// if there is no text or media message6const messageType =getContentType(m)// get what type of message it is (text, image, video...)78// if the message is an image9if(messageType ==='imageMessage'){10// download the message11const stream =awaitdownloadMediaMessage(12 m,13'stream',// can be 'buffer' too14{},15{16 logger,17// pass this so that baileys can request a reupload of media18// that has been deleted19 reuploadRequest: sock.updateMediaMessage20}21)22// save to file23const writeStream =createWriteStream('./my-download.jpeg')24 stream.pipe(writeStream)25}26}
Re-upload Media Message to Whatsapp
WhatsApp automatically removes old media from their servers. For the device to access said media -- a re-upload is required by another device that has it. This can be accomplished using:
await sock.updateMediaMessage(msg)
Reject Call
You can obtain callId and callFrom from call event
await sock.rejectCall(callId, callFrom)
Send States in Chat
Reading Messages
A set of message keys must be explicitly marked read now.
You cannot mark an entire 'chat' read as it were with Baileys Web.
This means you have to keep track of unread messages.
ts
1const key:WAMessageKey2// can pass multiple keys to read multiple messages as well3await sock.readMessages([key])
The message ID is the unique identifier of the message that you are marking as read.
On a WAMessage, the messageID can be accessed using messageID = message.key.id.
This lets the person/group with jid know whether you're online, offline, typing etc.
await sock.sendPresenceUpdate('available', jid)
[!NOTE]
If a desktop client is active, WA doesn't send push notifications to the device. If you would like to receive said notifications -- mark your Baileys client offline using sock.sendPresenceUpdate('unavailable')
Modifying Chats
WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
[!IMPORTANT]
If you mess up one of your updates, WA can log you out of all your devices and you'll have to log in again.
Archive a Chat
ts
1const lastMsgInChat =awaitgetLastMessageInChat(jid)// implement this on your end2await sock.chatModify({ archive:true, lastMessages:[lastMsgInChat]}, jid)
1const lastMsgInChat =awaitgetLastMessageInChat(jid)// implement this on your end2// mark it unread3await sock.chatModify({ markRead:false, lastMessages:[lastMsgInChat]}, jid)
1const lastMsgInChat =awaitgetLastMessageInChat(jid)// implement this on your end2await sock.chatModify({3delete:true,4 lastMessages:[5{6 key: lastMsgInChat.key,7 messageTimestamp: lastMsgInChat.messageTimestamp8}9]10},11 jid
12)
Pin/Unpin a Chat
ts
1await sock.chatModify({2 pin:true// or `false` to unpin3},4 jid
5)
Star/Unstar a Message
ts
1await sock.chatModify({2 star:{3 messages:[4{5 id:'messageID',6 fromMe:true// or `false`7}8],9 star:true// - true: Star Message; false: Unstar Message10}11},12 jid
13)
Disappearing Messages
Ephemeral can be:
Time
Seconds
Remove
0
24h
86.400
7d
604.800
90d
7.776.000
You need to pass in Seconds, default is 7 days
ts
1// turn on disappearing messages2await sock.sendMessage(3 jid,4// this is 1 week in seconds -- how long you want messages to appear for5{ disappearingMessagesInChat:WA_DEFAULT_EPHEMERAL}6)78// will send as a disappearing message9await sock.sendMessage(jid,{ text:'hello'},{ ephemeralExpiration:WA_DEFAULT_EPHEMERAL})1011// turn off disappearing messages12await sock.sendMessage(13 jid,14{ disappearingMessagesInChat:false}15)
User Querys
Check If ID Exists in Whatsapp
ts
1const[result]=await sock.onWhatsApp(jid)2if(result.exists)console.log(`${jid} exists on WhatsApp, as jid: ${result.jid}`)
Query Chat History (groups too)
You need to have oldest message in chat
ts
1const msg =awaitgetOldestMessageInChat(jid)// implement this on your end2await sock.fetchMessageHistory(350,//quantity (max: 50 per query)4 msg.key,5 msg.messageTimestamp6)
Messages will be received in messaging.history-set event
Fetch Status
ts
1const status =await sock.fetchStatus(jid)2console.log('status: '+ status)
Fetch Profile Picture (groups too)
To get the display picture of some person/group
ts
1// for low res picture2const ppUrl =await sock.profilePictureUrl(jid)3console.log(ppUrl)45// for high res picture6const ppUrl =await sock.profilePictureUrl(jid,'image')
Fetch Bussines Profile (such as description or category)
Fetch Someone's Presence (if they're typing or online)
ts
1// the presence update is fetched and called here2sock.ev.on('presence.update',console.log)34// request updates for a chat5await sock.presenceSubscribe(jid)
Change Profile
Change Profile Status
await sock.updateProfileStatus('Hello World!')
Change Profile Name
await sock.updateProfileName('My name')
Change Display Picture (groups too)
To change your display picture or a group's
[!NOTE]
Like media messages, you can pass { stream: Stream } or { url: Url } or Buffer directly, you can see more here
1// title & participants2const group =await sock.groupCreate('My Fab Group',['1234@s.whatsapp.net','4564@s.whatsapp.net'])3console.log('created group with id: '+ group.gid)4await sock.sendMessage(group.id,{ text:'hello there'})// say hello to everyone on the group
Add/Remove or Demote/Promote
ts
1// id & people to add to the group (will throw error if it fails)2await sock.groupParticipantsUpdate(3 jid,4['abcd@s.whatsapp.net','efgh@s.whatsapp.net'],5'add'// replace this parameter with 'remove' or 'demote' or 'promote'6)
1// only allow admins to send messages2await sock.groupSettingUpdate(jid,'announcement')3// allow everyone to send messages4await sock.groupSettingUpdate(jid,'not_announcement')5// allow everyone to modify the group's settings -- like display picture etc.6await sock.groupSettingUpdate(jid,'unlocked')7// only allow admins to modify the group's settings8await sock.groupSettingUpdate(jid,'locked')
Leave a Group
ts
1// will throw error if it fails2await sock.groupLeave(jid)
Get Invite Code
To create link with code use 'https://chat.whatsapp.com/' + code
1const response =await sock.groupRequestParticipantsUpdate(2 jid,// group id3['abcd@s.whatsapp.net','efgh@s.whatsapp.net'],4'approve'// or 'reject' 5)6console.log(response)
Baileys is written with custom functionality in mind. Instead of forking the project & re-writing the internals, you can simply write your own extensions.
Enabling Debug Level in Baileys Logs
First, enable the logging of unhandled messages from WhatsApp by setting:
This will enable you to see all sorts of messages WhatsApp sends in the console.
How Whatsapp Communicate With Us
[!TIP]
If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
Example: Functionality to track the battery percentage of your phone. You enable logging and you'll see a message about your battery pop up in the console:
[!TIP]
Recommended to see onMessageReceived function in socket.ts file to understand how websockets events are fired
ts
1// for any message with tag 'edge_routing'2sock.ws.on('CB:edge_routing',(node:BinaryNode)=>{})34// for any message with tag 'edge_routing' and id attribute = abcd5sock.ws.on('CB:edge_routing,id:abcd',(node:BinaryNode)=>{})67// for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info8sock.ws.on('CB:edge_routing,id:abcd,routing_info',(node:BinaryNode)=>{})
License
Copyright (c) 2025 Rajeh Taher/WhiskeySockets
Licensed under the MIT License:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Thus, the maintainers of the project can't be held liable for any potential misuse of this project.