adiwajshing/baileys tutorial


npm install3. On a WAMessage, the messageID can be accessed using messageID = message.key.id. /* (for media messages) specify the type of media (optional for all media types except documents), import {Mimetype} from '@adiwajshing/baileys', // (for media messages) file name for the media, /* will send audio messages as voice notes, if set to true */, // will detect links & generate a link preview automatically (default true). 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. Also, this repo is now licenced under GPL 3 since it uses libsignal-node, /** provide an auth state object to maintain the auth state */, /** Fails the connection if the connection times out in this time interval or no data is received */, /** Default timeout for queries, undefined for no timeout */, /** ping-pong interval for WS connection */, /** agent used for fetch requests -- uploading/downloading media */, /** should the QR be printed in the terminal */, * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried, // 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, // so if valid credentials are available -- it'll connect without QR, // this will be called as soon as the credentials are updated, /** connection is now open, connecting or closed */, /** the error that caused the connection to close */, /** has the device received all pending notifications while it was offline */, /** connection state has been updated -- WS closed, opened, connecting etc. on November 3, 2021, There are no reviews yet. Hence, instead of having to fork the project & re-write the internals, you can simply write extensions in your own code. (Use chats.get(jid) with KeyedDB). The presence expires after about 10 seconds. Baileys also comes with a unit test suite. You can specify a buffer, a local url or even a remote url. WA uses an encrypted form of communication to send chat/app updates. Thank you to @pokearaujo for writing his observations on the workings of WhatsApp Multi-Device. If you're interested in building a WhatsApp bot, you may wanna check out WhatsAppInfoBot and an actual bot built with it, Messcat. ``` ts const id = '1234-123@g.us'const messageID = 'AHASHH123123AHGA' // id of the message you want to read, await conn.chatRead (id) // mark all messages in chat as read (equivalent of opening a chat in WA)await conn.chatRead (id, 'unread') // mark the chat as unread```. Baileys is type-safe, extensible and simple to use. This is done primarily for simplicity & more testability, The Baileys event emitter will emit all events and be used to generate a source of truth for the connected user's account. Baileys now supports the latest multi-device beta. To run the example script, download or clone the repo and then type the following in terminal: Use the edge version (no guarantee of stability, but latest fixes + features). Not running Selenium or Chromimum saves you like half a gig of ram :/. MessageType.video, { mimetype: Mimetype.gif, caption: "hello!" Baileys does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a WebSocket.

