Skip to main content
Message utilities provide functions for generating messages, extracting content, and handling message metadata.

getContentType

Extracts the content type key from a message object to determine the message type.
function getContentType(
  content: proto.IMessage | undefined
): keyof proto.IMessage | undefined

Parameters

content
proto.IMessage | undefined
required
The message content object to analyze.

Returns

The key representing the message type (e.g., 'conversation', 'imageMessage', 'videoMessage'), or undefined if no valid content type is found.

Usage example

import { getContentType } from '@whiskeysockets/baileys'

const message = {
  conversation: 'Hello World'
}

const type = getContentType(message)
console.log(type) // 'conversation'

const imageMsg = {
  imageMessage: {
    url: 'https://example.com/image.jpg',
    mimetype: 'image/jpeg'
  }
}

const imageType = getContentType(imageMsg)
console.log(imageType) // 'imageMessage'

generateMessageID

Generates a random message ID in WhatsApp’s format.
function generateMessageID(): string

Returns

A randomly generated message ID string in the format 3EB0 followed by 18 hexadecimal characters.

Usage example

import { generateMessageID } from '@whiskeysockets/baileys'

const msgId = generateMessageID()
console.log(msgId) // '3EB0A1B2C3D4E5F6789ABC'

generateMessageIDV2

Generates a message ID using an improved algorithm that incorporates timestamp and user information.
function generateMessageIDV2(userId?: string): string

Parameters

userId
string
Optional user JID to incorporate into the message ID for better uniqueness.

Returns

A message ID string that includes timestamp and optional user data, hashed with SHA256.

Usage example

import { generateMessageIDV2 } from '@whiskeysockets/baileys'

const msgId = generateMessageIDV2('[email protected]')
console.log(msgId) // '3EB0' + 18 hex chars derived from timestamp and user
generateMessageIDV2 is preferred over generateMessageID as it produces more deterministic IDs that are less likely to collide.

normalizeMessageContent

Normalizes ephemeral, view-once, and other wrapped messages to extract the core message content.
function normalizeMessageContent(
  content: WAMessageContent | null | undefined
): WAMessageContent | undefined

Parameters

content
WAMessageContent | null | undefined
required
The message content to normalize.

Returns

The normalized message content with wrapper layers removed (ephemeral, viewOnce, etc.).

Usage example

import { normalizeMessageContent } from '@whiskeysockets/baileys'

const wrappedMessage = {
  viewOnceMessage: {
    message: {
      imageMessage: {
        url: 'https://example.com/image.jpg'
      }
    }
  }
}

const normalized = normalizeMessageContent(wrappedMessage)
console.log(normalized)
// { imageMessage: { url: 'https://example.com/image.jpg' } }

extractMessageContent

Extracts the actual content from a message, unwrapping various message types including templates and buttons.
function extractMessageContent(
  content: WAMessageContent | undefined | null
): WAMessageContent | undefined

Parameters

content
WAMessageContent | undefined | null
required
The message content to extract from.

Returns

The extracted core message content, or undefined if no content is present.

Usage example

import { extractMessageContent } from '@whiskeysockets/baileys'

const templateMessage = {
  buttonsMessage: {
    imageMessage: {
      url: 'https://example.com/image.jpg'
    },
    contentText: 'Choose an option'
  }
}

const content = extractMessageContent(templateMessage)
console.log(content)
// { imageMessage: { url: 'https://example.com/image.jpg' } }

generateWAMessageContent

Generates WhatsApp message content from a high-level message object.
async function generateWAMessageContent(
  message: AnyMessageContent,
  options: MessageContentGenerationOptions
): Promise<WAMessageContent>

Parameters

message
AnyMessageContent
required
The message to generate content for. Can be text, media, location, contact, etc.
options
MessageContentGenerationOptions
required
Options for content generation.
upload
WAMediaUploadFunction
Function to upload media files.
logger
ILogger
Logger instance for debugging.
mediaCache
CacheStore
Cache for media uploads to avoid re-uploading.
getUrlInfo
function
Function to fetch link preview information.
backgroundColor
string | number
Background color for audio status messages.

Returns

A Promise resolving to a WAMessageContent object ready to be sent.

Usage example

import { generateWAMessageContent } from '@whiskeysockets/baileys'

const content = await generateWAMessageContent(
  { text: 'Hello with link preview: https://github.com' },
  {
    upload: uploadFunction,
    logger: myLogger,
    getUrlInfo: async (url) => {
      // Fetch link preview data
      return {
        'matched-text': url,
        title: 'GitHub',
        description: 'Where the world builds software'
      }
    }
  }
)

generateWAMessageFromContent

Generates a complete WAMessage from message content, adding metadata like timestamp and message key.
function generateWAMessageFromContent(
  jid: string,
  message: WAMessageContent,
  options: MessageGenerationOptionsFromContent
): WAMessage

Parameters

