Skip to main content

Message Generation

generateWAMessage

Generates a complete WhatsApp message with all metadata.
async function generateWAMessage(
  jid: string,
  content: AnyMessageContent,
  options: MessageGenerationOptions
): Promise<WAMessage>
jid
string
required
Recipient JID (chat identifier)
content
AnyMessageContent
required
Message content - can be text, media, location, contact, etc.
options
MessageGenerationOptions
required
Message generation options
return
WAMessage
Complete WhatsApp message ready to send
Example:
const msg = await generateWAMessage(
  '[email protected]',
  { text: 'Hello!' },
  {
    userJid: sock.user.id,
    upload: sock.waUploadToServer,
    logger
  }
)

generateWAMessageContent

Generates the content portion of a WhatsApp message.
async function generateWAMessageContent(
  message: AnyMessageContent,
  options: MessageContentGenerationOptions
): Promise<WAMessageContent>
message
AnyMessageContent
required
Raw message content to generate
options
MessageContentGenerationOptions
required
Content generation options including upload function and media cache
return
WAMessageContent
Generated message content ready for protobuf encoding

generateWAMessageFromContent

Generates a WAMessage from already-prepared message content.
function generateWAMessageFromContent(
  jid: string,
  message: WAMessageContent,
  options: MessageGenerationOptionsFromContent
): WAMessage
jid
string
required
Recipient JID
message
WAMessageContent
required
Pre-generated message content
options
MessageGenerationOptionsFromContent
required
Options including userJid, timestamp, quoted message, and ephemeral settings
return
WAMessage
Complete WAMessage with key and metadata

Media Operations

downloadMediaMessage

Downloads media from a message. Supports automatic re-upload requests on failure.
async function downloadMediaMessage<Type extends 'buffer' | 'stream'>(
  message: WAMessage,
  type: Type,
  options: MediaDownloadOptions,
  ctx?: DownloadMediaMessageContext
): Promise<Type extends 'buffer' ? Buffer : Transform>
message
WAMessage
required
The message containing media to download
type
'buffer' | 'stream'
required
Whether to return a Buffer or Stream
options
MediaDownloadOptions
required
Download options
ctx
DownloadMediaMessageContext
Optional context for automatic re-upload requests
return
Buffer | Transform
Downloaded media as Buffer or Stream depending on type parameter
When a 404 or 410 error occurs, the function automatically requests re-upload from the sender if context is provided.
Example:
// Download as buffer
const buffer = await downloadMediaMessage(
  message,
  'buffer',
  {},
  { reuploadRequest: sock.updateMediaMessage, logger }
)

await fs.writeFile('media.jpg', buffer)

// Download as stream
const stream = await downloadMediaMessage(message, 'stream', {})
stream.pipe(fs.createWriteStream('media.jpg'))

prepareWAMessageMedia

Prepares media for sending by encrypting and uploading it.
async function prepareWAMessageMedia(
  message: AnyMediaMessageContent,
  options: MessageContentGenerationOptions
): Promise<WAMessageContent>
message
AnyMediaMessageContent
required
Media message content to prepare
options
MessageContentGenerationOptions
required
Options including upload function, media cache, and logger
return
WAMessageContent
Prepared message content with encrypted media URL
Features:
  • Automatic thumbnail generation for images and videos
  • Audio duration detection
  • Waveform generation for voice messages (ptt)
  • Media caching to avoid re-uploads
  • Encryption and hashing

Message Helpers

getContentType

Extracts the content type key from a message.
function getContentType(
  content: proto.IMessage | undefined
): keyof proto.IMessage | undefined
content
proto.IMessage
Message content to analyze
return
string
The key representing the message type (e.g., ‘conversation’, ‘imageMessage’, ‘videoMessage’)
Example:
const msgType = getContentType(message.message)
// Returns: 'conversation', 'imageMessage', 'videoMessage', etc.

normalizeMessageContent

Normalizes ephemeral and view-once messages to regular content.
function normalizeMessageContent(
  content: WAMessageContent | null | undefined
): WAMessageContent | undefined
content
WAMessageContent
Message content to normalize
return
WAMessageContent
Unwrapped message content (extracts inner message from ephemeral/viewOnce wrappers)
Example:
const normalized = normalizeMessageContent(message.message)
// Extracts actual content from ephemeralMessage, viewOnceMessage, etc.

extractMessageContent

Extracts the true message content, including from template messages.
function extractMessageContent(
  content: WAMessageContent | undefined | null
): WAMessageContent | undefined
return
WAMessageContent
Extracted core message content

getDevice

Predicts the device type based on message ID pattern.
function getDevice(id: string): 'ios' | 'web' | 'android' | 'desktop' | 'unknown'
id
string
required
Message ID to analyze
return
string
Detected device type based on ID pattern
Example:
const device = getDevice(message.key.id)
// Returns: 'ios', 'android', 'web', 'desktop', or 'unknown'

generateForwardMessageContent

Generates content for forwarding a message.
function generateForwardMessageContent(
  message: WAMessage,
  forceForward?: boolean
): WAMessageContent
message
WAMessage
required
The message to forward
forceForward
boolean
Force showing as forwarded even if from you (default: false)
return
WAMessageContent
Message content configured for forwarding with incremented forwarding score
Example:
const forwardContent = generateForwardMessageContent(originalMessage)

await sock.sendMessage(recipientJid, forwardContent)

Message Aggregation

getAggregateVotesInPollMessage

Aggregates all votes in a poll message.
function getAggregateVotesInPollMessage(
  message: Pick<WAMessage, 'pollUpdates' | 'message'>,
  meId?: string
): Array<{ name: string; voters: string[] }>
message
WAMessage
required
Poll message with updates
meId
string
Your JID for attribution
return
Array
List of poll options with their voters
Example:
const votes = getAggregateVotesInPollMessage(pollMessage, sock.user.id)
// [
//   { name: 'Option 1', voters: ['[email protected]', '[email protected]'] },
//   { name: 'Option 2', voters: ['[email protected]'] }
// ]

updateMessageWithReaction

Updates a message with a new reaction.
function updateMessageWithReaction(
  msg: Pick<WAMessage, 'reactions'>,
  reaction: proto.IReaction
): void
msg
WAMessage
required
Message to update (mutated in place)
reaction
proto.IReaction
required
Reaction data to add/update

updateMessageWithPollUpdate

Updates a message with a new poll vote.
function updateMessageWithPollUpdate(
  msg: Pick<WAMessage, 'pollUpdates'>,
  update: proto.IPollUpdate
): void

URL Utilities

extractUrlFromText

Extracts the first URL from text using regex.
function extractUrlFromText(text: string): string | undefined
text
string
required
Text to search for URLs
return
string
First URL found in the text, or undefined
Example:
const url = extractUrlFromText('Check out https://example.com')
// Returns: 'https://example.com'

generateLinkPreviewIfRequired

Generates link preview metadata if URL is detected.
async function generateLinkPreviewIfRequired(
  text: string,
  getUrlInfo: (url: string) => Promise<WAUrlInfo>,
  logger?: ILogger
): Promise<WAUrlInfo | undefined>
return
WAUrlInfo
Link preview metadata including title, description, and thumbnail

Media Utilities

Detailed guide on media message handling

Socket Events

Message events and event handling

Build docs developers (and LLMs) love