npm.io
0.3.4 • Published yesterday

@pontasockets/baileys

Licence
MIT
Version
0.3.4
Deps
18
Size
39.4 MB
Vulns
0
Weekly
511
██████╗  ██████╗ ███╗   ██╗████████╗ █████╗ 
██╔══██╗██╔═══██╗████╗  ██║╚══██╔══╝██╔══██╗
██████╔╝██║   ██║██╔██╗ ██║   ██║   ███████║
██╔═══╝ ██║   ██║██║╚██╗██║   ██║   ██╔══██║
██║     ╚██████╔╝██║ ╚████║   ██║   ██║  ██║
╚═╝      ╚═════╝ ╚═╝  ╚═══╝   ╚═╝   ╚═╝  ╚═╝
███████╗ ██████╗  ██████╗██╗  ██╗███████╗████████╗███████╗
██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝██╔════╝
███████╗██║   ██║██║     █████╔╝ █████╗     ██║   ███████╗
╚════██║██║   ██║██║     ██╔═██╗ ██╔══╝     ██║   ╚════██║
███████║╚██████╔╝╚██████╗██║  ██╗███████╗   ██║   ███████║
╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝   ╚═╝   ╚══════╝

B A I L E Y S

WhatsApp Web API · Custom Fork · Node.js


npm license stars


Extended from @whiskeysockets/baileys · Packed with exclusive patches & features



Table of Contents


What's Different

This fork introduces targeted custom patches on top of the original Baileys library. Here's everything that's been changed or added:


# Patch Description
01 Code Block Message Send syntax-highlighted code via { code, language } — renders as AI bot message in WhatsApp
02 Table Message Send structured tables via { table: { title?, headers, rows } } — renders as rich table in WhatsApp
03 Rich Text Message Send styled text via { richText: '...' } — renders as AI bot markdown text in WhatsApp
04 Mixed Rich Message Combine text + code + table in one message via { items: [...] }
05 Inline Citation Message Send text with clickable footnote citations via { richResponse: [...] }
02 Custom Message ID All outgoing message IDs prefixed with PONTASOCKETS
03 LID Bug Fixes Full fix for participant, mentionedJid, sender, and group admin LID resolution
04 makeInMemoryStore Fix Corrected store behavior for stable session handling
05 Newsletter Support Full channel/newsletter create, follow, react, and admin management
06 AI Logo Message Support for AI bot avatar in message context
07 Logger Buffer Clear Prevents memory buildup from log buffers
08 LID → JID Conversion Auto-converts LID mentions, sender LID, and group member LID to JID

Features

✔  Multi-Device Support          ✔  End-to-End Encryption
✔  Real-Time Messaging           ✔  Session Persistence
✔  Code Block Messages           ✔  Newsletter Management
✔  Group & Channel Management    ✔  Rich Interactive Messages
✔  Poll, Album, Carousel         ✔  LID → JID Auto-Conversion

Installation

# Using npm
npm install @pontasockets/baileys

# Using yarn
yarn add @pontasockets/baileys

Quick Start

const {
  default: makeWASocket,
  useMultiFileAuthState,
} = require('@pontasockets/baileys');

async function start() {
  const { state, saveCreds } = await useMultiFileAuthState('./sessions')

  const sock = makeWASocket({
    printQRInTerminal: true,
    auth: state
  })

  sock.ev.on('creds.update', saveCreds)

  sock.ev.on('messages.upsert', ({ messages }) => {
    console.log('New message:', messages[0].message)
  })
}

start()

Documentation

Connecting Account
Connect with QR Code
const sock = makeWASocket({
  printQRInTerminal: true, // Display QR in terminal
  auth: state
})
Connect with Pairing Code
const sock = makeWASocket({
  printQRInTerminal: false,
  auth: state
})

if (!sock.authState.creds.registered) {
  const number = '62xxxx'

  // Default pairing code
  const code = await sock.requestPairingCode(number)

  // Custom 8-digit pairing code
  const customCode = await sock.requestPairingCode(number, 'PONTASOCKETS')

  console.log(code)
}