jid
string
required
The recipient JID (e.g., '[email protected]' or group JID).
message
WAMessageContent
required
The message content to wrap.
options
MessageGenerationOptionsFromContent
required
Message generation options.
timestamp
Date
Message timestamp (defaults to current time).
messageId
string
Custom message ID (auto-generated if not provided).
quoted
WAMessage
Message being quoted/replied to.
userJid
string
Your user JID.
ephemeralExpiration
number
Expiration time in seconds for disappearing messages.

Returns

A complete WAMessage object with key, content, and metadata.

Usage example

import { generateWAMessageFromContent, proto } from '@whiskeysockets/baileys'

const message = generateWAMessageFromContent(
  '[email protected]',
  {
    conversation: 'Hello World'
  },
  {
    userJid: '[email protected]',
    timestamp: new Date()
  }
)

console.log(message.key.id) // Auto-generated message ID
console.log(message.key.remoteJid) // '[email protected]'

generateWAMessage

Combines content generation and message creation into a single function.
async function generateWAMessage(
  jid: string,
  content: AnyMessageContent,
  options: MessageGenerationOptions
): Promise<WAMessage>

Parameters

jid
string
required
The recipient JID.
content
AnyMessageContent
required
High-level message content (text, media, location, etc.).
options
MessageGenerationOptions
required
Combined options for both content generation and message creation.

Returns

A Promise resolving to a complete WAMessage ready to send.

Usage example

import { generateWAMessage } from '@whiskeysockets/baileys'

const message = await generateWAMessage(
  '[email protected]',
  { text: 'Hello World!' },
  {
    userJid: '[email protected]',
    upload: uploadFunction,
    logger: myLogger
  }
)

// Send the message
await sock.relayMessage(message.key.remoteJid, message.message, {
  messageId: message.key.id
})

generateForwardMessageContent

Generates content for forwarding a message, maintaining forward count and metadata.
function generateForwardMessageContent(
  message: WAMessage,
  forceForward?: boolean
): WAMessageContent

Parameters

message
WAMessage
required
The message to forward.
forceForward
boolean
If true, shows the message as forwarded even if it’s from you.

Returns

Message content formatted for forwarding with updated forwarding score.

Usage example

import { generateForwardMessageContent, generateWAMessage } from '@whiskeysockets/baileys'

// Forward a received message
const forwardContent = generateForwardMessageContent(receivedMessage)

const forwardMsg = await generateWAMessage(
  '[email protected]',
  { forward: receivedMessage },
  options
)

updateMessageWithReceipt

Updates a message with read receipt information.
function updateMessageWithReceipt(
  msg: Pick<WAMessage, 'userReceipt'>,
  receipt: MessageUserReceipt
): void

Parameters

msg
Pick<WAMessage, 'userReceipt'>
required
The message object to update.
receipt
MessageUserReceipt
required
The receipt information to add or update.

Usage example

import { updateMessageWithReceipt } from '@whiskeysockets/baileys'

const message = { userReceipt: [] }

updateMessageWithReceipt(message, {
  userJid: '[email protected]',
  receiptTimestamp: Date.now(),
  readTimestamp: Date.now()
})

updateMessageWithReaction

Updates a message with reaction information.
function updateMessageWithReaction(
  msg: Pick<WAMessage, 'reactions'>,
  reaction: proto.IReaction
): void

Parameters

msg
Pick<WAMessage, 'reactions'>
required
The message object to update.
reaction
proto.IReaction
required
The reaction to add or update.

Usage example

import { updateMessageWithReaction } from '@whiskeysockets/baileys'

const message = { reactions: [] }

updateMessageWithReaction(message, {
  key: messageKey,
  text: '❤️',
  senderTimestampMs: Date.now()
})

getAggregateVotesInPollMessage

Aggregates all votes in a poll message to show results.
function getAggregateVotesInPollMessage(
  message: Pick<WAMessage, 'pollUpdates' | 'message'>,
  meId?: string
): Array<{ name: string; voters: string[] }>

Parameters

message
Pick<WAMessage, 'pollUpdates' | 'message'>
required
The poll message with updates.
meId
string
Your user JID for proper vote attribution.

Returns

Array of poll options with their vote counts and voter JIDs.

Usage example

import { getAggregateVotesInPollMessage } from '@whiskeysockets/baileys'

const pollResults = getAggregateVotesInPollMessage(
  pollMessage,
  '[email protected]'
)

pollResults.forEach(option => {
  console.log(`${option.name}: ${option.voters.length} votes`)
  console.log('Voters:', option.voters)
})

getDevice

Determines the device type from a message ID.
function getDevice(id: string): 'ios' | 'web' | 'android' | 'desktop' | 'unknown'

Parameters

id
string
required
The message ID to analyze.

Returns

The detected device type based on the message ID pattern.

Usage example

import { getDevice } from '@whiskeysockets/baileys'

const device = getDevice(message.key.id)
console.log(device) // 'android', 'ios', 'web', etc.
  • AnyMessageContent - Union type of all possible message content
  • WAMessage - Complete WhatsApp message structure
  • WAMessageContent - Protocol buffer message content
  • MessageGenerationOptions - Options for message generation
  • proto.IMessage - Protocol buffer message interface

Build docs developers (and LLMs) love