phoenix-baileys-v2
v2.2.16
Published
A WebSockets library for interacting with WhatsApp Web
Maintainers
Readme
Baileys - Javascript WhatsApp Web API
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.
Install
Use the stable version:
yarn add phoenix-baileys-v2Use the edge version (no guarantee of stability, but latest fixes + features)
yarn add github:Exiqonbotz/phoenix-baileys-v2Then import your code using:
import makeWASocket from 'phoenix-baileys-v2'What's New (Usernames)
Full implementation of the WhatsApp username protocol, reverse-engineered from WhatsApp 2.26.17.2. See USERNAME.md for full documentation and setup instructions.
checkUsername(username, includeSuggestions?)— check whether a@usernameis available before setting it. Returns{ available, suggestions, rejectionReasons, suggestionsEligible }. Confirmed fromC1568872p.A01()andC164057Wg.java(xwa2_username_checkdata path).setUsername(username, options?)— set your own username viaw:mexUsernameSet. Options:source(USER_INPUT/SUGGESTION/FB/IG),sessionId,pin.deleteUsername()— unset your username. Sendsusername: nullwhich triggers the server-side delete path (confirmedC1568872p.java:24).getMyUsername()— fetch your current username viaw:mexUsernameGet.setUsernamePin(pin)— protect your username with a PIN, or delete it by passingnull. Usesw:mexoperationUsernamePinSet(confirmedMexUsernamePinProtocolApi.java).findUserByUsername(username, pin?)— look up a contact's JID by their@usernamevia USync. Supports PIN-protected usernames. Returns{ jid, contact }.fetchContactUsernames(...jids)— batch-fetch the username of multiple contacts by JID via USyncUsernameProtocol.USERNAME_QUERY_IDS— object holding thew:mexquery IDs (must be filled in from a live session capture — see USERNAME.md).USERNAME_CHECK_RESULT,USERNAME_SOURCE— enums confirmed from APK (EnumC141106Vn,C1568872p.java).
What's New (Interop — BirdyChat & Haiket)
Full support for the WhatsApp DMA Interoperability Protocol (w:interop). Allows messaging with users on third-party platforms directly from a WhatsApp account. See INTEROP.md for full documentation.
- Automatic init on connect — integrators are fetched, TOS accepted, and opt-in sent in parallel with other init queries. No manual setup required.
fetchIntegrators()— returns all available integrators withid,name,status(active|onboarding|removed),identifierType(email|pn|username),optedIn, andfeatures.resolveInteropUser(externalId, integratorId)— look up a single user by email (BirdyChat) or phone number (Haiket). Returns their interop JID (12-…@interop) or an error object.resolveInteropUsers([...])— batch lookup of up to 256 users in a single IQ request.optInIntegrators(ids)/optOutIntegrators(ids)— opt in or out of specific integrators.getReachabilitySettings()/setReachabilitySettings(users, enabled)— interop presence/reachability subscription mechanism (replaces XMPP presence for interop contacts).blockInteropUser(jid)/unblockInteropUser(jid)— block/unblock via the dedicatedw:interopblocklist (separate from the regular WA blocklist).reportInteropSpam(jid)— report an interop contact as spam.trustInteropContact(jid)— mark an interop JID astrusted_contactin privacy tokens (called automatically after the first send in WA).isInteropUser(jid)— new JID utility exported fromWABinary, returnstruefor@interopJIDs.- Incoming message support —
decodeMessageNodenow correctly handles messages received from interop JIDs (@interop) aschattype, routed through the normalmessages.upsertevent. profilePictureUrl— works out of the box for interop JIDs (no TC token attached, matching the WA protocol).- Constants
INTEGRATOR_BIRDYCHAT(12) andINTEGRATOR_HAIKET(13) exported directly from the socket.
What's New (Identity + Meta AI + History Sync + New Message Types)
- TC Token (Privacy Token) system — full upstream parity
- Tokens are now stored under LID instead of PN where applicable (AB prop 14303).
- Expiry is enforced using a rolling 28-day / 4-bucket window; expired tokens are cleared on send.
- Fire-and-forget token issuance after every outgoing 1:1 message, with in-flight deduplication via
inFlightTcTokenIssuance. - Token re-issuance triggers automatically when a peer's device identity changes (
reissueTcTokenAfterIdentityChange). - Privacy token notifications (
privacy_token) are now processed viastoreTcTokensFromIqResultwithsender_lidsupport. - TC tokens from history sync are stored and indexed (
storeTcTokensFromHistorySync). - A persistent
__indexkey tracks all storage JIDs for daily cross-session pruning (pruneExpiredTcTokens). - Profile picture IQs and presence subscribes are gated by server-assigned AB props (
serverProps.profilePicPrivacyToken,serverProps.privacyTokenOn1to1). - New exports:
readTcTokenIndex,buildMergedTcTokenIndexWrite,isTcTokenExpired,shouldSendNewTcToken,resolveTcTokenJid,resolveIssuanceJid,storeTcTokensFromIqResult,TC_TOKEN_INDEX_KEY.
- App state sync — missing-key handling (Blocked state)
- Collections blocked on a missing app state sync key are parked in
blockedCollectionsinstead of being retried indefinitely. - When the key arrives via
APP_STATE_SYNC_KEY_SHARE, blocked collections are re-synced automatically. - New utilities:
isMissingKeyError,isAppStateSyncIrrecoverable,MAX_SYNC_ATTEMPTS,ensureLTHashStateVersion(exported fromchat-utils).
- Collections blocked on a missing app state sync key are parked in
- Server AB props (
serverProps) on the socketchats.makeChatsSocketnow fetches and exposesserverPropscontaining three live AB flags:privacyTokenOn1to1(prop 10518) — whether tctoken is required on all 1:1 messagesprofilePicPrivacyToken(prop 9666) — whether profile-picture IQs require a tctokenlidTrustedTokenIssueToLid(prop 14303) — whether tokens are issued to LID or PN
- History sync completion tracking
historySyncStatustracksinitialBootstrapCompleteandrecentSyncCompletein-memory.messaging-history.statusevent fires with{ syncType, status: 'complete'|'paused', explicit }forINITIAL_BOOTSTRAPandRECENTsync types.- A 120 s paused-timeout fires a
status: 'paused'event if progress stalls mid-RECENT sync (HISTORY_SYNC_PAUSED_TIMEOUT_MS). - On reconnection with existing data (
accountSyncCounter > 0), the 20 s AwaitingInitialSync wait is skipped.
- Username support
USyncUsernameProtocol— new USync protocol for username lookups.USyncQuery.withUsernameProtocol()andUSyncUser.withUsername()/withUsernameKey()added.USyncContactProtocol.getUserElementsupportsusername,usernameKey, andlidlookups in addition to phone.- Group metadata now includes
ownerUsername,subjectOwnerUsername,descOwnerUsername, andusernameper participant. authorUsernamepropagated through group-participant events (group-participants.update,groups.update,group.join-request).participantUsernameandremoteJidUsernameexposed on message keys.usernamefield carried through history sync, sync-action, and lidContactAction contacts events.
- Server error codes
SERVER_ERROR_CODESexported fromdecode-wa-message:MissingTcToken: '463',SmaxInvalid: '479'.- ACK error handler distinguishes 463 (account restricted / missing tctoken) and 479 (stale session / SMAX_INVALID) with specific log messages and no-retry behaviour for 463.
- Identity change handler
ctx.onBeforeSessionRefresh?.(from)callback fires beforeassertSessions, enabling fire-and-forget tctoken re-issuance in parallel with the session refresh.
- Call latency
relaylatencycall status now readslatency/latency_ms/latency-msattributes and setscall.latencyMs.
- Rich AI Response Message support
- Send Meta AI-style rich responses via
richResponsewith optional syntax-highlighted code blocks. - Built-in tokenizer supports JavaScript, TypeScript, and Python.
- Uses
botForwardedMessage→richResponseMessage→unifiedResponseproto chain.
- Send Meta AI-style rich responses via
- New WA 2.3000+ message types
statusNotification— status add-yours / reshare / question-answer-reshare events.statusQuestionAnswer— user answered a status question.questionResponse— direct response to a question message.statusQuoted— quote a status with a custom type.statusStickerInteraction— react to a status with a sticker.newsletterFollowerInvite— invite a user to follow a newsletter.messageHistoryNotice— notify about message history metadata.
- JID display normalization is now built in
- Runtime prefers PN JIDs (
@s.whatsapp.net) over LID JIDs (@lid) in display/event paths when mapping data is available. - This includes message identity fields, mentions (
contextInfo.mentionedJid), quote/reply participants, and call/event payload identity fields.
- Runtime prefers PN JIDs (
- Meta AI
msmsgdecryption is now deterministic- Decoding now uses a bounded strategy pipeline for known private/group Meta AI message families.
- Broad brute-force loops were removed for better reliability and predictable behavior.
- One-time initial full history sync is supported
- With fresh auth state, full history sync can run on first successful connect.
- After completion, auth state persists it as done so reconnects do not repeat full sync automatically.
- Optional LID/PN diagnostics
- Set
LID_PN_DEBUG=1to trace LID -> PN normalization source selection.
- Set
Index
- Non-Media Messages
- Text Message
- Quote Message
- Mention User
- Forward Messages
- Location Message
- Live Location Message
- Contact Message
- Reaction Message
- Pin Message
- Keep Message
- Poll Message
- Poll Result Message
- Call Message
- Event Message
- Order Message
- Product Message
- Payment Message
- Payment Invite Message
- Admin Invite Message
- Group Invite Message
- Share Phone Number Message
- Request Phone Number Message
- Buttons Reply Message
- Buttons Message
- Buttons List Message
- Buttons Product List Message
- Buttons Cards Message
- Buttons Template Message
- Buttons Interactive Message
- Buttons Interactive Message PIX
- Buttons Interactive Message PAY
- Status Mentions Message
- Send Album Message
- Shop Message
- Collection Message
- Sticker Pack Message
- Rich AI Response Message
- Rich Composer Methods
- Status Notification Message
- Status Question Answer Message
- Question Response Message
- Status Quoted Message
- Status Sticker Interaction Message
- Newsletter Follower Invite Message
- Message History Notice
- Sending with Link Preview
- Media Messages
- Non-Media Messages
- 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
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 here (Recommended)
Starting socket with QR-CODE
[!TIP] You can customize browser name if you connect with QR-CODE, with
Browserconstant, we have some browsers config, see here
import makeWASocket from 'phoenix-baileys-v2'
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 'phoenix-baileys-v2'
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) // or await sock.requestPairingCode(number, 'CODEOTPS') custom your pairing code
console.log(code)
}Receive Full History
- Set
syncFullHistoryastrueif you want to force full history sync. - 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
})Behavior note:
- With fresh auth state, full history sync can run once on first successful connect.
- That completion is persisted in auth creds, so later reconnects/restarts with the same auth folder do not repeat full sync automatically.
- You can still explicitly force it again by setting
syncFullHistory: true.
Important Notes About Socket Config
Caching Group Metadata (Recommended)
If you use baileys for groups, we recommend you to set
cachedGroupMetadatain 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
- If you want to improve sending message, retrying when error occurs and decrypt poll votes, you need to have a store and set
getMessageconfig in socket like this:const sock = makeWASocket({ getMessage: async key => await getMessageFromStore(key) })
Receive Notifications in Whatsapp App
- If you want to receive notifications in whatsapp app, set
markOnlineOnConnecttofalseconst sock = makeWASocket({ markOnlineOnConnect: false })
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 'phoenix-baileys-v2'
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]
useMultiFileAuthStateis 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. TheuseMultiFileAuthStatefunction 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
You can listen to these events like this:
const sock = makeWASocket()
sock.ev.on('messages.upsert', ({ messages }) => {
console.log('got messages', messages)
})Built-in note: manual @lid mention rewrite handlers are no longer required for most bots.
Baileys now normalizes identity fields and mention arrays across receive/send/event paths where LID -> PN mapping data is available.
For troubleshooting, set LID_PN_DEBUG=1.
Core Events You Should Handle (Recommended)
Use this list as your production baseline.
connection.update
- When: connection state changes (
connecting,open,close) and QR updates. - Why: reconnect strategy and connection diagnostics.
- Handler:
sock.ev.on('connection.update', update => {
const { connection, lastDisconnect } = update
console.log(connection, lastDisconnect?.error)
})- Pitfall: reconnect blindly without checking logout reason.
creds.update
- When: auth credentials/keys rotate.
- Why: persistence of auth state.
- Handler:
sock.ev.on('creds.update', saveCreds)- Pitfall: not saving key updates causes delivery/decryption issues.
messages.upsert
- When: new messages arrive.
- Why: primary inbound message processing.
- Handler:
sock.ev.on('messages.upsert', event => {
for (const message of event.messages) {
// process every message
}
})- Pitfall: handling only
event.messages[0].
messages.update
- When: message status/content update arrives (poll votes, receipts, edits metadata).
- Why: keep local state in sync and decrypt poll updates.
- Handler:
sock.ev.on('messages.update', updates => {
for (const update of updates) {
// update local message state
}
})- Pitfall: skipping updates makes message state inconsistent.
messages.delete
- When: message deletion events are emitted.
- Why: remove/hide messages in local store/UI.
- Handler:
sock.ev.on('messages.delete', item => {
// delete by key from storage
})- Pitfall: leaving deleted messages in local caches.
message-receipt.update
- When: read/delivery receipts update.
- Why: accurate read/delivered indicators.
- Handler:
sock.ev.on('message-receipt.update', receipts => {
// apply receipt state
})- Pitfall: assuming only one receipt per event.
messaging-history.set
- When: history chunk is pushed (initial sync/replay).
- Why: initial backfill and reconnect recovery.
- Handler:
sock.ev.on('messaging-history.set', data => {
// merge chats/contacts/messages idempotently
})- Pitfall: non-idempotent writes causing duplicates after reconnect.
chats.upsert
- When: new chat records are added.
- Why: create chats in local store.
- Handler:
sock.ev.on('chats.upsert', chats => {
// insert new chats
})- Pitfall: assuming all chats already exist before messages.
chats.update
- When: chat metadata changes (mute/archive/unread/etc.).
- Why: keep chat state accurate.
- Handler:
sock.ev.on('chats.update', updates => {
// patch chat records
})- Pitfall: overwriting full records instead of patching.
chats.delete
- When: chats are removed.
- Why: remove chat from local state.
- Handler:
sock.ev.on('chats.delete', deletions => {
// remove chat ids
})- Pitfall: stale chat references in dependent tables.
contacts.upsert
- When: new contacts are synced.
- Why: create contact directory entries.
- Handler:
sock.ev.on('contacts.upsert', contacts => {
// insert contacts
})- Pitfall: discarding partial payload fields you need later.
contacts.update
- When: contact fields change (name/status/device flags).
- Why: keep identity/profile metadata fresh.
- Handler:
sock.ev.on('contacts.update', updates => {
// patch contacts
})- Pitfall: treating update payload as full contact object.
groups.update
- When: group properties change (subject/announce/restrict/etc.).
- Why: maintain current group metadata.
- Handler:
sock.ev.on('groups.update', updates => {
// patch group metadata cache/store
})- Pitfall: not invalidating stale group cache.
group-participants.update
- When: members join/leave/promote/demote.
- Why: maintain participant roster and roles.
- Handler:
sock.ev.on('group-participants.update', event => {
// apply participant delta by action
})- Pitfall: ignoring action type and applying wrong mutation.
call
- When: call offer/accept/reject/timeout events are emitted.
- Why: missed-call handling and call-related UX/workflows.
- Handler:
sock.ev.on('call', calls => {
for (const call of calls) {
// handle call status transitions
}
})- Pitfall: assuming only direct calls; group calls also emit call events.
Production Event Handling Checklist
- Always persist auth changes from
creds.update. - Make handlers idempotent to survive reconnect/history replay.
- Process all messages in
event.messages, not only index0. - Configure
getMessageif you rely on retry/poll decryption paths. - Cache group metadata for group-heavy bots.
Debugging Tips
- Use structured logs around event entry/exit and reconnect causes.
- Enable
LID_PN_DEBUG=1when tracking LID -> PN normalization behavior. - Log disconnect reason codes from
connection.updatefor recovery policy tuning.
Example to Start
[!NOTE] This example includes basic auth storage too
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from 'phoenix-baileys-v2'
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.upsertit's recommended to use a loop likefor (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
import pino from 'pino'
import { makeInMemoryStore, getAggregateVotesInPollMessage } from 'phoenix-baileys-v2'
const logger = pino({ timestamp: () => `,"time":"${new Date().toJSON()}"` }).child({ class: '@Exiqonbotz' })
logger.level = 'fatal'
const store = makeInMemoryStore({ logger })
async function getMessage(key) {
if (store) {
const msg = await store.loadMessage(key.remoteJid, key.id)
return msg?.message
}
return {
conversation: 'Exiqonbotz'
}
}
sock.ev.on('messages.update', async chatUpdate => {
for (const { key, update } of chatUpdate) {
if (update.pollUpdates && key.fromMe) {
const pollCreation = await getMessage(key)
if (pollCreation) {
const pollUpdate = await getAggregateVotesInPollMessage({
message: pollCreation,
pollUpdates: update.pollUpdates
})
const toCmd = pollUpdate.filter(v => v.voters.length !== 0)[0]?.name
if (toCmd == undefined) return
console.log(toCmd)
}
}
}
})Summary of Events on First Connection
- When you connect first time,
connection.updatewill 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:
import makeWASocket, { makeInMemoryStore } from 'phoenix-baileys-v2'
// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = makeInMemoryStore({})
// can be read from a file
store.readFromFile('./baileys_store.json')
// saves the state to a file every 10s
setInterval(() => {
store.writeToFile('./baileys_store.json')
}, 10_000)
const sock = makeWASocket({})
// will listen from this socket
// the store can listen from a new socket once the current socket outlives its lifetime
store.bind(sock.ev)
sock.ev.on('chats.upsert', () => {
// can use 'store.chats' however you want, even after the socket dies out
// 'chats' => a KeyedDB instance
console.log('got chats', store.chats.all())
})
sock.ev.on('contacts.upsert', () => {
console.log('got contacts', Object.values(store.contacts))
})The store also provides some simple functions such as loadMessages that utilize the store to speed up data retrieval.
Whatsapp IDs Explain
idis the WhatsApp ID, calledjidtoo, 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:
[email protected]. - For groups, it must be in the format
[email protected].
- Example for people:
- For broadcast lists, it's
[timestamp of creation]@broadcast. - For stories, the ID is
status@broadcast.
- It must be in the format
Utility Functions
getContentType, returns the content type for any messagegetDevice, returns the device from messagemakeCacheableSignalKeyStore, make auth store more fastdownloadContentFromMessage, 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
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: ['[email protected]']
})Forward Messages
const msg = getMessageFromStore() // implement this on your end
await sock.sendMessage(jid, { forward: msg, force: true or number }) // WA forward the message!Location Message
await sock.sendMessage(jid, {
location: {
degreesLatitude: 24.121231,
degreesLongitude: 55.1121221
}
})Live Location Message
await sock.sendMessage(jid, {
location: {
degreesLatitude: 24.121231,
degreesLongitude: 55.1121221
},
live: true
})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
'TELtype=CELLtype=VOICEwaid=911234567890:+91 12345 67890\n' + // WhatsApp ID + phone number
'END:VCARD'
await sock.sendMessage(id, {
contacts: {
displayName: 'Exiqonbotz',
contacts: [{ vcard }]
}
})Reaction Message
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, // 2 to remove
time: 86400,
key: Key
}
})Keep Message
await sock.sendMessage(jid, {
keep: {
key: Key,
type: 1 // or 2
}
})Poll Message
await sock.sendMessage(
jid,
{
poll: {
name: 'My Poll',
values: ['Option 1', 'Option 2', ...],
selectableCount: 1,
toAnnouncementGroup: false // or true
}
}
)Poll Result Message
await sock.sendMessage(jid, {
pollResult: {
name: 'Hi',
values: [
['Option 1', 1000],
['Option 2', 2000]
]
}
})Call Message
await sock.sendMessage(jid, {
call: {
name: 'Hay',
type: 1 // 2 for video
}
})Event Message
await sock.sendMessage(jid, {
event: {
isCanceled: false, // or true
name: 'holiday together!',
description: 'who wants to come along?',
location: {
degreesLatitude: 24.121231,
degreesLongitude: 55.1121221,
name: 'name'
},
startTime: number,
endTime: number,
extraGuestsAllowed: true // or false
}
})Order Message
await sock.sendMessage(
jid,
{
order: {
orderId: '574xxx',
thumbnail: 'your_thumbnail',
itemCount: 'your_count',
status: 'your_status', // INQUIRY || ACCEPTED || DECLINED
surface: 'CATALOG',
message: 'your_caption',
orderTitle: "your_title",
sellerJid: 'your_jid'',
token: 'your_token',
totalAmount1000: 'your_amount',
totalCurrencyCode: 'IDR'
}
}
)Product Message
await sock.sendMessage(jid, {
product: {
productImage: {
// for using buffer >> productImage: your_buffer
url: your_url
},
productId: 'your_id',
title: 'your_title',
description: 'your_description',
currencyCode: 'IDR',
priceAmount1000: 'your_amount',
retailerId: 'your_reid', // optional use if needed
url: 'your_url', // optional use if needed
productImageCount: 'your_imageCount',
firstImageId: 'your_image', // optional use if needed
salePriceAmount1000: 'your_priceSale',
signedUrl: 'your_url' // optional use if needed
},
businessOwnerJid: 'your_jid'
})Payment Message
await sock.sendMessage(jid, {
payment: {
note: 'Hi!',
currency: 'IDR', // optional
offset: 0, // optional
amount: '10000', // optional
expiry: 0, // optional
from: '[email protected]', // optional
image: {
// optional
placeholderArgb: 'your_background', // optional
textArgb: 'your_text', // optional
subtextArgb: 'your_subtext' // optional
}
}
})Payment Invite Message
await sock.sendMessage(id, {
paymentInvite: {
type: number, // 1 || 2 || 3
expiry: 0
}
})Admin Invite Message
await sock.sendMessage(jid, {
adminInvite: {
jid: '123xxx@newsletter',
name: 'newsletter_name',
caption: 'Please be my channel admin',
expiration: 86400,
jpegThumbnail: Buffer // optional
}
})Group Invite Message
await sock.sendMessage(jid, {
groupInvite: {
jid: '[email protected]',
name: 'group_name',
caption: 'Please Join My Whatsapp Group',
code: 'code_invite',
expiration: 86400,
jpegThumbnail: Buffer // optional
}
})Share Phone Number Message
await sock.sendMessage(jid, {
sharePhoneNumber: {}
})Request Phone Number Message
await sock.sendMessage(jid, {
requestPhoneNumber: {}
})Buttons Reply Message
// List
await sock.sendMessage(
jid,
{
buttonReply: {
name: 'Hii',
description: 'description',
rowId: 'ID'
},
type: 'list'
}
)
// Plain
await sock.sendMessage(
jid,
{
buttonReply: {
displayText: 'Hii',
id: 'ID'
},
type: 'plain'
}
)
// Template
await sock.sendMessage(
jid,
{
buttonReply: {
displayText: 'Hii',
id: 'ID',
index: 'number'
},
type: 'template'
}
)
// Interactive
await sock.sendMessage(
jid,
{
buttonReply: {
body: 'Hii',
nativeFlows: {
name: 'menu_options',
paramsJson: JSON.stringify({ id: 'ID', description: 'description' })
version: 1 // 2 | 3
}
},
type: 'interactive'
}
)Buttons Message
await sock.sendMessage(jid, {
text: 'This is a button message!', // image: buffer or // image: { url: url } If you want to use images
caption: 'caption', // Use this if you are using an image or video
footer: 'Hello World!',
buttons: [
{
buttonId: 'Id1',
buttonText: {
displayText: 'Button 1'
}
},
{
buttonId: 'Id2',
buttonText: {
displayText: 'Button 2'
}
},
{
buttonId: 'Id3',
buttonText: {
displayText: 'Button 3'
}
}
]
})Buttons List Message
// Just working in a private chat
await sock.sendMessage(jid, {
text: 'This is a list!',
footer: 'Hello World!',
title: 'Amazing boldfaced list title',
buttonText: 'Required, text on the button to view the list',
sections: [
{
title: 'Section 1',
rows: [
{
title: 'Option 1',
rowId: 'option1'
},
{
title: 'Option 2',
rowId: 'option2',
description: 'This is a description'
}
]
},
{
title: 'Section 2',
rows: [
{
title: 'Option 3',
rowId: 'option3'
},
{
title: 'Option 4',
rowId: 'option4',
description: 'This is a description V2'
}
]
}
]
})Buttons Product List Message
// Just working in a private chat
await sock.sendMessage(jid, {
text: 'This is a list!',
footer: 'Hello World!',
title: 'Amazing boldfaced list title',
buttonText: 'Required, text on the button to view the list',
productList: [
{
title: 'This is a title',
products: [
{
productId: '1234'
},
{
productId: '5678'
}
]
}
],
businessOwnerJid: '[email protected]',
thumbnail: 'https://example.jpg' // or buffer
})Buttons Cards Message
await sock.sendMessage(jid, {
text: 'Body Message',
title: 'Title Message',
subtile: 'Subtitle Message',
footer: 'Footer Message',
cards: [
{
image: { url: 'https://example.jpg' }, // or buffer
title: 'Title Cards',
body: 'Body Cards',
footer: 'Footer Cards',
buttons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'Display Button',
id: 'ID'
})
},
{
name: 'cta_url',
buttonParamsJson: JSON.stringify({
display_text: 'Display Button',
url: 'https://www.example.com'
})
}
]
},
{
video: { url: 'https://example.mp4' }, // or buffer
title: 'Title Cards',
body: 'Body Cards',
footer: 'Footer Cards',
buttons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'Display Button',
id: 'ID'
})
},
{
name: 'cta_url',
buttonParamsJson: JSON.stringify({
display_text: 'Display Button',
url: 'https://www.example.com'
})
}
]
}
]
})Buttons Template Message
await sock.sendMessage(jid, {
text: 'This is a template message!',
footer: 'Hello World!',
templateButtons: [
{
index: 1,
urlButton: {
displayText: 'Follow Me',
url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
}
},
{
index: 2,
callButton: {
displayText: 'Call Me!',
phoneNumber: '628xxx'
}
},
{
index: 3,
quickReplyButton: {
displayText: 'This is a reply, just like normal buttons!',
id: 'id-like-buttons-message'
}
}
]
})Buttons Interactive Message
await sock.sendMessage(jid, {
text: 'This is an Interactive message!',
title: 'Hiii',
subtitle: 'There is a subtitle',
footer: 'Hello World!',
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'Click Me!',
id: 'your_id'
})
},
{
name: 'cta_url',
buttonParamsJson: JSON.stringify({
display_text: 'Follow Me',
url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y',
merchant_url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
})
},
{
name: 'cta_copy',
buttonParamsJson: JSON.stringify({
display_text: 'Click Me!',
copy_code: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
})
},
{
name: 'cta_call',
buttonParamsJson: JSON.stringify({
display_text: 'Call Me!',
phone_number: '628xxx'
})
},
{
name: 'cta_catalog',
buttonParamsJson: JSON.stringify({
business_phone_number: '628xxx'
})
},
{
name: 'cta_reminder',
buttonParamsJson: JSON.stringify({
display_text: '...'
})
},
{
name: 'cta_cancel_reminder',
buttonParamsJson: JSON.stringify({
display_text: '...'
})
},
{
name: 'address_message',
buttonParamsJson: JSON.stringify({
display_text: '...'
})
},
{
name: 'send_location',
buttonParamsJson: JSON.stringify({
display_text: '...'
})
},
{
name: 'open_webview',
buttonParamsJson: JSON.stringify({
title: 'Follow Me!',
link: {
in_app_webview: true, // or false
url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
}
})
},
{
name: 'mpm',
buttonParamsJson: JSON.stringify({
product_id: '8816262248471474'
})
},
{
name: 'wa_payment_transaction_details',
buttonParamsJson: JSON.stringify({
transaction_id: '12345848'
})
},
{
name: 'automated_greeting_message_view_catalog',
buttonParamsJson: JSON.stringify({
business_phone_number: '628xxx',
catalog_product_id: '12345'
})
},
{
name: 'galaxy_message',
buttonParamsJson: JSON.stringify({
mode: 'published',
flow_message_version: '3',
flow_token: '1:1307913409923914:293680f87029f5a13d1ec5e35e718af3',
flow_id: '1307913409923914',
flow_cta: 'Exiqonbotz >\\<',
flow_action: 'navigate',
flow_action_payload: {
screen: 'QUESTION_ONE',
params: {
user_id: '123456789',
referral: 'campaign_xyz'
}
},
flow_metadata: {
flow_json_version: '201',
data_api_protocol: 'v2',
flow_name: 'Lead Qualification [en]',
data_api_version: 'v2',
categories: ['Lead Generation', 'Sales']
}
})
},
{
name: 'single_select',
buttonParamsJson: JSON.stringify({
title: 'Click Me!',
sections: [
{
title: 'Title 1',
highlight_label: 'Highlight label 1',
rows: [
{
header: 'Header 1',
title: 'Title 1',
description: 'Description 1',
id: 'Id 1'
},
{
header: 'Header 2',
title: 'Title 2',
description: 'Description 2',
id: 'Id 2'
}
]
}
]
})
}
]
})
// If you want to use an image
await sock.sendMessage(jid, {
image: {
url: 'https://example.jpg'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'DisplayText',
id: 'ID1'
})
}
],
hasMediaAttachment: false // or true
})
// If you want to use an video
await sock.sendMessage(jid, {
video: {
url: 'https://example.mp4'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'DisplayText',
id: 'ID1'
})
}
],
hasMediaAttachment: false // or true
})
// If you want to use an document
await sock.sendMessage(jid, {
document: {
url: 'https://example.jpg'
},
mimetype: 'image/jpeg',
jpegThumbnail: await sock.resize('https://example.jpg', 320, 320),
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'DisplayText',
id: 'ID1'
})
}
],
hasMediaAttachment: false // or true
})
// If you want to use an location
await sock.sendMessage(jid, {
location: {
degressLatitude: -0,
degressLongitude: 0,
name: 'Hi'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'DisplayText',
id: 'ID1'
})
}
],
hasMediaAttachment: false // or true
})
// if you want to use an product
await sock.sendMessage(jid, {
product: {
productImage: {
url: 'https://example.jpg'
},
productId: '836xxx',
title: 'Title',
description: 'Description',
currencyCode: 'IDR',
priceAmount1000: '283xxx',
retailerId: 'Exiqonbotz',
url: 'https://example.com',
productImageCount: 1
},
businessOwnerJid: '[email protected]',
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
interactiveButtons: [
{
name: 'quick_reply',
buttonParamsJson: JSON.stringify({
display_text: 'DisplayText',
id: 'ID1'
})
}
],
hasMediaAttachment: false // or true
})Buttons Interactive Message PIX
await sock.sendMessage(jid, {
text: '', // This string is required. Even it's empty.
interactiveButtons: [
{
name: 'payment_info',
buttonParamsJson: JSON.stringify({
payment_settings: [
{
type: 'pix_static_code',
pix_static_code: {
merchant_name: 'Exiqonbotz',
key: '[email protected]',
key_type: 'EMAIL' // PHONE || EMAIL || CPF || EVP
}
}
]
})
}
]
})Buttons Interactive Message PAY
await sock.sendMessage(jid, {
text: '', // This string is required. Even it's empty.
interactiveButtons: [
{
name: 'review_and_pay',
buttonParamsJson: JSON.stringify({
currency: 'IDR',
payment_configuration: '',
payment_type: '',
total_amount: {
value: '999999999',
offset: '100'
},
reference_id: '45XXXXX',
type: 'physical-goods',
payment_method: 'confirm',
payment_status: 'captured',
payment_timestamp: Math.floor(Date.now() / 1000),
order: {
status: 'completed',
description: '',
subtotal: {
value: '0',
offset: '100'
},
order_type: 'PAYMENT_REQUEST',
items: [
{
retailer_id: 'your_retailer_id',
name: 'Exiqonbotz >\\\<',
amount: {
value: '999999999',
offset: '100'
},
quantity: '1'
}
]
},
additional_note: 'Exiqonbotz >\\\<',
native_payment_methods: [],
share_payment_status: false
})
}
]
})Status Mentions Message
const jids = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
// Text
await sock.sendStatusMentions(
{
text: 'Hello Everyone',
font: 2, // optional
textColor: 'FF0000', // optional
backgroundColor: '#000000' // optional
},
jids // Limit to 5 mentions per status
)
// Image
await sock.sendStatusMentions(
{
Image: { url: 'https://example.com/ruriooe.jpg' }, or image buffer
caption: 'Hello Everyone ' // optional
},
jids // Limit to 5 mentions per status
)
// Video
await sock.sendStatusMentions(
{
video: { url: 'https://example.com/ruriooe.mp4' }, or video buffer
caption: 'Hello Everyone ' // optional
},
jids // Limit to 5 mentions per status
)
// Audio
await sock.sendStatusMentions(
{
audio: { url: 'https://example.com/ruriooe.mp3' }, or audio buffer
backgroundColor: '#000000', // optional
mimetype: 'audio/mp4',
ppt: true
},
jids // Limit to 5 mentions per status
)Send Album Message
await sock.sendAlbumMessage(
jid,
[
{
image: { url: 'https://example.jpg' },
caption: 'Hello World'
},
{
image: Buffer,
caption: 'Hello World'
},
{
video: { url: 'https://example.mp4' },
caption: 'Hello World'
},
{
video: Buffer,
caption: 'Hello World'
}
],
{
quoted: message,
delay: 2000
}
)Shop Message
await sock.sendMessage(jid, {
text: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
shop: {
surface: 1, // 2 | 3 | 4
id: 'https://example.com'
},
viewOnce: true
})
// Image
await sock.sendMessage(jid, {
image: {
url: 'https://example.jpg'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
shop: {
surface: 1, // 2 | 3 | 4
id: 'https://example.com'
},
hasMediaAttachment: false, // or true
viewOnce: true
})
// Video
await sock.sendMessage(jid, {
video: {
url: 'https://example.jpg'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
shop: {
surface: 1, // 2 | 3 | 4
id: 'https://example.com'
},
hasMediaAttachment: false, // or true
viewOnce: true
})
// Document
await sock.sendMessage(jid, {
document: {
url: 'https://example.jpg'
},
mimetype: 'image/jpeg',
jpegThumbnail: await sock.resize('https://example.jpg', 320, 320),
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
shop: {
surface: 1, // 2 | 3 | 4
id: 'https://example.com'
},
hasMediaAttachment: false, // or true,
viewOnce: true
})
// Location
await sock.sendMessage(jid, {
location: {
degressLatitude: -0,
degressLongitude: 0,
name: 'Hi'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
shop: {
surface: 1, // 2 | 3 | 4
id: 'https://example.com'
},
hasMediaAttachment: false, // or true
viewOnce: true
})
// Product
await sock.sendMessage(jid, {
product: {
productImage: {
url: 'https://example.jpg'
},
productId: '836xxx',
title: 'Title',
description: 'Description',
currencyCode: 'IDR',
priceAmount1000: '283xxx',
retailerId: 'Exiqonbotz',
url: 'https://example.com',
productImageCount: 1
},
businessOwnerJid: '[email protected]',
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
shop: {
surface: 1, // 2 | 3 | 4
id: 'https://example.com'
},
hasMediaAttachment: false, // or true
viewOnce: true
})Collection Message
await sock.sendMessage(jid, {
text: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
collection: {
bizJid: 'jid',
id: 'https://example.com',
version: 1
},
viewOnce: true
})
// Image
await sock.sendMessage(jid, {
image: {
url: 'https://example.jpg'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
collection: {
bizJid: 'jid',
id: 'https://example.com',
version: 1
},
hasMediaAttachment: false, // or true
viewOnce: true
})
// Video
await sock.sendMessage(jid, {
video: {
url: 'https://example.jpg'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
collection: {
bizJid: 'jid',
id: 'https://example.com',
version: 1
},
hasMediaAttachment: false, // or true
viewOnce: true
})
// Document
await sock.sendMessage(jid, {
document: {
url: 'https://example.jpg'
},
mimetype: 'image/jpeg',
jpegThumbnail: await sock.resize('https://example.jpg', 320, 320),
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
collection: {
bizJid: 'jid',
id: 'https://example.com',
version: 1
},
hasMediaAttachment: false, // or true,
viewOnce: true
})
// Location
await sock.sendMessage(jid, {
location: {
degressLatitude: -0,
degressLongitude: 0,
name: 'Hi'
},
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
collection: {
bizJid: 'jid',
id: 'https://example.com',
version: 1
},
hasMediaAttachment: false, // or true
viewOnce: true
})
// Product
await sock.sendMessage(jid, {
product: {
productImage: {
url: 'https://example.jpg'
},
productId: '836xxx',
title: 'Title',
description: 'Description',
currencyCode: 'IDR',
priceAmount1000: '283xxx',
retailerId: 'Exiqonbotz',
url: 'https://example.com',
productImageCount: 1
},
businessOwnerJid: '[email protected]',
caption: 'Body',
title: 'Title',
subtitle: 'Subtitle',
footer: 'Footer',
collection: {
bizJid: 'jid',
id: 'https://example.com',
version: 1
},
hasMediaAttachment: false, // or true
viewOnce: true
})Sticker Pack Message
// I don't know why the sticker doesn't appear
await sock.sendMessage(jid, {
stickerPack: {
name: 'Hiii',
publisher: 'Exiqonbotz',
description: 'Hello',
cover: Buffer, // Image buffer
stickers: [
{
data: { url: 'https://example.com/1234kjd.webp' },
emojis: ['❤'], // optional
accessibilityLabel: '' // optional
},
{
data: Buffer,
emojis: ['❤'], // optional
accessibilityLabel: '' // optional
}
]
}
})Rich AI Response Message
Send a WhatsApp AI-style rich response — the same format used by Meta AI bots — with an optional syntax-highlighted code block.
Uses botForwardedMessage → richResponseMessage → unifiedResponse (raw JSON bytes in the data field).
Token types produced by the built-in tokenizer: KEYWORD, STR, NUMBER, METHOD, COMMENT, DEFAULT.
WAProto types used: AIRichResponseMessage (field 97), AIRichResponseUnifiedResponse, ForwardedAIBotMessageInfo, BotMessageSharingInfo.
// Text-only
await sock.sendMessage(jid, {
richResponse: {
text: 'aku hann universe'
}
})
// Text + JS code block (auto-tokenized)
await sock.sendMessage(jid, {
richResponse: {
text: 'Here is a Hello World example:',
code: 'console.log("Hello World")',
language: 'javascript' // default
}
})
// Text + code + custom bot JID
await sock.sendMessage(jid, {
richResponse: {
text: 'Result:',
code: 'const x = 42\nconsole.log(x)',
botJid: '259786046210223@bot'
}
})Rich Composer Methods
These methods are available directly on the socket and send rich AI-style content using the botForwardedMessage proto chain.
Send Table
await sock.sendTable(
jid,
'User Stats', // title
['Name', 'Score', 'Rank'], // headers
[['Alice', '980', '#1'], ['Bob', '870', '#2']], // rows
quoted, // optional quoted message
{ headerText: 'Top Players', footer: 'Updated daily' } // optional
)Send List
await sock.sendList(
jid,
'Shopping List', // title
['Apples', 'Bread', 'Milk'], // items (string[] or string[][])
quoted, // optional
{ footer: 'Remember to buy!' }
)Send Code Block
await sock.sendCodeBlock(
jid,
'console.log("Hello World")', // code string
quoted, // optional
{
title: 'Example',
language: 'javascript', // default: 'javascript'
footer: 'Run with Node.js'
}
)Send Latex
Send a LaTeX expression as text (no image rendering).
await sock.sendLatex(
jid,
quoted,
{
text: 'Quadratic formula:',
expressions: [
{
latexExpression: 'x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}',
url: 'https://example.com/formula.png', // pre-rendered image url
width: 300,
height: 80
}
],
footer: 'Source: Wikipedia'
}
)Send Latex Image
Renders LaTeX to a PNG via your own renderLatexToPng function and uploads it.
const renderLatexToPng = async (expr) => {
// return { buffer: Buffer, width: number, height: number }
}
await sock.sendLatexImage(
jid,
quoted,
{
text: 'Euler\'s identity:',
expressions: [{ latexExpression: 'e^{i\\pi}+1=0' }]
},
renderLatexToPng,
waUploadToServer
)Send Latex Inline Image
Same as above but renders each expression as an inline image block.
await sock.sendLatexInlineImage(
jid,
quoted,
{
text: 'Inline formula:',
expressions: [{ latexExpression: '\\sqrt{2}' }]
},
renderLatexToPng,
waUploadToServer
)Send Rich Message
Send a fully custom array of submessages using the rich response format.
await sock.sendRichMessage(
jid,
[
{ messageType: 2, messageText: 'Header text' },
{ messageType: 5, codeMetadata: { codeLanguage: 'javascript', codeBlocks: [...] } }
],
quoted
)Capture & Resend Unified Response
Capture the unifiedResponse payload from a received Meta AI message and forward it.
// capture from an incoming message
const captured = sock.captureUnifiedResponse(message)
// resend to another jid
if (captured) {
await sock.sendUnifiedResponse(jid, quoted, captured)
}Status Notification Message
[!NOTE] Added in WA 2.3000+
Sent when a status add-yours / reshare / question-answer-reshare event fires.
await sock.sendMessage(jid, {
statusNotification: {
responseMessageKey: { remoteJid: jid, id: 'MSG_ID' },
originalMessageKey: { remoteJid: jid, id: 'ORIG_ID' },
type: 1 // 1=STATUS_ADD_YOURS, 2=STATUS_RESHARE, 3=STATUS_QUESTION_ANSWER_RESHARE
}
})
// full proto key also accepted:
// statusNotificationMessage: { ... }Status Question Answer Message
[!NOTE] Added in WA 2.3000+
User answered a status question.
await sock.sendMessage(jid, {
statusQuestionAnswer: {
key: { remoteJid: jid, id: 'MSG_ID' },
text: 'My answer'
}
})
// full proto key: statusQuestionAnswerMessageQuestion Response Message
[!NOTE] Added in WA 2.3000+
Direct response to a question message.
await sock.sendMessage(jid, {
questionResponse: {
key: { remoteJid: jid, id: 'QUESTION_MSG_ID' },
text: 'My response'
}
})
// full proto key: questionResponseMessageStatus Quoted Message
[!NOTE] Added in WA 2.3000+
Quote a status with a custom type.
await sock.sendMessage(jid, {
statusQuoted: {
type: 1, // 1 = QUESTION_ANSWER
text: 'Quoted text',
thumbnail: Buffer, // optional
originalStatusId: { remoteJid: jid, id: 'STATUS_MSG_ID' }
}
})
// full proto key: statusQuotedMessageStatus Sticker Interaction Message
[!NOTE] Added in WA 2.3000+
React to a status with a sticker.
await sock.sendMessage(jid, {
statusStickerInteraction: {
key: { remoteJid: jid, id: 'STATUS_MSG_ID' },
stickerKey: 'sticker-hash-key',
type: 1 // 1 = REACTION
}
})
// full proto key: statusStickerInteractionMessageNewsletter Follower Invite Message
[!NOTE] Added in WA 2.3000+
Invite a user to follow a newsletter.
await sock.sendMessage(jid, {
newsletterFollowerInvite: {
newsletterJid: '120363xxxxxx@newsletter',
newsletterName: 'My Channel',
jpegThumbnail: Buffer, // optional
caption: 'Join my channel!'
}
})
// full proto key: newsletterFollowerInviteMessageV2Message History Notice
[!NOTE] Added in WA 2.3000+
Notify about message history metadata.
await sock.sendMessage(jid, {
messageHistoryNotice: {
contextInfo: { ... }
// messageHistoryMetadata is optional
}
})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 con