Handling Events
Basic Message Listener
sock.ev.on('messages.upsert', ({ messages }) => {
  const msg = messages[0]
  console.log('From:', msg.key.remoteJid)
  console.log('Content:', msg.message)
})
Decrypt Poll Votes
sock.ev.on('messages.update', (m) => {
  if (m.pollUpdates) {
    console.log('Poll vote received:', m.pollUpdates)
  }
})

Sending Messages
sock.sendMessage(jid, content, options?)
  ↳ jid     — Recipient JID (user or group)
  ↳ content — Message payload object
  ↳ options — Optional: { quoted, ephemeral, ... }
Text Message
// Simple text
await sock.sendMessage(jid, { text: 'Hello!' })

// With quoted reply
await sock.sendMessage(jid, { text: 'Reply!' }, { quoted: message })

// With link preview
await sock.sendMessage(jid, {
  text: 'Visit https://example.com',
  linkPreview: {
    'canonical-url': 'https://example.com',
    title: 'Example Domain',
    description: 'A demo website',
    jpegThumbnail: fs.readFileSync('preview.jpg')
  }
})
Code Block Message NEW

Renders as a syntax-highlighted code block in WhatsApp (AI bot style message)

Single Code Block

// JavaScript
await sock.sendMessage(jid, {
  code: 'console.log("Hello World")',
  language: 'javascript'
}, { quoted: message })

// Python
await sock.sendMessage(jid, {
  code: 'print("Hello World")',
  language: 'python'
}, { quoted: message })

// Bash / Terminal
await sock.sendMessage(jid, {
  code: stderr.trim(),
  language: 'bash'
}, { quoted: message })

Multiple Code Blocks in One Message

Gunakan key codes (array) untuk kirim lebih dari satu code block sekaligus dalam satu pesan

// 2 bahasa berbeda dalam 1 pesan
await sock.sendMessage(jid, {
  codes: [
    { code: 'console.log("Hello World")', language: 'javascript' },
    { code: 'print("Hello World")', language: 'python' }
  ]
}, { quoted: message })

// Input vs Output
await sock.sendMessage(jid, {
  codes: [
    { code: 'SELECT * FROM users WHERE id = 1;', language: 'sql' },
    { code: '{ "id": 1, "name": "Ponta", "role": "admin" }', language: 'json' }
  ]
}, { quoted: message })

// Banyak snippet sekaligus
await sock.sendMessage(jid, {
  codes: [
    { code: 'npm install @pontasockets/baileys', language: 'bash' },
    { code: 'import makeWASocket from "@pontasockets/baileys"', language: 'javascript' },
    { code: 'const sock = makeWASocket({ printQRInTerminal: true })', language: 'javascript' }
  ]
}, { quoted: message })

Note: Key code (single) dan codes (array) keduanya tetap support — tidak breaking change.

Supported Languages:

Language Keys
JavaScript javascript · js
TypeScript typescript · ts
Python python · py
Bash / Shell bash · sh · zsh
Go go · golang
Rust rust · rs
C c · h
C++ cpp · c++
C# csharp · cs
CSS css
HTML html
PowerShell powershell · ps1
CMD cmd · bat
SQL sql
JSON json
Table Message NEW

Renders as a structured table in WhatsApp (AI bot style rich message)

Simple Table

await sock.sendMessage(jid, {
  table: {
    title: 'Daftar User',
    headers: ['Name', 'Role', 'Status'],
    rows: [
      ['Ponta', 'Admin', 'Active'],
      ['Yue', 'Member', 'Idle'],
      ['Frieren', 'Guest', 'Offline']
    ]
  }
}, { quoted: message })

Table tanpa title

await sock.sendMessage(jid, {
  table: {
    headers: ['Command', 'Description'],
    rows: [
      ['.ping', 'Cek latency bot'],
      ['.info', 'Info bot'],
      ['.help', 'List semua command']
    ]
  }
}, { quoted: message })

Table tanpa header (data only)

await sock.sendMessage(jid, {
  table: {
    rows: [
      ['RAM', '512 MB'],
      ['CPU', '4 Core'],
      ['Uptime', '99.9%']
    ]
  }
}, { quoted: message })

Mixed: Table + Code Block dalam 1 pesan

