Install
Use the stable version:
yarn add nishiki-bail
Then import your code using:
import makeWASocket from 'nishiki-bail''
Index
-
Connecting Account
- Connect with QR-CODE
- Connect with Pairing Code
- Receive Full History
-
Important Notes About Socket Config
- Caching Group Metadata (Recommended)
- Improve Retry System & Decrypt Poll Votes
- Receive Notifications in Whatsapp App
-
Save Auth Info
-
Handling Events
- Example to Start
- Decrypt Poll Votes
- Summary of Events on First Connection
-
Implementing a Data Store
-
Whatsapp IDs Explain
-
Utility Functions
-
Sending Messages
- Non-Media Messages
- Text Message
- Quote Message
- Mention User
- Forward Messages
- Location Message
- Contact Message
- Reaction Message
- Pin Message
- Poll Message
- Sending with Link Preview
- Media Messages
- Gif Message
- Video Message
- Audio Message
- Image Message
- ViewOnce Message
-
Modify Messages
- Delete Messages (for everyone)
- Edit Messages
-
Manipulating Media Messages
- Thumbnail in Media Messages
- Downloading Media Messages
- Re-upload Media Message to Whatsapp
-
Reject Call
-
Send States in Chat
- Reading Messages
- Update Presence
-
Modifying Chats
- Archive a Chat
- Mute/Unmute a Chat
- Mark a Chat Read/Unread
- Delete a Message for Me
- Delete a Chat
- Star/Unstar a Message
- Disappearing Messages
-
User Querys
- Check If ID Exists in Whatsapp
- Query Chat History (groups too)
- Fetch Status
- Fetch Profile Picture (groups too)
- Fetch Bussines Profile (such as description or category)
- Fetch Someone's Presence (if they're typing or online)
-
Change Profile
- Change Profile Status
- Change Profile Name
- Change Display Picture (groups too)
- Remove display picture (groups too)
-
Groups
- Create a Group
- Add/Remove or Demote/Promote
- Change Subject (name)
- Change Description
- Change Settings
- Leave a Group
- Get Invite Code
- Revoke Invite Code
- Join Using Invitation Code
- Get Group Info by Invite Code
- Query Metadata (participants, name, description...)
- Join using groupInviteMessage
- Get Request Join List
- Approve/Reject Request Join
- Get All Participating Groups Metadata
- Toggle Ephemeral
- Change Add Mode
-
Privacy
- Block/Unblock User
- Get Privacy Settings
- Get BlockList
- Update LastSeen Privacy
- Update Online Privacy
- Update Profile Picture Privacy
- Update Status Privacy
- Update Read Receipts Privacy
- Update Groups Add Privacy
- Update Default Disappearing Mode
-
Broadcast Lists & Stories
- Send Broadcast & Stories
- Query a Broadcast List's Recipients & Name
-
Writing Custom Functionality
- Enabling Debug Level in Baileys Logs
- How Whatsapp Communicate With Us
- Register a Callback for Websocket Events
Connecting Account
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 in the SocketConfig type alias (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 the BrowsersMap type alias
import makeWASocket from 'nishiki-bail'
const sock = makeWASocket({
// can provide additional config here
browser: Browsers.ubuntu('My App'),
printQRInTerminal: true
})
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
import makeWASocket from 'nishiki-bail'
const sock = makeWASocket({
// can provide additional config here
printQRInTerminal: false //need to be false
})
if (!sock.authState.creds.registered) {
const number = 'XXXXXXXXXXX'
const code = await sock.requestPairingCode(number)
console.log(code)
}
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:
const sock = makeWASocket({
...otherOpts,
// can use Windows, Ubuntu here too
browser: Browsers.macOS('Desktop'),
syncFullHistory: true
})
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:
const groupCache = new NodeCache({stdTTL: 5 * 60, useClones: false})
const sock = makeWASocket({
cachedGroupMetadata: async (jid) => groupCache.get(jid)
})
sock.ev.on('groups.update', async ([event]) => {
const metadata = await sock.groupMetadata(event.id)
groupCache.set(event.id, metadata)
})
sock.ev.on('group-participants.update', async (event) => {
const metadata = await sock.groupMetadata(event.id)
groupCache.set(event.id, metadata)
})
Improve Retry System & Decrypt Poll Votes
Receive Notifications in Whatsapp App
Saving & Restoring Sessions
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:
import makeWASocket, { useMultiFileAuthState } from 'nishiki-bail'
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const sock = makeWASocket({ auth: state })
// this will be called as soon as the credentials are updated
sock.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 in the BaileysEventMap type alias, it's important you see all events
You can listen to these events like this:
const sock = makeWASocket()
sock.ev.on('messages.upsert', ({ messages }) => {
console.log('got messages', messages)
})
Example to Start
[!NOTE]
This example includes basic auth storage too
[!NOTE]
For reliable serialization of the authentication state, especially when storing as JSON, always use the BufferJSON utility.
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from 'nishiki-bail'
import { Boom } from '@hapi/boom'
async function connectToWhatsApp () {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
const sock = makeWASocket({
// can provide additional config here
auth: state,
printQRInTerminal: true
})
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if(connection === 'close') {
const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
// reconnect if not logged out
if(shouldReconnect) {
connectToWhatsApp()
}
} else if(connection === 'open') {
console.log('opened connection')
}
})
sock.ev.on('messages.upsert', event => {
for (const m of event.messages) {
console.log(JSON.stringify(m, undefined, 2))
console.log('replying to', m.key.remoteJid)
await sock.sendMessage(m.key.remoteJid!, { text: 'Hello Word' })
}
})
// to storage creds (session info) when it updates
sock.ev.on('creds.update', saveCreds)
}
// run in main file
connectToWhatsApp()
[!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
- That's a simple example
sock.ev.on('messages.update', event => {
for(const { key, update } of event) {
if(update.pollUpdates) {
const pollCreation = await getMessage(key)
if(pollCreation) {
console.log(
'got poll update, aggregation: ',
getAggregateVotesInPollMessage({
message: pollCreation,
pollUpdates: update.pollUpdates,
})
)
}
}
}
})
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:
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
const jid: string
const content: AnyMessageContent
const options: MiscMessageGenerationOptions
sock.sendMessage(jid, content, options)
Non-Media Messages
Text Message
await sock.sendMessage(jid, { text: 'hello word' })
Quote Message (works with all types)
await sock.sendMessage(jid, { text: 'hello word' }, { quoted: message })
Mention User (works with most types)
- @number is to mention in text, it's optional
await sock.sendMessage(
jid,
{
text: '@12345678901',
mentions: ['12345678901@s.whatsapp.net']
}
)
Forward Messages
- You need to have message object, can be retrieved from store or use a message object
const msg = getMessageFromStore() // implement this on your end
await sock.sendMessage(jid, { forward: msg }) // WA forward the message!
Location Message
await sock.sendMessage(
jid,
{
location: {
degreesLatitude: 24.121231,
degreesLongitude: 55.1121221
}
}
)
Contact Message
const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
+ 'VERSION:3.0\n'
+ 'FN:Jeff Singh\n' // full name
+ 'ORG:Ashoka Uni;\n' // the organization of the contact
+ 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
+ 'END:VCARD'
await sock.sendMessage(
id,
{
contacts: {
displayName: 'Jeff',
contacts: [{ vcard }]
}
}
)
Reaction Message
- You need to pass the key of message, you can retrieve from store or use a key object
await sock.sendMessage(
jid,
{
react: {
text: '💖', // use an empty string to remove the reaction
key: message.key
}
}
)
Pin Message
| Time |
Seconds |
| 24h |
86.400 |
| 7d |
604.800 |
| 30d |
2.592.000 |
await sock.sendMessage(
jid,
{
pin: {
type: 1, // 0 to remove
time: 86400
key: message.key
}
}
)
Poll Message
await sock.sendMessage(
jid,
{
poll: {
name: 'My Poll',
values: ['Option 1', 'Option 2', ...],
selectableCount: 1,
toAnnouncementGroup: false // or true
}
}
)
Sending Messages with Link Previews
- By default, wa does not have link generation when sent from the web
- Baileys has a function to generate the content for these link previews
- To enable this function's usage, add
link-preview-js as a dependency to your project with yarn add link-preview-js
- Send a link:
await sock.sendMessage(
jid,
{
text: '666'
}
)
Media Messages
Sending media (video, stickers, images) is easier & more efficient than ever.
[!NOTE]
In media messages, you can pass { stream: Stream } or { url: Url } or Buffer directly, you can see more in the WAMediaUpload type alias
- When specifying a media url, Baileys never loads the entire buffer into memory; it even encrypts the media as a readable stream.
[!TIP]
It's recommended to use Stream or Url to save memory
Gif Message
- Whatsapp doesn't support
.gif files, that's why we send gifs as common .mp4 video with gifPlayback flag