TS 中文文档 TS 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • 入门教程

    • TypeScript 手册
    • 基础知识
    • 日常类型
    • 类型缩小
    • 更多关于函数
    • 对象类型
    • 从类型创建类型
    • 泛型
    • Keyof 类型运算符
    • Typeof 类型运算符
    • 索引访问类型
    • 条件类型
    • 映射类型
    • 模板字面类型
    • 类
    • 模块
  • 参考手册

  • 项目配置

Baileys - Typescript/Javascript WhatsApp Web API


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 gigof 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 goimplementation.

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:

cd path/to/Baileys
yarn
yarn example

Install


Use the stable version:

  1. ``` sh
  2. temporarily unavailable

  3. ```

Use the edge version (no guarantee of stability, but latest fixes + features)

  1. ``` sh
  2. yarn add github:WhiskeySockets/Baileys

  3. ```

Then import your code using:

  1. ``` ts
  2. import makeWASocket from '@adiwajshing/baileys'
  3. ```

Unit Tests


TODO

Connecting


  1. ``` ts
  2. import makeWASocket, { DisconnectReason } from '@adiwajshing/baileys'
  3. import { Boom } from '@hapi/boom'

  4. async function connectToWhatsApp () {
  5.     const sock = makeWASocket({
  6.         // can provide additional config here
  7.         printQRInTerminal: true
  8.     })
  9.     sock.ev.on('connection.update', (update) => {
  10.         const { connection, lastDisconnect } = update
  11.         if(connection === 'close') {
  12.             const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
  13.             console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
  14.             // reconnect if not logged out
  15.             if(shouldReconnect) {
  16.                 connectToWhatsApp()
  17.             }
  18.         } else if(connection === 'open') {
  19.             console.log('opened connection')
  20.         }
  21.     })
  22.     sock.ev.on('messages.upsert', m => {
  23.         console.log(JSON.stringify(m, undefined, 2))

  24.         console.log('replying to', m.messages[0].key.remoteJid)
  25.         await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
  26.     })
  27. }
  28. // run in main file
  29. connectToWhatsApp()
  30. ```

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.

Configuring the Connection


You can configure the connection by passing a SocketConfig object.

The entire SocketConfig structure is mentioned here with default values:

  1. ``` ts
  2. type SocketConfig = {
  3.     /** the WS url to connect to WA */
  4.     waWebSocketUrl: string | URL
  5.     /** Fails the connection if the socket times out in this interval */
  6. connectTimeoutMs: number
  7.     /** Default timeout for queries, undefined for no timeout */
  8.     defaultQueryTimeoutMs: number | undefined
  9.     /** ping-pong interval for WS connection */
  10.     keepAliveIntervalMs: number
  11.     /** proxy agent */
  12. agent?: Agent
  13.     /** pino logger */
  14. logger: Logger
  15.     /** version to connect with */
  16.     version: WAVersion
  17.     /** override browser config */
  18. browser: WABrowserDescription
  19. /** agent used for fetch requests -- uploading/downloading media */
  20. fetchAgent?: Agent
  21.     /** should the QR be printed in the terminal */
  22.     printQRInTerminal: boolean
  23.     /** should events be emitted for actions done by this socket connection */
  24.     emitOwnEvents: boolean
  25.     /** provide a cache to store media, so does not have to be re-uploaded */
  26.     mediaCache?: NodeCache
  27.     /** custom upload hosts to upload media to */
  28.     customUploadHosts: MediaConnInfo['hosts']
  29.     /** time to wait between sending new retry requests */
  30.     retryRequestDelayMs: number
  31.     /** time to wait for the generation of the next QR in ms */
  32.     qrTimeout?: number;
  33.     /** provide an auth state object to maintain the auth state */
  34.     auth: AuthenticationState
  35.     /** manage history processing with this control; by default will sync up everything */
  36.     shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
  37.     /** transaction capability options for SignalKeyStore */
  38.     transactionOpts: TransactionCapabilityOptions
  39.     /** provide a cache to store a user's device list */
  40.     userDevicesCache?: NodeCache
  41.     /** marks the client as online whenever the socket successfully connects */
  42.     markOnlineOnConnect: boolean
  43.     /**
  44.      * map to store the retry counts for failed messages;
  45.      * used to determine whether to retry a message or not */
  46.     msgRetryCounterMap?: MessageRetryMap
  47.     /** width for link preview images */
  48.     linkPreviewImageThumbnailWidth: number
  49.     /** Should Baileys ask the phone for full history, will be received async */
  50.     syncFullHistory: boolean
  51.     /** Should baileys fire init queries automatically, default true */
  52.     fireInitQueries: boolean
  53.     /**
  54.      * generate a high quality link preview,
  55.      * entails uploading the jpegThumbnail to WA
  56.      * */
  57.     generateHighQualityLinkPreview: boolean

  58.     /** options for axios */
  59.     options: AxiosRequestConfig<any>
  60.     /**
  61.      * fetch a message from your store
  62.      * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
  63.      * */
  64.     getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
  65. }
  66. ```