Gunakan key items untuk gabungkan berbagai tipe dalam urutan bebas

await sock.sendMessage(jid, {
  items: [
    {
      table: {
        title: 'Query Result',
        headers: ['id', 'name', 'score'],
        rows: [
          ['1', 'Ponta', '98'],
          ['2', 'Yue', '87']
        ]
      }
    },
    { code: 'SELECT * FROM users ORDER BY score DESC', language: 'sql' }
  ]
}, { quoted: message })

Note: items array juga bisa diisi full code blocks saja (pengganti codes), atau full tables saja, atau campuran keduanya — bebas urutannya.

Rich Text Message NEW

Renders as AI bot markdown-style text dalam WhatsApp (gunakan richText, bukan text — supaya tidak konflik dengan text message biasa)

// Simple text
await sock.sendMessage(jid, {
  richText: 'Halo! Ini adalah pesan teks rich dari bot.'
}, { quoted: message })

// Markdown supported (bold, italic, code inline)
await sock.sendMessage(jid, {
  richText: '*Hasil eksekusi:*\nStatus: `success`\nWaktu: _120ms_'
}, { quoted: message })
Mixed Rich Message NEW

Gabungkan text, code block, dan table dalam urutan bebas dalam satu pesan menggunakan key items

Text → Code → Text

await sock.sendMessage(jid, {
  items: [
    { text: 'Contoh fungsi JavaScript:' },
    { code: 'function greet(name) {\n  return `Hello, ${name}!`\n}', language: 'javascript' },
    { text: 'Panggil fungsi di atas dengan `greet("Ponta")` untuk mendapat output `Hello, Ponta!`' }
  ]
}, { quoted: message })

Text → Code → Table

await sock.sendMessage(jid, {
  items: [
    { text: 'Query yang dijalankan:' },
    { code: 'SELECT id, name, score FROM users ORDER BY score DESC LIMIT 3', language: 'sql' },
    { text: 'Hasil:' },
    {
      table: {
        headers: ['id', 'name', 'score'],
        rows: [
          ['1', 'Ponta', '98'],
          ['2', 'Yue', '87'],
          ['3', 'Frieren', '75']
        ]
      }
    }
  ]
}, { quoted: message })

Full mixed

await sock.sendMessage(jid, {
  items: [
    { text: '*Dokumentasi Command `.eval`*' },
    { text: 'Syntax:' },
    { code: '.eval <kode javascript>', language: 'bash' },
    { text: 'Contoh penggunaan:' },
    { code: 'return 1 + 1', language: 'javascript' },
    { text: 'Supported types:' },
    {
      table: {
        headers: ['Type', 'Contoh'],
        rows: [
          ['Expression', '2 ** 10'],
          ['Statement', 'let x = 5; return x'],
          ['Async', 'await fetch(url)']
        ]
      }
    },
    { text: '_Hanya owner yang bisa menggunakan command ini._' }
  ]
}, { quoted: message })

Tipe yang valid di dalam items:

  • { text: 'string' } — teks / markdown
  • { code: 'string', language: 'string' } — code block
  • { table: { title?, headers?, rows } } — tabel
Inline Citation Message NEW

Render teks dengan citation/footnote yang bisa diklik — mirip jawaban AI WhatsApp yang punya referensi sumber

Format citation di teks: {{KEY}}N{{/KEY}}

  • KEY harus cocok dengan field key di inlineEntities
  • N adalah nomor urut footnote (¹²³ atau 1 2 3)

Single citation

await sock.sendMessage(jid, {
  richResponse: [
    {
      text: 'Koperasi Merah Putih adalah inisiatif pemerintah. {{SS_0}}¹{{/SS_0}} ',
      inlineEntities: [{
        key: 'SS_0',
        metadata: {
          reference_id: 1,
          reference_url: 'https://example.com',
          reference_title: 'Judul Sumber',
          reference_display_name: 'Sumber',
          sources: [{
            source_type: 'THIRD_PARTY',
            source_display_name: 'Sumber',
            source_subtitle: 'example.com',
            source_url: 'https://example.com'
          }],
          __typename: 'GenAISearchCitationItem'
        }
      }]
    }
  ]
}, { quoted: message })