* add/update the given messages. // allow everyone to modify the group's settings -- like display picture etc. I felt the entire Baileys object became too bloated as it supported too many configurations. Thumbnails for videos can also be generated automatically, though, you need to have, To check if a given ID is on WhatsAppNote: this method falls back to using, To query chat history on a group or with someone, To get the display picture of some person/group, To change your display picture or a group's, To get someone's presence (if they're typing, online), To join the group using the invitation code, To revokes the current invite link of a group. This is returned by the pin & mute functions. This data has the following structure: Note: this also offers any updates to the QR. Not running Selenium or Chromimum saves you like half a gig of ram :/. The store also provides some simple functions such as loadMessages that utilize the store to speed up data retrieval. When specifying a media url, Baileys never loads the entire buffer into memory; it even encrypts the media as a readable stream. Do note, the conn.chats object is a KeyedDB. The message ID is the unique identifier of the message that you are marking as read. Of course, replace xyz with an actual ID. Do not spam people with this. /* (for location & media messages) has to be a base 64 encoded JPEG if you want to send a custom thumb. If you're interested in building a WhatsApp bot, you may wanna check out WhatsAppInfoBot and an actual bot built with it, Messcat. Baileys is written, keeping in mind, that you may require other custom functionality. You should ideally take this on your own, simply because your state in MD is its own source of truth & there is no one-size-fits-all way to handle the storage for this. This is done primarily for simplicity & more testability, The Baileys event emitter will emit all events and be used to generate a source of truth for the connected user's account. For example: ``` tsimport { WAConnection, ProxyAgent } from '@adiwajshing/baileys', const conn = new WAConnecion ()conn.connectOptions.agent = ProxyAgent ('http://some-host:1234'), await conn.connect ()console.log ("oh hello " + conn.user.name + "! * add/update the given messages. Access the event emitter using (. Baileys now uses the EventEmitter syntax for events. : Agent = undefined, /** agent used for fetch requests -- uploading/downloading media */ fetchAgent? You will require a phone with WhatsApp to test, and a second WhatsApp number to send messages to.Set the phone number you can randomly send messages to in a .env file with TEST_JID=1234@s.whatsapp.net, ``` tsimport { WAConnection } from '@adiwajshing/baileys', async function connectToWhatsApp () { const conn = new WAConnection() // called when WA sends chats // this can take up to a few minutes if you have thousands of chats! The API for the legacy and MD versions has been made as similar as possible so ya'll can switch between them seamlessly. Baileys now fires the connection.update event to let you know something has updated in the connection. This lets the person/group with id know whether you're online, offline, typing etc. //send a template message with an image **attached**! Sending media (video, stickers, images) is easier & more efficient than ever. where presence can be one of the following: tsexport enum Presence { available = 'available', // "online" composing = 'composing', // "typing" recording = 'recording', // "recording" paused = 'paused' // stopped typing, back to "online"}```. The store listens for chat updates, new messages, message updates etc. : boolean}) => void): this/** when all initial messages are received from WA */on (event: 'initial-data-received', listener: (update: {chatsWithMissingMessages: { jid: string, count: number }[] }) => void): this/** when multiple chats are updated (new message, updated message, deleted, pinned, etc) */on (event: 'chats-update', listener: (chats: WAChatUpdate[]) => void): this/** when a chat is updated (new message, updated message, read message, deleted, pinned, presence updated etc) */on (event: 'chat-update', listener: (chat: WAChatUpdate) => void): this/** when participants are added to a group */on (event: 'group-participants-update', listener: (update: {jid: string, participants: string[], actor? * By default 'chat' -- which follows the setting of the chat */, // the ID of the user that sent the message (undefined for individual chats), // can pass multiple keys to read multiple messages as well, // get what type of message it is -- text, image, video, // pass this so that baileys can request a reupload of media, // sends a message to delete the given message, // this is 1 week in seconds -- how long you want messages to appear for, // the presence update is fetched and called here, // id & people to add to the group (will throw error if it fails), // replace this parameter with "remove", "demote" or "promote". Not doing so will prevent your messages from reaching the recipient & cause other unexpected consequences. This is also available in the WAChat objects of the respective chats, as a mute or pin property. You can configure the connection via the connectOptions property. ', "Required, text on the button to view the list", // use an empty string to remove the reaction, 'Hi, this was sent using https://github.com/adiwajshing/baileys'. Baileys now fires the connection.update event to let you know something has updated in the connection. // allow everyone to modify the group's settings -- like display picture etc. You connected via a proxy")```, The entire WAConnectOptions struct is mentioned here with default values:tsconn.connectOptions = { /** fails the connection if no data is received for X seconds */ maxIdleTimeMs? Not running Selenium or Chromimum saves you like half a gig of ram :/. To run the example script, download or clone the repo and then type the following in a terminal: Use the edge version (no guarantee of stability, but latest fixes + features). Use at your own discretion. ts/** when the connection has opened successfully */on (event: 'open', listener: (result: WAOpenResult) => void): this/** when the connection is opening */on (event: 'connecting', listener: () => void): this/** when the connection has closed */on (event: 'close', listener: (err: {reason? The message ID is the unique identifier of the message that you are marking as read. // some random context info (can show a forwarded message with this too), // optional, if you want to manually set the timestamp of the message, // (for media messages) the caption to send with the media (cannot be sent with stickers though). The message ID is the unique identifier of the message that you are marking as read. or set to null if you don't want to send a thumbnail. When specifying a media url, Baileys never loads the entire buffer into memory, it even encrypts the media as a readable stream. They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code. 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! Hence, you can register a callback for an event using the following:tsconn.on (`CB:action,,battery`, json => { const batteryLevelStr = json[2][0][1].value const batterylevel = parseInt (batteryLevelStr) console.log ("battery level: " + batterylevel + "%")})This callback will be fired any time a message is received matching the following criteria:message [0] === "action" && message [1] === null && message[2][0][0] === "battery", Functionality to keep track of the pushname changes on your phone.You enable logging and you'll see an unhandled message about your pushanme pop up like this: s24, ["Conn",{"pushname":"adiwajshing"}]. /* (for media messages) specify the type of media (optional for all media types except documents), import {Mimetype} from '@adiwajshing/baileys', // (for media messages) file name for the media, /* will send audio messages as voice notes, if set to true */. If they were received while the connection was online, /** message was reacted to. This can be accomplished using: Note: deleting for oneself is supported via chatModify (next section).

Lightweight full-featured WhatsApp Web + Multi-Device API, Baileys does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a WebSocket. // send a buttons message with image header! This will enable you to see all sorts of messages WhatsApp sends in the console. {"level":10,"fromMe":false,"frame":{"tag":"ib","attrs":{"from":"@s.whatsapp.net"},"content":[{"tag":"edge_routing","attrs":{},"content":[{"tag":"routing_info","attrs":{},"content":{"type":"Buffer","data":[8,2,8,5]}}]}]},"msg":"communication"}. The API for the legacy and MD versions has been made as similar as possible so you can switch between them seamlessly. This also serves as a good demonstration of how to use the Baileys event emitter to construct a source of truth.