ovl_wa_baileys v1.0.1
Baileys - Typescript/Javascript WhatsApp Web API
Important Note
This library was originally a project for CS-2362 at Ashoka University and is in no way affiliated with or endorsed by WhatsApp. Use at your own discretion. Do not spam people with this. We discourage any stalkerware, bulk or automated messaging usage.
Liability and License Notice
Baileys and its maintainers cannot be held liable for misuse of this application, as stated in the MIT license. 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.
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 Chromimum 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.
Please Read
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:
1. cd path/to/Baileys
2. yarn
3. 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'
Unit Tests
TODO
Connecting multi device (recommended)
WhatsApp provides a multi-device API that allows Baileys to be authenticated as a second WhatsApp client by scanning a QR code with WhatsApp on your phone.
import makeWASocket, { DisconnectReason } from '@whiskeysockets/baileys'
import { Boom } from '@hapi/boom'
async function connectToWhatsApp () {
const sock = makeWASocket({
// can provide additional config here
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', m => {
console.log(JSON.stringify(m, undefined, 2))
console.log('replying to', m.messages[0].key.remoteJid)
await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
})
}
// run in main file
connectToWhatsApp()
```
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!
**Note:** install `qrcode-terminal` using `yarn add qrcode-terminal` to auto-print the QR to the terminal.
**Note:** the code to support the legacy version of WA Web (pre multi-device) has been removed in v5. Only the standard multi-device connection is now supported. This is done as WA seems to have completely dropped support for the legacy version.
## Connecting native mobile api
Baileys also supports the native mobile API, which allows users to authenticate as a standalone WhatsApp client using their phone number.
Run the [example](Example/example.ts) file with ``--mobile`` cli flag to use the native mobile API.
## Configuring the Connection
You can configure the connection by passing a `SocketConfig` object.
The entire `SocketConfig` structure is mentioned here with default values:
``` ts
type SocketConfig = {
/** the WS url to connect to WA */
waWebSocketUrl: string | URL
/** Fails the connection if the socket times out in this interval */
connectTimeoutMs: number
/** Default timeout for queries, undefined for no timeout */
defaultQueryTimeoutMs: number | undefined
/** ping-pong interval for WS connection */
keepAliveIntervalMs: number
/** proxy agent */
agent?: Agent
/** pino logger */
logger: Logger
/** version to connect with */
version: WAVersion
/** override browser config */
browser: WABrowserDescription
/** agent used for fetch requests -- uploading/downloading media */
fetchAgent?: Agent
/** should the QR be printed in the terminal */
printQRInTerminal: boolean
/** should events be emitted for actions done by this socket connection */
emitOwnEvents: boolean
/** provide a cache to store media, so does not have to be re-uploaded */
mediaCache?: NodeCache
/** custom upload hosts to upload media to */
customUploadHosts: MediaConnInfo['hosts']
/** time to wait between sending new retry requests */
retryRequestDelayMs: number
/** max msg retry count */
maxMsgRetryCount: number
/** time to wait for the generation of the next QR in ms */
qrTimeout?: number;
/** provide an auth state object to maintain the auth state */
auth: AuthenticationState
/** manage history processing with this control; by default will sync up everything */
shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
/** transaction capability options for SignalKeyStore */
transactionOpts: TransactionCapabilityOptions
/** provide a cache to store a user's device list */
userDevicesCache?: NodeCache
/** marks the client as online whenever the socket successfully connects */
markOnlineOnConnect: boolean
/**
* map to store the retry counts for failed messages;
* used to determine whether to retry a message or not */
msgRetryCounterMap?: MessageRetryMap
/** width for link preview images */
linkPreviewImageThumbnailWidth: number
/** Should Baileys ask the phone for full history, will be received async */
syncFullHistory: boolean
/** Should baileys fire init queries automatically, default true */
fireInitQueries: boolean
/**
* generate a high quality link preview,
* entails uploading the jpegThumbnail to WA
* */
generateHighQualityLinkPreview: boolean
/** options for axios */
options: AxiosRequestConfig<any>
/**
* fetch a message from your store
* implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
* */
getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
}
```
### Emulating the Desktop app instead of the web
1. Baileys, by default, emulates a chrome web session
2. If you'd like to emulate a desktop connection (and receive more message history), add this to your Socket config:
``` ts
const conn = makeWASocket({
...otherOpts,
// can use Windows, Ubuntu here too
browser: Browsers.macOS('Desktop'),
syncFullHistory: true
})
```
## 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:
``` ts
import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@whiskeysockets/baileys'
import * as fs from 'fs'
// 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
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 conn = makeWASocket({ auth: state })
// this will be called as soon as the credentials are updated
conn.ev.on ('creds.update', saveCreds)
```
**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.
## Listening to Connection Updates
Baileys now fires the `connection.update` event to let you know something has updated in the connection. This data has the following structure:
``` ts
type ConnectionState = {
/** connection is now open, connecting or closed */
connection: WAConnectionState
/** the error that caused the connection to close */
lastDisconnect?: {
error: Error
date: Date
}
/** is this a new login */
isNewLogin?: boolean
/** the current QR code */
qr?: string
/** has the device received all pending notifications while it was offline */
receivedPendingNotifications?: boolean
}
```
**Note:** this also offers any updates to the QR
## 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.
The events are typed as mentioned here:
``` ts
export type BaileysEventMap = {
/** connection state has been updated -- WS closed, opened, connecting etc. */
'connection.update': Partial<ConnectionState>
/** credentials updated -- some metadata, keys or something */
'creds.update': Partial<AuthenticationCreds>