Multi citation dalam satu teks

await sock.sendMessage(jid, {
  richResponse: [
    {
      text: 'Node.js {{SS_0}}¹{{/SS_0}} adalah runtime JavaScript. Dibuat oleh Ryan Dahl {{SS_1}}²{{/SS_1}} pada 2009.',
      inlineEntities: [
        {
          key: 'SS_0',
          metadata: {
            reference_id: 1,
            reference_url: 'https://nodejs.org',
            reference_title: 'Node.js Official',
            reference_display_name: 'nodejs.org',
            sources: [{
              source_type: 'THIRD_PARTY',
              source_display_name: 'nodejs.org',
              source_subtitle: 'nodejs.org',
              source_url: 'https://nodejs.org'
            }],
            __typename: 'GenAISearchCitationItem'
          }
        },
        {
          key: 'SS_1',
          metadata: {
            reference_id: 2,
            reference_url: 'https://wikipedia.org/wiki/Ryan_Dahl',
            reference_title: 'Ryan Dahl - Wikipedia',
            reference_display_name: 'Wikipedia',
            sources: [{
              source_type: 'THIRD_PARTY',
              source_display_name: 'Wikipedia',
              source_subtitle: 'wikipedia.org',
              source_url: 'https://wikipedia.org/wiki/Ryan_Dahl'
            }],
            __typename: 'GenAISearchCitationItem'
          }
        }
      ]
    }
  ]
}, { quoted: message })

Citation + Code Block dalam satu pesan

await sock.sendMessage(jid, {
  richResponse: [
    {
      text: 'Cara install Node.js {{SS_0}}¹{{/SS_0}}:',
      inlineEntities: [{
        key: 'SS_0',
        metadata: {
          reference_id: 1,
          reference_url: 'https://nodejs.org/en/download',
          reference_title: 'Download Node.js',
          reference_display_name: 'nodejs.org',
          sources: [{
            source_type: 'THIRD_PARTY',
            source_display_name: 'nodejs.org',
            source_subtitle: 'nodejs.org',
            source_url: 'https://nodejs.org/en/download'
          }],
          __typename: 'GenAISearchCitationItem'
        }
      }]
    },
    {
      code: 'curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -\napt-get install -y nodejs',
      language: 'bash'
    },
    {
      text: '_Verifikasi instalasi dengan_ `node --version`'
    }
  ]
}, { quoted: message })

Tipe yang valid di dalam richResponse:

  • { text, inlineEntities? } — teks / markdown dengan optional citation
  • { code, language } — code block
  • { table, title? } — tabel, table berupa [{ items: string[], isHeading?: bool }, ...]
Image Message
// From local file
await sock.sendMessage(jid, {
  image: fs.readFileSync('image.jpg'),
  caption: 'My cat!',
  mentions: ['1234567890@s.whatsapp.net']
})

// From URL
await sock.sendMessage(jid, {
  image: { url: 'https://example.com/image.jpg' },
  caption: 'Downloaded image'
})
Video Message
// From local file
await sock.sendMessage(jid, {
  video: fs.readFileSync('video.mp4'),
  caption: 'Funny clip!'
})

// View Once
await sock.sendMessage(jid, {
  video: fs.readFileSync('secret.mp4'),
  viewOnce: true
})
Audio / PTT Message
// Regular audio
await sock.sendMessage(jid, {
  audio: fs.readFileSync('audio.mp3'),
  ptt: false
})

// Push-to-talk voice note
await sock.sendMessage(jid, {
  audio: fs.readFileSync('voice.ogg'),
  ptt: true,
  waveform: [0, 1, 0, 1, 0]
})
Contact Message
const vcard = [
  'BEGIN:VCARD',
  'VERSION:3.0',
  'FN:Jeff Singh',
  'ORG:Ashoka Uni',
  'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890',
  'END:VCARD'
].join('\n')

await sock.sendMessage(jid, {
  contacts: {
    displayName: 'Jeff Singh',
    contacts: [{ vcard }]
  }
})
React to Message
// Add reaction
await sock.sendMessage(jid, {
  react: {
    text: '👍',
    key: message.key
  }
})