Emulating the Desktop app instead of the web


Baileys, by default, emulates a chrome web session
If you'd like to emulate a desktop connection (and receive more message history), add this to your Socket config:
  1. ``` ts
  2. const conn = makeWASocket({
  3.     ...otherOpts,
  4.     // can use Windows, Ubuntu here too
  5.     browser: Browsers.macOS('Desktop'),
  6.     syncFullHistory: true
  7. })
  8. ```

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:

  1. ``` ts
  2. import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@adiwajshing/baileys'
  3. import * as fs from 'fs'

  4. // utility function to help save the auth state in a single folder
  5. // 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
  6. const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
  7. // will use the given state to connect
  8. // so if valid credentials are available -- it'll connect without QR
  9. const conn = makeWASocket({ auth: state })
  10. // this will be called as soon as the credentials are updated
  11. conn.ev.on ('creds.update', saveCreds)
  12. ```

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:

  1. ``` ts
  2. type ConnectionState = {
  3. /** connection is now open, connecting or closed */
  4. connection: WAConnectionState
  5. /** the error that caused the connection to close */
  6. lastDisconnect?: {
  7.   error: Error
  8.   date: Date
  9. }
  10. /** is this a new login */
  11. isNewLogin?: boolean
  12. /** the current QR code */
  13. qr?: string
  14. /** has the device received all pending notifications while it was offline */
  15. receivedPendingNotifications?: boolean
  16. }
  17. ```

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:

  1. ``` ts
  2. export type BaileysEventMap = {
  3.     /** connection state has been updated -- WS closed, opened, connecting etc. */
  4. 'connection.update': Partial<ConnectionState>
  5.     /** credentials updated -- some metadata, keys or something */
  6.     'creds.update': Partial<AuthenticationCreds>
  7.     /** history sync, everything is reverse chronologically sorted */
  8.     'messaging-history.set': {
  9.         chats: Chat[]
  10.         contacts: Contact[]
  11.         messages: WAMessage[]
  12.         isLatest: boolean
  13.     }
  14.     /** upsert chats */
  15.     'chats.upsert': Chat[]
  16.     /** update the given chats */
  17.     'chats.update': Partial<Chat>[]
  18.     /** delete chats with given ID */
  19.     'chats.delete': string[]
  20.     /** presence of contact in a chat updated */
  21.     'presence.update': { id: string, presences: { [participant: string]: PresenceData } }

  22.     'contacts.upsert': Contact[]
  23.     'contacts.update': Partial<Contact>[]

  24.     'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
  25.     'messages.update': WAMessageUpdate[]
  26.     'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
  27.     /**
  28.      * add/update the given messages. If they were received while the connection was online,
  29.      * the update will have type: "notify"
  30.      * */
  31.     'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
  32.     /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
  33.     'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]

  34.     'message-receipt.update': MessageUserReceiptUpdate[]

  35.     'groups.upsert': GroupMetadata[]
  36.     'groups.update': Partial<GroupMetadata>[]
  37.     /** apply an action to participants in a group */
  38.     'group-participants.update': { id: string, participants: string[], action: ParticipantAction }

  39.     'blocklist.set': { blocklist: string[] }
  40.     'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
  41.     /** Receive an update on a call, including when the call was received, rejected, accepted */
  42.     'call': WACallEvent[]
  43. }
  44. ```

You can listen to these events like this:

  1. ``` ts
  2. const sock = makeWASocket()
  3. sock.ev.on('messages.upsert', ({ messages }) => {
  4.     console.log('got messages', messages)
  5. })
  6. ```

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.

