@itsmelody/baileys
v0.2.11
Published
This library is based on Baileys and has been edited by Melody to offer maximum speed and stability. It is not affiliated with WhatsApp.
Downloads
767
Maintainers
Readme
@itsmelody/Baileys - API de WhatsApp Web ✰
Nota Importante
ꕤ Esta librería está basada en Baileys y ha sido editada por Melody para ofrecer máxima velocidad y estabilidad. No está afiliada con WhatsApp.
Credits to
@itsliaaa
Aviso de Responsabilidad
@itsmelody/Baileys no pueden ser responsables por mal uso. Por favor, usa esta librería para crear cosas lindas y positivas, no para spam o actividades maliciosas.
Instalación
# Versión estable
npm install @itsmelody/Baileys
# o
yarn add @itsmelody/Baileys
# Versión de desarrollo
npm install github:itsmelody/Baileys
# o
yarn add github:itsmelody/Baileys
Novedades y Correcciones ✰
- 🖼️ Se solucionó un problema que impedía enviar contenido multimedia a los boletines informativos (Newsletters).
- 📁 Se reintrodujo
makeInMemoryStorecon una adaptación mínima deESMy ajustes para Baileys v7. - 📦 Gestión de procesos más segura: Se cambió la ejecución de FFmpeg de
execaspawn. - 🗃️ Nuevo backend de imagen: Se agregó
@napi-rs/imagepara un equilibrio perfecto entre rendimiento y compatibilidad. - 💭 Compatibilidad para citar mensajes dentro de canales (Newsletters). [NUEVO]
- 🎀 Soporte para iconos de botones personalizados en mensajes interactivos. [NUEVO]
Compatibilidad Ampliada de Mensajes
- 🖼️ Mensajes de Álbum: Envía múltiples imágenes y videos en un solo bloque.
- 👥 Estado de Grupo: Soporte para mensajes de estado específicos de grupo.
- 👉🏻 Mensajes Interactivos: Botones, listas, flujos nativos, plantillas y carruseles.
- 🎞️ Menciones en Status: Publica y menciona en estados de WhatsApp.
- 📦 Sticker Packs: Envío de paquetes de stickers completos con metadatos.
- ✨ Rich Response: Mensajes con respuestas enriquecidas. [NUEVO]
- 🧾 Code Blocks: Mensajes con bloques de código y resaltado. [NUEVO]
- 📋 Tablas: Visualización de datos estructurados en tablas. [NUEVO]
- 💳 Pagos: Solicitudes, invitaciones, pedidos y facturas de pago.
- 📰 Anuncios: Envío simplificado de externalAdReply sin configuración manual.
Ejemplo Rápido (JavaScript)
const { makeWASocket, useMultiFileAuthState } = require('@itsmelody/Baileys')
async function startBot() {
const { state, saveCreds } = await useMultiFileAuthState('session-melody')
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
logger: require('pino')({ level: 'silent' })
})
sock.ev.on('connection.update', ({ connection }) => {
if(connection === 'open') console.log('¡Conectado con éxito! ✰')
})
sock.ev.on('creds.update', saveCreds)
}
startBot()
Características Principales
· Optimizado para mayor velocidad y estabilidad
· Mensajes multimedia
· Comandos personalizados fáciles de implementar
· Soporte para grupos y chats privados
· Mensajes interactivos con botone
Funciones Técnicas
· Conexión estable con reconexión automática
· Sesiones persistentes que se guardan solitas
· Manejo de errores con mensajes bonitos
· Sincronización en tiempo real
Características Técnicas
· Sin Selenium - Conexión directa vía WebSocket
· Super eficiente - Ahorra mucha RAM
· Soporte multi-dispositivo - Compatible con la versión web
· Totalmente tipado - Con TypeScript y JavaScript
· API completa - Todas las funciones de WhatsApp Web
· Rendimiento optimizado - Código eficiente y rápido
Uso Básico
Inicializar el Bot (JavaScript)
const { makeWASocket, useMultiFileAuthState } = require('@Itsmelody/Baileys')
const { state, saveCreds } = await useMultiFileAuthState('session-mymelody')
const melody = makeWASocket({
auth: state,
printQRInTerminal: true
})
melody.ev.on('creds.update', saveCreds)Ejemplos de Funciones
Enviar Mensaje a Múltiples Chats
async function broadcastMessage(jids, message) {
for(const jid of jids) {
await melody.sendMessage(jid, { text: message })
}
}Descargar Medios
const { downloadMediaMessage } = require('@Itsmelody/Baileys')
const stream = await downloadMediaMessage(message, 'buffer')
// Guardar o procesar el medioTipos para TypeScript
import { WAMessage, WASocket } from '@Itsmelody/Baileys'
interface MyBot extends WASocket {
// Tus tipos personalizados aquí
}
function handleMessage(message: WAMessage): void {
// Tu lógica de manejo de mensajes
}🧩 Import (ESM & CJS)
// --- ESM
import { makeWASocket } from '@itsmelody/Baileys'
// --- CJS (tested and working on Node.js 24 ✅)
const { makeWASocket } = require('@itsmelody/Baileys')🔠 Text
// --- Send a regular text message
sock.sendMessage(jid, {
text: '👋🏻 Hello'
}, {
quoted: message
})
// --- Send a text message with a link preview
const urlA = 'https://github.com/Melody-Xz/Baileys'
sock.sendMessage(jid, {
text: urlA + ' 👆🏻 Check it out!',
linkPreview: {
'matched-text': urlA,
title: '🌱 @itsmelody/Baileys',
description: 'Underrated Baileys Fork',
previewType: 0, // --- Use 1 for video playback in the link preview
jpegThumbnail: fs.readFileSync('./path/to/image.jpg')
}
})
// --- Send a text message with a large link preview and favicon
import { prepareWAMessageMedia } from '@itsmelody/Baileys'
const urlB = 'https://github.com/Melody-Xz/Baileys#readme'
const { imageMessage: image } = await prepareWAMessageMedia({
image: {
url: './path/to/image.jpg'
}
}, {
upload: sock.waUploadToServer,
mediaTypeOverride: 'thumbnail-link'
})
// --- Set the thumbnail display size
image.height = 720
image.width = 480
sock.sendMessage(jid, {
text: urlB + ' 👆🏻 Check it out!',
linkPreview: {
'matched-text': urlB,
title: '🌱 @itsmelody/Baileys',
description: 'Underrated Baileys Fork',
previewType: 0,
jpegThumbnail: fs.readFileSync('./path/to/image.jpg'),
highQualityThumbnail: image,
linkPreviewMetadata: {
linkMediaDuration: 0, // --- Duration in seconds (for video/audio content)
socialMediaPostType: 1, // --- Enum: 0 = NONE, 1 = REEL, 2 = LIVE_VIDEO, 3 = LONG_VIDEO, 4 = SINGLE_IMAGE, 5 = CAROUSEL
} // --- Additional metadata for large link preview
},
favicon: {
url: './path/to/tiny-image.jpg'
}
})🔔 Mention
// --- Regular mention
sock.sendMessage(jid, {
text: '👋🏻 Hello @628123456789',
mentions: ['[email protected]']
}, {
quoted: message
})
// --- Mention all
sock.sendMessage(jid, {
text: '👋🏻 Hello @all',
mentionAll: true
}, {
quoted: message
})😁 Reaction
sock.sendMessage(jid, {
react: {
key: message.key,
text: '✨'
}
}, {
quoted: message
})📌 Pin Message
sock.sendMessage(jid, {
pin: message.key,
time: 86400, // --- Set the value in seconds: 86400 (1d), 604800 (7d), or 2592000 (30d)
type: 1 // --- Or 0 to remove
}, {
quoted: message
})➡️ Forward Message
sock.sendMessage(jid, {
forward: message,
force: true // --- Optional
})👤 Contact
const vcard = 'BEGIN:VCARD\n'
+ 'VERSION:3.0\n'
+ 'FN:Melody\n'
+ 'ORG:Waitress;\n'
+ 'TEL;type=CELL;type=VOICE;waid=628123456789:+62 8123 4567 89\n'
+ 'END:VCARD'
sock.sendMessage(jid, {
contacts: {
displayName: 'Melody',
contacts: [
{ vcard }
]
}
}, {
quoted: message
})📍 Location
sock.sendMessage(jid, {
location: {
degreesLatitude: 24.121231,
degreesLongitude: 55.1121221,
name: '👋🏻 I am here'
}
}, {
quoted: message
})🗓️ Event
sock.sendMessage(jid, {
event: {
name: '🎶 Meet & Mingle Party',
description: 'Meet & Mingle Party is a fun, casual gathering to connect, chat, and build new relationships within the community.',
call: 'audio', // --- Or "video", this field is optional
startDate: new Date(Date.now() + 3600000),
endDate: new Date(Date.now() + 28800000),
isCancelled: false, // --- Optional
isScheduleCall: false, // --- Optional
extraGuestsAllowed: false, // --- Optional
location: {
name: 'Jakarta',
degreesLatitude: -6.2,
degreesLongitude: 106.8
}
}
}, {
quoted: message
})👥 Group Invite
const inviteCode = groupUrl
.split('chat.whatsapp.com/')[1]
?.split('?')[0]
const groupJid = '[email protected]'
const groupName = '@itsmelody/Baileys'
sock.sendMessage(jid, {
groupInvite: {
inviteCode,
inviteExpiration: Date.now() + 86400000,
text: '👋🏻 Hello, we invite you to join our group.',
jid: groupJid,
subject: groupName,
}
}, {
quoted: message
})🛍️ Product
import { randomUUID } from 'crypto'
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
body: '👋🏻 Check my product here!',
footer: '@itsmelody/Baileys',
product: {
currencyCode: 'IDR',
description: '🛍️ Interesting product!',
priceAmount1000: 70_000_000,
productId: randomUUID(),
productImageCount: 1,
salePriceAmount1000: 65_000_000,
signedUrl: 'https://github.com/Melody-Xz/Baileys',
title: '📦 Starseed (Premium)',
url: 'https://github.com/Melody-Xz/Baileys'
},
businessOwnerJid: '[email protected]'
})📊 Poll
// --- Regular poll message
sock.sendMessage(jid, {
poll: {
name: '🔥 Voting time',
values: ['Yes', 'No'],
selectableCount: 1,
toAnnouncementGroup: false
}
}, {
quoted: message
})
// --- Quiz (only for newsletter)
sock.sendMessage('1211111111111@newsletter', {
poll: {
name: '🔥 Quiz',
values: ['Yes', 'No'],
correctAnswer: 'Yes',
pollType: 1
}
}, {
quoted: message
})
// --- Poll result
sock.sendMessage(jid, {
pollResult: {
name: '📝 Poll Result',
votes: [{
name: 'Nice',
voteCount: 10
}, {
name: 'Nah',
voteCount: 2
}],
pollType: 0 // Or 1 for quiz
}
}, {
quoted: message
})
// --- Poll update
sock.sendMessage(jid, {
pollUpdate: {
metadata: {},
key: message.key,
vote: {
enclv: /* <Buffer> */,
encPayload: /* <Buffer> */
}
}
}, {
quoted: message
})💭 Button Response
// --- Using buttonsResponseMessage
sock.sendMessage(jid, {
type: 'plain',
buttonReply: {
id: '#Menu',
displayText: '✨ Interesting Menu'
}
}, {
quoted: message
})
// --- Using interactiveResponseMessage
sock.sendMessage(jid, {
flowReply: {
format: 0,
text: '💭 Response',
name: 'menu_options',
paramsJson: JSON.stringify({
id: '#Menu',
description: '✨ Interesting Menu'
})
}
}, {
quoted: message
})
// --- Using listResponseMessage
sock.sendMessage(jid, {
listReply: {
title: '📄 See More',
description: '✨ Interesting Menu',
id: '#Menu'
}
}, {
quoted: message
})
// --- Using templateButtonReplyMessage
sock.sendMessage(jid, {
type: 'template',
buttonReply: {
id: '#Menu',
displayText: '✨ Interesting Menu',
index: 1
}
}, {
quoted: message
})sock.sendMessage(jid, {
richResponse: [{
text: 'Example Usage',
}, {
language: 'javascript',
code: [{
highlightType: 0,
codeContent: 'console.log("Hello, World!")'
}]
}, {
text: 'Pretty simple, right?\n'
}, {
text: 'Comparison between Node.js, Bun, and Deno',
}, {
title: 'Runtime Comparison',
table: [{
isHeading: true,
items: ['', 'Node.js', 'Bun', 'Deno']
}, {
isHeading: false,
items: ['Engine', 'V8 (C++)', 'JavaScriptCore (C++)', 'V8 (C++)']
}, {
isHeading: false,
items: ['Performance', '4/5', '5/5', '4/5']
}]
}, {
text: 'Does this help clarify the differences?'
}]
})[!TIP] You can easily add syntax highlighting by importing
tokenizeCodedirectly from Baileys.
import { tokenizeCode } from '@itsmelody/Baileys'
const language = 'javascript'
const code = 'console.log("Hello, World!")'
sock.sendMessage(jid, {
richResponse: [{
text: 'Example Usage',
}, {
language,
code: tokenizeCode(code, language)
}, {
text: 'Pretty simple, right?'
}]
})🧾 Message with Code Block
[!NOTE] This feature already includes a built-in tokenizer.
sock.sendMessage(jid, {
headerText: '## Example Usage',
contentText: '---',
code: 'console.log("Hello, World!")',
language: 'javascript',
footerText: 'Pretty simple, right?'
})🌏 Message with Inline Entities
sock.sendMessage(jid, {
headerText: '## Check Out!',
contentText: '---',
links: [{
text: '1. Google',
title: 'Popular Search Engine',
url: 'https://www.google.com/'
}, {
text: '2. YouTube',
title: 'Popular Streaming Platform',
url: 'https://www.youtube.com/'
}, {
text: '3. Modded Baileys',
title: 'Underrated Baileys Fork',
url: 'https://github.com/Melody-Xz/Baileys'
}],
footerText: '---'
})📋 Message with Table
sock.sendMessage(jid, {
headerText: '## Comparison between Node.js, Bun, and Deno',
contentText: '---',
title: 'Runtime Comparison',
table: [
['', 'Node.js', 'Bun', 'Deno'],
['Engine', 'V8 (C++)', 'JavaScriptCore (C++)', 'V8 (C++)'],
['Performance', '4/5', '5/5', '4/5']
],
noHeading: false, // --- Optional
footerText: 'Does this help clarify the differences?'
})🎞️ Status Mention
sock.sendMessage([jidA, jidB, jidC], {
text: 'Hello! 👋🏻'
})📁 Sending Media Messages
[!NOTE] For media messages, you can pass a
Bufferdirectly, or an object with either{ stream: Readable }or{ url: string }(local file path or HTTP/HTTPS URL).
🖼️ Image
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '🔥 Superb'
}, {
quoted: message
})🎥 Video
sock.sendMessage(jid, {
video: {
url: './path/to/video.mp4'
},
gifPlayback: false, // --- Set true if you want to send video as GIF
ptv: false, // --- Set true if you want to send video as PTV
caption: '🔥 Superb'
}, {
quoted: message
})📃 Sticker
sock.sendMessage(jid, {
sticker: {
url: './path/to/sticker.webp'
}
}, {
quoted: message
})💽 Audio
sock.sendMessage(jid, {
audio: {
url: './path/to/audio.mp3'
},
ptt: false, // --- Set true if you want to send audio as Voice Note
}, {
quoted: message
})🗂️ Document
sock.sendMessage(jid, {
document: {
url: './path/to/document.pdf'
},
mimetype: 'application/pdf',
caption: '✨ My work!'
}, {
quoted: message
})🖼️ Album (Image & Video)
sock.sendMessage(jid, {
album: [{
image: {
url: './path/to/image.jpg'
},
caption: '1st image'
}, {
video: {
url: './path/to/video.mp4'
},
caption: '1st video'
}, {
image: {
url: './path/to/image.jpg'
},
caption: '2nd image'
}, {
video: {
url: './path/to/video.mp4'
},
caption: '2nd video'
}]
}, {
quoted: message
})📦 Sticker Pack
[!IMPORTANT] If
sharpor@napi-rs/imageis not installed, thecoverandstickersmust already be in WebP format.
sock.sendMessage(jid, {
cover: {
url: './path/to/image.webp'
},
stickers: [{
data: {
url: './path/to/image.webp'
}
}, {
data: {
url: './path/to/image.webp'
}
}, {
data: {
url: './path/to/image.webp'
}
}],
name: '📦 My Sticker Pack',
publisher: 'Melody',
description: '@itsmelody/Baileys'
}, {
quoted: message
})👉🏻 Sending Interactive Messages
1️⃣ Buttons
// --- Regular buttons message
sock.sendMessage(jid, {
text: '👆🏻 Buttons!',
footer: '@itsmelody/Baileys',
buttons: [{
text: '👋🏻 SignUp',
id: '#SignUp'
}]
}, {
quoted: message
})
// --- Buttons with Media & Native Flow
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '👆🏻 Buttons and Native Flow!',
footer: '@itsmelody/Baileys',
buttons: [{
text: '👋🏻 Rating',
id: '#Rating'
}, {
text: '📋 Select',
sections: [{
title: '✨ Section 1',
rows: [{
header: '',
title: '💭 Secret Ingredient',
description: '',
id: '#SecretIngredient'
}]
}, {
title: '✨ Section 2',
highlight_label: '🔥 Popular',
rows: [{
header: '',
title: '🏷️ Coupon',
description: '',
id: '#CouponCode'
}]
}]
}]
}, {
quoted: message
})2️⃣ List
[!NOTE] It only works in private chat (
@s.whatsapp.net).
sock.sendMessage(jid, {
text: '📋 List!',
footer: '@itsmelody/Baileys',
buttonText: '📋 Select',
title: '👋🏻 Hello',
sections: [{
title: '🚀 Menu 1',
rows: [{
title: '✨ AI',
description: '',
rowId: '#AI'
}]
}, {
title: '🌱 Menu 2',
rows: [{
title: '🔍 Search',
description: '',
rowId: '#Search'
}]
}]
}, {
quoted: message
})3️⃣ Interactive
// --- Native Flow
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '🗄️️ Interactive!',
footer: '@itsmelody/Baileys',
optionText: '👉🏻 Select Options', // --- Optional, wrap all native flow into a single list
optionTitle: '📄 Select Options', // --- Optional
offerText: '🏷️ Newest Coupon!', // --- Optional, add an offer into message
offerCode: '@itsmelody/Baileys', // --- Optional
offerUrl: 'https://github.com/Melody-Xz/Baileys', // --- Optional
offerExpiration: Date.now() + 3_600_000, // --- Optional
nativeFlow: [{
text: '👋🏻 Greeting',
id: '#Greeting',
icon: 'review' // --- Optional
}, {
text: '📞 Call',
call: '628123456789'
}, {
text: '📋 Copy',
copy: '@itsmelody/Baileys'
}, {
text: '🌐 Source',
url: 'https://github.com/Melody-Xz/Baileys',
useWebview: true // --- Optional
}, {
text: '📋 Select',
sections: [{
title: '✨ Section 1',
rows: [{
header: '',
title: '🏷️ Coupon',
description: '',
id: '#CouponCode'
}]
}, {
title: '✨ Section 2',
highlight_label: '🔥 Popular',
rows: [{
header: '',
title: '💭 Secret Ingredient',
description: '',
id: '#SecretIngredient'
}]
}],
icon: 'default' // --- Optional
}],
interactiveAsTemplate: false, // --- Optional, wrap the interactive message into a template
}, {
quoted: message
})
// --- Carousel & Native Flow
sock.sendMessage(jid, {
text: '🗂️ Interactive with Carousel!',
footer: '@itsmelody/Baileys',
cards: [{
image: {
url: './path/to/image.jpg'
},
caption: '🖼️ Image 1',
footer: '🏷️️ Pinterest',
nativeFlow: [{
text: '🌐 Source',
url: 'https://github.com/Melody-Xz/Baileys',
useWebview: true
}]
}, {
image: {
url: './path/to/image.jpg'
},
caption: '🖼️ Image 2',
footer: '🏷️ Pinterest',
offerText: '🏷️ New Coupon!',
offerCode: '@itsmelody/Baileys',
offerUrl: 'https://github.com/Melody-Xz/Baileys',
offerExpiration: Date.now() + 3_600_000,
nativeFlow: [{
text: '🌐 Source',
url: 'https://github.com/Melody-Xz/Baileys'
}]
}, {
image: {
url: './path/to/image.jpg'
},
caption: '🖼️ Image 3',
footer: '🏷️ Pinterest',
optionText: '👉🏻 Select Options',
optionTitle: '👉🏻 Select Options',
offerText: '🏷️ New Coupon!',
offerCode: '@itsmelody/Baileys',
offerUrl: 'https://github.com/Melody-Xz/Baileys',
offerExpiration: Date.now() + 3_600_000,
nativeFlow: [{
text: '🛒 Product',
id: '#Product',
icon: 'default'
}, {
text: '🌐 Source',
url: 'https://github.com/Melody-Xz/Baileys'
}]
}]
}, {
quoted: message
})4️⃣ Hydrated Template
sock.sendMessage(jid, {
title: '👋🏻 Hello',
image: {
url: './path/to/image.jpg'
},
caption: '🫙 Template!',
footer: '@itsmelody/Baileys',
templateButtons: [{
text: '👉🏻 Tap Here',
id: '#Order'
}, {
text: '🌐 Source',
url: 'https://github.com/Melody-Xz/Baileys'
}, {
text: '📞 Call',
call: '628123456789'
}]
}, {
quoted: message
})💳 Sending Payment Messages
1️⃣ Invite Payment
sock.sendMessage(jid, {
paymentInviteServiceType: 3 // 1, 2, or 3
})2️⃣ Invoice
[!NOTE] Invoice message are not supported yet.
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
invoiceNote: '🏷️ Invoice'
})3️⃣ Order
sock.sendMessage(chat, {
orderText: '🛍️ Order',
thumbnail: fs.readFileSync('./path/to/image.jpg') // --- Must in buffer format
}, {
quoted: message
})4️⃣ Request Payment
sock.sendMessage(jid, {
text: '💳 Request Payment',
requestPaymentFrom: '[email protected]'
})👁️ Other Message Options
1️⃣ AI Icon
[!NOTE] It only works in private chat (
@s.whatsapp.net).
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '🤖 With AI icon!',
ai: true
}, {
quoted: message
})2️⃣ Ephemeral
[!NOTE] Wrap message into
ephemeralMessage
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '👁️ Ephemeral',
ephemeral: true
})3️⃣ External Ad Reply
[!NOTE] Add an ad thumbnail to messages (may not be displayed on some WhatsApp versions).
sock.sendMessage(jid, {
text: '📰 External Ad Reply',
externalAdReply: {
title: '📝 Did you know?',
body: '❓ I dont know',
thumbnail: fs.readFileSync('./path/to/image.jpg'), // --- Must in buffer format
largeThumbnail: false, // --- Or true for bigger thumbnail
url: 'https://github.com/Melody-Xz/Baileys' // --- Optional, used for WhatsApp internal thumbnail caching and direct URL
}
}, {
quoted: message
})4️⃣ Group Status
[!NOTE] It only works in group chat (
@g.us)
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '👥 Group Status!',
groupStatus: true
})5️⃣ Raw
sock.sendMessage(jid, {
extendedTextMessage: {
text: '📃 Built manually from scratch using the raw WhatsApp proto structure',
contextInfo: {
externalAdReply: {
title: '@itsmelody/Baileys',
thumbnail: fs.readFileSync('./path/to/image.jpg'),
sourceApp: 'whatsapp',
showAdAttribution: true,
mediaType: 1
}
}
},
raw: true
}, {
quoted: message
})6️⃣ Secure Meta Service Label
sock.sendMessage(jid, {
text: '🏷️ Just a label!',
secureMetaServiceLabel: true
})7️⃣ View Once
[!NOTE] Wrap message into
viewOnceMessage
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '👁️ View Once',
viewOnce: true
})8️⃣ View Once V2
[!NOTE] Wrap message into
viewOnceMessageV2
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '👁️ View Once V2',
viewOnceV2: true
})9️⃣ View Once V2 Extension
[!NOTE] Wrap message into
viewOnceMessageV2Extension
sock.sendMessage(jid, {
image: {
url: './path/to/image.jpg'
},
caption: '👁️ View Once V2 Extension',
viewOnceV2Extension: true
})♻️ Modify Messages
🗑️ Delete Messages
sock.sendMessage(jid, {
delete: message.key
})✏️ Edit Messages
// --- Edit plain text
sock.sendMessage(jid, {
text: '✨ I mean, nice!',
edit: message.key
})
// --- Edit media messages caption
sock.sendMessage(jid, {
caption: '✨ I mean, here is the image!',
edit: message.key
})🧰 Additional Contents
🏷️ Find User ID (JID|PN/LID)
[!NOTE] The ID must contain numbers only (no +, (), or -) and must include the country code with WhatsApp ID format.
// --- PN (Phone Number)
const phoneNumber = '[email protected]'
const ids = await sock.findUserId(phoneNumber)
console.log('🏷️ Got user ID', ':', ids)
// --- LID (Local Identifier)
const lid = '43411111111111@lid'
const ids = await sock.findUserId(lid)
console.log('🏷️ Got user ID', ':', ids)
// --- Output
// {
// phoneNumber: '[email protected]',
// lid: '43411111111111@lid'
// }
// --- Output when failed
// {
// phoneNumber: '[email protected]',
// lid: 'id-not-found'
// }
// --- Same output shape regardless of input type🔑 Request Custom Pairing Code
[!NOTE] The phone number must contain numbers only (no +, (), or -) and must include the country code.
const phoneNumber = '6281111111111'
const customPairingCode = 'STARFALL'
await sock.requestPairingCode(phoneNumber, customPairingCode)
console.log('🔗 Pairing code', ':', customPairingCode)🖼️ Image Processing
[!NOTE] Automatically use available image processing library:
sharp,@napi-rs/image, orjimp
import { getImageProcessingLibrary } from '@itsmelody/Baileys'
import { readFile } from 'fs/promises'
const lib = await getImageProcessingLibrary()
const bufferOrFilePath = './path/to/image.jpg'
const width = 512
let output
// --- If sharp installed
if (lib.sharp?.default) {
const img = lib.sharp.default(bufferOrFilePath)
output = await img.resize(width)
.jpeg({ quality: 80 })
.toBuffer()
}
// --- If @napi-rs/image installed
else if (lib.image?.Transformer) {
// --- Must in buffer format
const inputBuffer = Buffer.isBuffer(bufferOrFilePath)
? bufferOrFilePath
: await readFile(bufferOrFilePath)
const img = new lib.image.Transformer(inputBuffer)
output = await img.resize(width, undefined, 0)
.jpeg(50)
}
// --- If jimp installed
else if (lib.jimp?.Jimp) {
const img = await lib.jimp.Jimp.read(bufferOrFilePath)
output = await img
.resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
.getBuffer('image/jpeg', { quality: 50 })
}
// --- Fallback
else {
throw new Error('No image processing available')
}
console.log('✅ Process completed!')
console.dir(output, { depth: null })📣 Newsletter Management
// --- Create a new one
sock.newsletterCreate('@itsmelody/Baileys', '📣 Fresh updates weekly')
// --- Get info
const metadata = sock.newsletterMetadata('1231111111111@newsletter')
console.dir(metadata, { depth: null })
// --- Get subscribers count
const subscribers = await sock.newsletterSubscribers('1231111111111@newsletter')
console.dir(subscribers, { depth: null })
// --- Follow and Unfollow
sock.newsletterFollow('1231111111111@newsletter')
sock.newsletterUnfollow('1231111111111@newsletter')
// --- Mute and Unmute
sock.newsletterMute('1231111111111@newsletter')
sock.newsletterUnmute('1231111111111@newsletter')
// --- Demote admin
sock.newsletterDemote('1231111111111@newsletter', '[email protected]')
// --- Change owner
sock.newsletterChangeOwner('1231111111111@newsletter', '[email protected]')
// --- Update newsletter
sock.newsletterUpdate('1231111111111@newsletter', { name: '@itsmelody/Baileys' })
// --- Change name
sock.newsletterUpdateName('1231111111111@newsletter', '📦 @itsmelody/Baileys')
// --- Change description
sock.newsletterUpdateDescription('1231111111111@newsletter', '📣 Fresh updates weekly')
// --- Change photo
sock.newsletterUpdatePicture('1231111111111@newsletter', {
url: 'path/to/image.jpg'
})
// --- Remove photo
sock.newsletterRemovePicture('1231111111111@newsletter')
// --- React to a message
sock.newsletterReactMessage('1231111111111@newsletter', '100', '💛')
// --- Get admin count
const count = await sock.newsletterAdminCount('1231111111111@newsletter')
// --- Get all subscribed newsletters
const newsletters = await sock.newsletterSubscribed()
console.dir(newsletters, { depth: null })
// --- Fetch newsletter messages
const messages = sock.newsletterFetchMessages('jid', '1231111111111@newsletter', 50, 0, 0)
console.dir(messages, { depth: null })
// --- Delete newsletter
sock.newsletterDelete('1231111111111@newsletter')👥 Group Management
// --- Create a new one and add participants using their JIDs
const group = sock.groupCreate('@itsmelody/Baileys', ['[email protected]'])
console.dir(group, { depth: null })
// --- Get info
const metadata = await sock.groupMetadata(jid)
console.dir(metadata, { depth: null })
// --- Get group invite code
sock.groupInviteCode(jid)
// --- Revoke invite link
sock.groupRevokeInvite(jid)
// --- Accept group invite
sock.groupAcceptInvite(inviteCode)
// --- Leave group
sock.groupLeave(jid)
// --- Add participants
sock.groupParticipantsUpdate(jid, ['[email protected]'], 'add')
// --- Remove participants
sock.groupParticipantsUpdate(jid, ['[email protected]'], 'remove')
// --- Promote to admin
sock.groupParticipantsUpdate(jid, ['[email protected]'], 'promote')
// --- Demote from admin
sock.groupParticipantsUpdate(jid, ['[email protected]'], 'demote')
// --- Accept join requests
sock.groupRequestParticipantsUpdate(jid, ['[email protected]'], 'approve')
// --- Change name
sock.groupUpdateSubject(jid, '📦 @itsmelody/Baileys')
// --- Change description
sock.groupUpdateDescription(jid, 'Updated description')
// --- Change photo
sock.updateProfilePicture(jid, {
url: 'path/to/image.jpg'
})
// --- Remove photo
sock.removeProfilePicture(jid)
// --- Set group as admin only for chatting
sock.groupSettingUpdate(jid, 'announcement')
// --- Set group as open to all for chatting
sock.groupSettingUpdate(jid, 'not_announcement')
// --- Set admin only can edit group info
sock.groupSettingUpdate(jid, 'locked')
// --- Set all participants can edit group info
sock.groupSettingUpdate(jid, 'unlocked')
// --- Set admin only can add participants
sock.groupMemberAddMode(jid, 'admin_add')
// --- Set all participants can add participants
sock.groupMemberAddMode(jid, 'all_member_add')
// --- Enable or disable temporary messages with seconds format
sock.groupToggleEphemeral(jid, 86400)
// --- Disable temporary messages
sock.groupToggleEphemeral(jid, 0)
// --- Enable or disable membership approval mode
sock.groupJoinApprovalMode(jid, 'on')
sock.groupJoinApprovalMode(jid, 'off')
// --- Get all groups metadata
const groups = await sock.groupFetchAllParticipating()
console.dir(groups, { depth: null })
// --- Get pending join requests
const requests = await sock.groupRequestParticipantsList(jid)
console.dir(requests, { depth: null })
// --- Get group info from link
const group = await sock.groupGetInviteInfo('https://chat.whatsapp.com/ABC123')
console.log('👥 Got group info from link', ':', group)
// --- Update bot member label
sock.updateMemberLabel(jid, '@itsmelody/Baileys')👤 Profile Management
// --- Get user profile picture
const url = await sock.profilePictureUrl(jid, 'image')
console.log('🖼️ Got user profile url', url)
// --- Update profile picture
sock.updateProfilePicture(jid, buffer)
sock.updateProfilePicture(jid, { url })
// --- Remove profile picture
sock.removeProfilePicture(jid)
// --- Update profile name
sock.updateProfileName('My Name')
// --- Update profile status
sock.updateProfileStatus('Available')
// --- Presence
sock.sendPresenceUpdate('available', jid)
sock.presenceSubscribe(jid)
// --- Read receipts
sock.readMessages([message.key])
sock.sendReceipt(jid, participant, [messageId], 'read')
// --- Block user
sock.updateBlockStatus(jid, 'block')
// --- Unblock user
sock.updateBlockStatus(jid, 'unblock')
// --- Fetch blocklist
const blocked = await sock.fetchBlocklist()
console.dir(blocked, { depth: null })
// --- Modify chats
sock.chatModify({
archive: true,
lastMessageOrig: message,
lastMessage: message
}, jid)
// --- Star messages
sock.star(jid, [{ id: messageId, fromMe: true }], true)
// --- Contact
sock.addOrEditContact(jid, { displayName: 'Starseed' })
sock.removeContact(jid)
// --- Label
sock.addChatLabel(jid, labelId)
sock.removeChatLabel(jid, labelId)
sock.addMessageLabel(jid, messageId, labelId)
// --- App state sync
sock.resyncAppState(['regular', 'critical_block'], true)
// --- Get business profile
const profile = await sock.getBusinessProfile(jid)
console.dir(profile, { depth: null })🔐 Privacy Management
// --- Update last seen privacy
sock.updateLastSeenPrivacy('all')
sock.updateLastSeenPrivacy('contacts')
sock.updateLastSeenPrivacy('contact_blacklist')
sock.updateLastSeenPrivacy('nobody')
// --- Update online privacy
sock.updateOnlinePrivacy('all')
sock.updateOnlinePrivacy('match_last_seen')
// --- Update profile picture privacy
sock.updateProfilePicturePrivacy('contacts')
// --- Update status privacy
sock.updateStatusPrivacy('contacts')
// --- Update read receipts privacy
sock.updateReadReceiptsPrivacy('all')
sock.updateReadReceiptsPrivacy('none')
// --- Update groups add privacy
sock.updateGroupsAddPrivacy('all')
sock.updateGroupsAddPrivacy('contacts')
// --- Update messages privacy
sock.updateMessagesPrivacy('all')
sock.updateMessagesPrivacy('contacts')
sock.updateMessagesPrivacy('nobody')
// --- Update call privacy
sock.updateCallPrivacy('everyone')
// --- Update default disappearing mode
sock.updateDefaultDisappearingMode(86400)
// --- Update link previews privacy
sock.updateDisableLinkPreviewsPrivacy(true)📡 Events
sock.ev.on('connection.update', (update) => {})
sock.ev.on('creds.update', (update) => {})
sock.ev.on('messaging-history.set', (update) => {})
sock.ev.on('messaging-history.status', (update) => {})
sock.ev.on('chats.upsert', (update) => {})
sock.ev.on('chats.update', (update) => {})
sock.ev.on('chats.delete', (update) => {})
sock.ev.on('chats.lock', (update) => {})
sock.ev.on('lid-mapping.update', (update) => {})
sock.ev.on('presence.update', (update) => {})
sock.ev.on('contacts.upsert', (update) => {})
sock.ev.on('contacts.update', (update) => {})
sock.ev.on('messages.delete', (update) => {})
sock.ev.on('messages.update', (update) => {})
sock.ev.on('messages.media-update', (update) => {})
sock.ev.on('messages.upsert', (update) => {})
sock.ev.on('messages.reaction', (update) => {})
sock.ev.on('message-receipt.update', (update) => {})
sock.ev.on('groups.upsert', (update) => {})
sock.ev.on('groups.update', (update) => {})
sock.ev.on('group-participants.update', (update) => {})
sock.ev.on('group.join-request', (update) => {})
sock.ev.on('group.member-tag.update', (update) => {})
sock.ev.on('blocklist.set', (update) => {})
sock.ev.on('blocklist.update', (update) => {})
sock.ev.on('call', (update) => {})
sock.ev.on('labels.edit', (update) => {})
sock.ev.on('labels.association', (update) => {})
sock.ev.on('newsletter.reaction', (update) => {})
sock.ev.on('newsletter.view', (update) => {})
sock.ev.on('newsletter-participants.update', (update) => {})
sock.ev.on('newsletter-settings.update', (update) => {})
sock.ev.on('settings.update', (update) => {})