// Remove reaction (empty string)
await sock.sendMessage(jid, {
  react: {
    text: '',
    key: message.key
  }
})
Pin & Keep Message
Duration Seconds
24 Hours 86400
7 Days 604800
30 Days 2592000
// Pin a message
await sock.sendMessage(jid, {
  pin: { type: 1, time: 86400, key: message.key }
})

// Keep a message
await sock.sendMessage(jid, {
  keep: { key: message.key, type: 1 }
})
Location Message
// Static location
await sock.sendMessage(jid, {
  location: {
    degreesLatitude: 37.422,
    degreesLongitude: -122.084,
    name: 'Google HQ'
  }
})

// Live location
await sock.sendMessage(jid, {
  location: {
    degreesLatitude: 37.422,
    degreesLongitude: -122.084,
    accuracyInMeters: 10
  },
  live: true,
  caption: "I'm here!"
})
Call Message
// Voice call
await sock.sendMessage(jid, {
  call: { name: 'Call message', type: 1 }
})

// Video call
await sock.sendMessage(jid, {
  call: { name: 'Video call', type: 2 }
})
Poll Message
await sock.sendMessage(jid, {
  poll: {
    name: 'Favorite color?',
    values: ['Red', 'Blue', 'Green'],
    selectableCount: 1
  }
})
Album Message
await sock.sendAlbumMessage(jid, [
  {
    image: { url: 'https://example.com/image.jpg' },
    caption: 'First photo'
  },
  {
    video: { url: 'https://example.com/video.mp4' },
    caption: 'First video'
  }
], { quoted: message, delay: 3000 })
Group Invite Message
await sock.sendMessage(jid, {
  groupInvite: {
    jid: '123xxx@g.us',
    name: 'Group Name!',
    caption: 'Join my WhatsApp group!',
    code: 'xYz3yAtf...',
    expiration: 86400,
    jpegThumbnail: fs.readFileSync('preview.jpg')
  }
})
Interactive Messages
Shop Flow Message
await sock.sendMessage(jid, {
  text: 'Here is body message',
  title: 'Here is title',
  subtitle: 'Here is subtitle',
  footer: '© PONTASOCKETS Baileys',
  viewOnce: true,
  shop: {
    surface: 1,
    id: 'facebook_store_name'
  }
})
Native Flow Message
const buttons = [{
  name: 'quick_reply',
  buttonParamsJson: JSON.stringify({
    display_text: 'Quick Reply',
    id: '123'
  })
}]

await sock.sendMessage(jid, {
  text: 'Choose an option:',
  title: 'Title',
  footer: '© PONTASOCKETS Baileys',
  interactive: buttons
})
Carousel Message
await sock.sendMessage(jid, {
  text: 'Check out our collection!',
  title: 'Catalog',
  footer: '© PONTASOCKETS Baileys',
  cards: [{
    image: { url: 'https://example.com/image.jpg' },
    title: 'Product Name',
    body: 'Product description here',
    footer: '© PONTASOCKETS',
    buttons: [{
      name: 'quick_reply',
      buttonParamsJson: JSON.stringify({
        display_text: 'Select',
        id: '123'
      })
    }]
  }]
})
List Message
await sock.sendMessage(jid, {
  text: 'Choose from the menu:',
  sections: [{
    title: 'Food Menu',
    rows: [
      { title: 'Pizza', rowId: 'pizza', description: 'Cheese & pepperoni' },
      { title: 'Burger', rowId: 'burger', description: 'Double patty' }
    ]
  }],
  buttonText: 'Browse Menu'
})

Newsletter
Get Newsletter Metadata
// By invite code
const newsletter = await sock.newsletterMetadata('invite', '0029Vaf0HPMLdQeZsp3XRp2T')

// By JID
const newsletter = await sock.newsletterMetadata('jid', '120363282083849178@newsletter')

console.log(newsletter)
Follow / Unfollow / Mute / Unmute
const nlJid = '120363282083849178@newsletter'

await sock.newsletterFollow(nlJid)
await sock.newsletterUnfollow(nlJid)
await sock.newsletterMute(nlJid)
await sock.newsletterUnmute(nlJid)
Create Newsletter
const newsletter = await sock.newsletterCreate(
  'Newsletter Name',
  'Description here',
  { url: 'https://example.com/image.jpg' }
)