It can be used as follows:

  1. ``` ts
  2. import makeWASocket, { makeInMemoryStore } from '@adiwajshing/baileys'
  3. // the store maintains the data of the WA connection in memory
  4. // can be written out to a file & read from it
  5. const store = makeInMemoryStore({ })
  6. // can be read from a file
  7. store.readFromFile('./baileys_store.json')
  8. // saves the state to a file every 10s
  9. setInterval(() => {
  10.     store.writeToFile('./baileys_store.json')
  11. }, 10_000)

  12. const sock = makeWASocket({ })
  13. // will listen from this socket
  14. // the store can listen from a new socket once the current socket outlives its lifetime
  15. store.bind(sock.ev)

  16. sock.ev.on('chats.set', () => {
  17.     // can use "store.chats" however you want, even after the socket dies out
  18.     // "chats" => a KeyedDB instance
  19.     console.log('got chats', store.chats.all())
  20. })

  21. sock.ev.on('contacts.set', () => {
  22.     console.log('got contacts', Object.values(store.contacts))
  23. })
  24. ```

The store also provides some simple functions such as loadMessages that utilize the store to speed up data retrieval.

Note:I highly recommend building your own data store especially for MD connections, as storing someone's entire chat history in memory is a terrible waste of RAM.

Sending Messages


Send all types of messages with a single function:

Non-Media Messages


  1. ``` ts
  2. import { MessageType, MessageOptions, Mimetype } from '@adiwajshing/baileys'

  3. const id = 'abcd@s.whatsapp.net' // the WhatsApp ID
  4. // send a simple text!
  5. const sentMsg  = await sock.sendMessage(id, { text: 'oh hello there' })
  6. // send a reply messagge
  7. const sentMsg  = await sock.sendMessage(id, { text: 'oh hello there' }, { quoted: message })
  8. // send a mentions message
  9. const sentMsg  = await sock.sendMessage(id, { text: '@12345678901', mentions: ['12345678901@s.whatsapp.net'] })
  10. // send a location!
  11. const sentMsg  = await sock.sendMessage(
  12.     id,
  13.     { location: { degreesLatitude: 24.121231, degreesLongitude: 55.1121221 } }
  14. )
  15. // send a contact!
  16. const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
  17.             + 'VERSION:3.0\n'
  18.             + 'FN:Jeff Singh\n' // full name
  19.             + 'ORG:Ashoka Uni;\n' // the organization of the contact
  20.             + 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
  21.             + 'END:VCARD'
  22. const sentMsg  = await sock.sendMessage(
  23.     id,
  24.     {
  25.         contacts: {
  26.             displayName: 'Jeff',
  27.             contacts: [{ vcard }]
  28.         }
  29.     }
  30. )

  31. // send a buttons message!
  32. const buttons = [
  33.   {buttonId: 'id1', buttonText: {displayText: 'Button 1'}, type: 1},
  34.   {buttonId: 'id2', buttonText: {displayText: 'Button 2'}, type: 1},
  35.   {buttonId: 'id3', buttonText: {displayText: 'Button 3'}, type: 1}
  36. ]

  37. const buttonMessage = {
  38.     text: "Hi it's button message",
  39.     footer: 'Hello World',
  40.     buttons: buttons,
  41.     headerType: 1
  42. }

  43. const sendMsg = await sock.sendMessage(id, buttonMessage)

  44. //send a template message!
  45. const templateButtons = [
  46.     {index: 1, urlButton: {displayText: '⭐ Star Baileys on GitHub!', url: 'https://github.com/adiwajshing/Baileys'}},
  47.     {index: 2, callButton: {displayText: 'Call me!', phoneNumber: '+1 (234) 5678-901'}},
  48.     {index: 3, quickReplyButton: {displayText: 'This is a reply, just like normal buttons!', id: 'id-like-buttons-message'}},
  49. ]

  50. const templateMessage = {
  51.     text: "Hi it's a template message",
  52.     footer: 'Hello World',
  53.     templateButtons: templateButtons
  54. }

  55. const sendMsg = await sock.sendMessage(id, templateMessage)

  56. // send a list message!
  57. const sections = [
  58.     {
  59. title: "Section 1",
  60. rows: [
  61.      {title: "Option 1", rowId: "option1"},
  62.      {title: "Option 2", rowId: "option2", description: "This is a description"}
  63. ]
  64.     },
  65.    {
  66. title: "Section 2",
  67. ro
Last Updated: 2023-09-03 17:10:52