Register callbacks for low-level WhatsApp protocol events
Baileys provides direct access to the underlying WebSocket connection, allowing you to register callbacks for low-level WhatsApp protocol events. This is useful for implementing custom functionality and monitoring protocol-level messages.
Filter messages by tag and a specific attribute value:
// Listen for 'edge_routing' messages with id='abcd'sock.ws.on('CB:edge_routing,id:abcd', (node: BinaryNode) => { console.log('Edge routing with specific ID:', node)})
Filter by tag, attribute, and the first content node’s tag:
// Listen for 'edge_routing' with id='abcd' and first content tag 'routing_info'sock.ws.on('CB:edge_routing,id:abcd,routing_info', (node: BinaryNode) => { console.log('Specific edge routing message:', node)})
// Any presence updatesock.ws.on('CB:presence', (node: BinaryNode) => { const from = node.attrs.from const type = node.attrs.type // 'available', 'unavailable', 'composing', etc. console.log(`${from} is ${type}`)})// Only available statussock.ws.on('CB:presence,type:available', (node: BinaryNode) => { console.log(`${node.attrs.from} came online`)})// Only composing (typing)sock.ws.on('CB:presence,type:composing', (node: BinaryNode) => { console.log(`${node.attrs.from} is typing...`)})
For a message with tag 'iq', attrs.type='set', attrs.id='123', and first content tag 'pair-device', Baileys emits events in this order:
// Most specificws.emit('CB:iq,type:set,pair-device', node)ws.emit('CB:iq,id:123,pair-device', node)// Medium specificityws.emit('CB:iq,type:set', node)ws.emit('CB:iq,id:123', node)// Less specificws.emit('CB:iq,type', node)ws.emit('CB:iq,id', node)// With content tag onlyws.emit('CB:iq,,pair-device', node)// Least specificws.emit('CB:iq', node)
Baileys tries multiple patterns, emitting from most specific to least specific. Your callback will trigger on the first matching pattern.
Baileys provides utilities for working with binary nodes:
import { getBinaryNodeChild, getBinaryNodeChildren, getAllBinaryNodeChildren, binaryNodeToString} from '@whiskeysockets/baileys'sock.ws.on('CB:ib', (node: BinaryNode) => { // Get first child with specific tag const child = getBinaryNodeChild(node, 'edge_routing') // Get all children with specific tag const children = getBinaryNodeChildren(node, 'message') // Get all children (any tag) const allChildren = getAllBinaryNodeChildren(node) // Convert to readable string (XML-like format) console.log(binaryNodeToString(node))})