console.log('Created:', newsletter)
React to Newsletter Post
await sock.newsletterReactMessage(
  '120363282083849178@newsletter',
  '12',   // message server ID
  '🦖'    // emoji reaction
)

Groups
Create Group
const group = await sock.groupCreate('Group Title', [
  '1234567890@s.whatsapp.net',
  '0987654321@s.whatsapp.net'
])

console.log('Group JID:', group.id)
Group Settings
const jid = '123456789@g.us'

// Restrict: only admins can send messages
await sock.groupSettingUpdate(jid, 'announcement')

// Open: everyone can send messages
await sock.groupSettingUpdate(jid, 'not_announcement')

// Lock: only admins can edit group info
await sock.groupSettingUpdate(jid, 'locked')

// Unlock: everyone can edit group info
await sock.groupSettingUpdate(jid, 'unlocked')
Add / Remove / Promote / Demote
const participants = ['1234567890@s.whatsapp.net']

await sock.groupParticipantsUpdate(jid, participants, 'add')
await sock.groupParticipantsUpdate(jid, participants, 'remove')
await sock.groupParticipantsUpdate(jid, participants, 'promote')
await sock.groupParticipantsUpdate(jid, participants, 'demote')
Invite Link
// Get invite code
const code = await sock.groupInviteCode(jid)
console.log('Link: https://chat.whatsapp.com/' + code)

// Revoke and regenerate
const newCode = await sock.groupRevokeInvite(jid)
console.log('New link: https://chat.whatsapp.com/' + newCode)
Group Metadata
const metadata = await sock.groupMetadata(jid)

console.log('Name:', metadata.subject)
console.log('Description:', metadata.desc)
console.log('Participants:', metadata.participants.length)

Privacy
Update Profile Picture
// Set new picture
await sock.updateProfilePicture(jid, { url: 'https://example.com/image.jpg' })

// Remove picture
await sock.removeProfilePicture(jid)
Block / Unblock
await sock.updateBlockStatus(jid, 'block')
await sock.updateBlockStatus(jid, 'unblock')
Privacy Settings
// Last seen visibility
await sock.updateLastSeenPrivacy('all')         // "all" | "contacts" | "none"

// Online status visibility
await sock.updateOnlinePrivacy('all')           // "all" | "match_last_seen"

// Profile picture visibility
await sock.updateProfilePicturePrivacy('all')   // "all" | "contacts" | "none"

// Read receipts
await sock.updateReadReceiptsPrivacy('all')     // "all" | "none"

// Who can add to groups
await sock.updateGroupsAddPrivacy('all')        // "all" | "contacts"

// Default disappearing message timer
await sock.updateDefaultDisappearingMode(86400) // 0 to disable

Advanced
Debug Logging
const sock = makeWASocket({
  logger: { level: 'debug' }, // "fatal" | "error" | "warn" | "info" | "debug" | "trace"
  auth: state
})
Raw WebSocket Events
sock.ws.on('CB:presence', (json) => {
  console.log('Presence update:', json)
})

sock.ws.on('CB:edge_routing', (node) => {
  console.log('Edge routing:', node)
})

Contact

Platform Link
Telegram @pontact
Channel WhatsApp Channel
Rest API api.codeteam.web.id

Contributing

Contributions are welcome and appreciated!

  1. Fork the repository
  2. Create a feature branch → git checkout -b feat/your-feature
  3. Commit your changes → git commit -m "feat: add something awesome"
  4. Push to your branch → git push origin feat/your-feature
  5. Open a Pull Request with a clear description

All PRs are reviewed before merging.


License

This project is licensed for personal and non-commercial use only.

  • Personal use and modification allowed
  • Redistribution with attribution allowed
  • Commercial use strictly prohibited
  • Resale or rebranding prohibited

Disclaimer

This project is not affiliated with WhatsApp or Meta in any way. Use at your own risk and refer to WhatsApp's Terms of Service for compliance.


NPM · Baileys Wiki · Star this repo


Made with by PONTASOCKETS

Keywords