
Product
Introducing Socket Scanning for OpenVSX Extensions
Socket now scans OpenVSX extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.
@ajammm/baileys
Advanced tools
Baileys mod by ajammm - Updated to latest version with iOS & Apple device support, Anti-Call Protection, Rate Limiter & Auto Reconnect
https://www.npmjs.com/package/@ajammm/baileys
Library Bot WhatsApp berkinerja tinggi dengan dukungan multi-device penuh ā”ļø
Berikut adalah library WhatsApp berkinerja tinggi dengan implementasi TypeScript modern.
This project is based on yupra/baileys
Original Baileys library by WhiskeySockets
Modified and enhanced by AzzamDev Network (@ajammm)
Licensed under MIT License
Luncurkan bot WhatsApp Anda dengan library yang powerful dan modern! Dapatkan akses ke integrasi WhatsApp Web API terbaik.
Dukung pengembangan @ajammm/baileys
@ajammm/baileys adalah library berbasis TypeScript modern untuk integrasi WhatsApp Web API, dengan perbaikan untuk masalah @lid/@jid di grup.
š Modern & Cepat ā Berbasis TypeScript & WebSocket
š§ Perbaikan @lid & @jid ā perbaikan identitas grup
š± Multi-Device ā mendukung WhatsApp multi-device
š iOS & Apple Support ā dukungan penuh untuk perangkat Apple
š Enkripsi End-to-End ā komunikasi terenkripsi penuh
šØ Semua Tipe Pesan ā teks, media, polling, album, cerita, siaran
š Fitur Album Baru ā kirim album dengan gambar & video campuran
šÆ Mudah Digunakan ā API intuitif & fleksibel
ā ļø Penafian: Tidak berafiliasi dengan WhatsApp. Gunakan secara bertanggung jawab, hindari spam & aktivitas terlarang.
Stabil (Latest):
npm install @ajammm/baileys@latest
Versi Spesifik:
npm install @ajammm/baileys@2.1.2
Yarn:
yarn add @ajammm/baileys@latest
Import:
import makeWASocket from "@ajammm/baileys"
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from "@ajammm/baileys"
import { Boom } from "@hapi/boom"
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState("auth_info_baileys")
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
browser: ["@ajammm/baileys", "Desktop", "3.0"],
logger: P({ level: 'silent' }),
generateHighQualityLinkPreview: true,
defaultQueryTimeoutMs: 60000,
})
sock.ev.on("connection.update", ({ connection, lastDisconnect, qr }) => {
if (qr) {
console.log("š± Scan kode QR ini dengan WhatsApp Anda")
}
if (connection === "close") {
const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
console.log("ā Koneksi ditutup. Menyambung ulang:", shouldReconnect)
if (shouldReconnect) {
setTimeout(connectToWhatsApp, 3000)
}
} else if (connection === "open") {
console.log("ā
Berhasil terhubung ke WhatsApp!")
}
})
sock.ev.on("messages.upsert", async ({ messages }) => {
for (const m of messages) {
if (!m.message) continue
console.log("š© Pesan baru:", JSON.stringify(m, undefined, 2))
// Contoh balas otomatis
if (m.message.conversation === "hi") {
await sock.sendMessage(m.key.remoteJid!, {
text: "Halo! Saya didukung oleh @ajammm/baileys š¤"
})
}
}
})
sock.ev.on("creds.update", saveCreds)
return sock
}
connectToWhatsApp()
import makeWASocket from "@ajammm/baileys"
const sock = makeWASocket({
printQRInTerminal: true,
browser: ["@ajammm/baileys", "Chrome", "4.0.0"]
})
import makeWASocket, { useMultiFileAuthState } from "@ajammm/baileys"
async function connectWithPairingCode() {
const { state, saveCreds } = await useMultiFileAuthState("auth_info")
const sock = makeWASocket({
auth: state,
printQRInTerminal: false
})
if (!sock.authState.creds.registered) {
const phoneNumber = "6281234567890" // your phone number
const code = await sock.requestPairingCode(phoneNumber)
console.log("š Pairing Code:", code)
}
sock.ev.on("creds.update", saveCreds)
return sock
}
async function connectWithCustomPairing() {
const { state, saveCreds } = await useMultiFileAuthState("auth_info")
const sock = makeWASocket({
auth: state,
printQRInTerminal: false
})
if (!sock.authState.creds.registered) {
const phoneNumber = "6281234567890"
const customPair = "@ajammm/baileys25" // 8 characters
const code = await sock.requestPairingCode(phoneNumber, customPair)
console.log("š Custom Pairing Code:", code)
}
sock.ev.on("creds.update", saveCreds)
return sock
}
import { useMultiFileAuthState } from "@ajammm/baileys"
async function restoreSession() {
const { state, saveCreds } = await useMultiFileAuthState("./auth_session")
const sock = makeWASocket({
auth: state,
logger: P({ level: 'silent' })
})
sock.ev.on("creds.update", saveCreds)
return sock
}
Dukungan penuh untuk perangkat iOS dan Apple! Optimasi khusus untuk Safari dan macOS.
import makeWASocketIOS, { makeWASocketApple } from "@ajammm/baileys"
// Untuk perangkat iOS (iPhone/iPad)
const iosSock = makeWASocketIOS({
auth: state,
printQRInTerminal: true,
// Konfigurasi iOS otomatis diterapkan
})
// Untuk perangkat Apple (iOS/macOS)
const appleSock = makeWASocketApple({
auth: state,
printQRInTerminal: true,
// Konfigurasi Apple otomatis diterapkan
})
// Manual configuration untuk iOS
const customIOSSock = makeWASocket({
auth: state,
browser: ["iOS", "Safari", "17.4.1"], // Browser iOS
iosSupport: {
enabled: true,
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Mobile/15E148 Safari/604.1',
connectTimeoutMs: 30000,
keepAliveIntervalMs: 25000,
maxRetries: 3,
retryDelayMs: 500
}
})
// Auto-detection iOS device
const isIOSDevice = (typeof navigator !== 'undefined') && /iPad|iPhone|iPod/.test(navigator.userAgent)
// iOS-specific optimizations
const iosOptimizedSock = makeWASocketIOS({
iosSupport: {
enabled: true,
// Optimasi untuk iOS Safari
disableMediaPreview: true, // Disable preview untuk performa
iosWorkarounds: true, // Enable iOS workarounds
maxRetries: 3, // Retry lebih sedikit untuk iOS
retryDelayMs: 500 // Delay lebih cepat
}
})
// Apple device optimizations
const appleOptimizedSock = makeWASocketApple({
options: {
appleOptimizations: true, // Enable Apple optimizations
connectTimeoutMs: 25000, // Timeout lebih lama untuk Apple
keepAliveIntervalMs: 20000 // Keep alive lebih sering
}
})
// Browser configurations untuk berbagai perangkat Apple
const browserConfigs = {
// iOS Safari
iOS: ['iOS', 'Safari', '17.4.1'],
// iPad Safari
iPad: ['iPad', 'Safari', '17.4.1'],
// macOS Safari
macOS: ['Mac OS', 'Safari', '17.4.1'],
// Default Apple
apple: ['iOS', 'Safari', '17.4.1']
}
// Penggunaan
const iOSSock = makeWASocket({
browser: browserConfigs.iOS,
iosSupport: { enabled: true }
})
const macOSSock = makeWASocket({
browser: browserConfigs.macOS,
iosSupport: { enabled: true }
})
// iOS-optimized message sending
await iosSock.sendMessage(jid, {
text: "Hello from iOS optimized @ajammm/baileys! š",
// iOS akan otomatis menggunakan optimasi yang sesuai
})
// iOS-safe media sending
await iosSock.sendMessage(jid, {
image: { url: "https://example.com/image.jpg" },
caption: "iOS-compatible image š±",
// Media preview disabled untuk performa iOS
})
// iOS WebSocket handling
iosSock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
if (connection === 'open') {
console.log('ā
Connected with iOS optimizations!')
}
if (connection === 'close') {
// iOS-specific reconnection logic
console.log('š iOS WebSocket reconnecting...')
}
})
// Handle iOS Safari WebSocket limitations
const iosSafeSock = makeWASocketIOS({
iosSupport: {
enabled: true,
// Workarounds untuk iOS Safari
webSocketUrl: 'wss://web.whatsapp.com/ws/chat',
connectTimeoutMs: 30000, // Timeout lebih lama untuk iOS
keepAliveIntervalMs: 25000, // Keep alive lebih sering
retryDelayMs: 500, // Retry delay lebih cepat
maxRetries: 3 // Retry count lebih sedikit
}
})
// iOS memory management
iosSafeSock.ev.on('messages.upsert', async ({ messages }) => {
// iOS-optimized message processing
for (const message of messages) {
// Process messages dengan memory-efficient way
await processMessageIOS(message)
}
})
// iOS battery optimization
const batteryOptimizedSock = makeWASocketIOS({
options: {
iosBatteryOptimization: true, // Enable battery saving
reducePolling: true, // Reduce polling frequency
optimizeMedia: true // Optimize media handling
}
})
// Monitor iOS-specific metrics
iosSock.ev.on('connection.update', (update) => {
console.log('iOS Connection Status:', {
connection: update.connection,
isIOS: true,
iosOptimizations: update.iosOptimizations || false,
webSocketState: update.webSocketState
})
})
// iOS performance logging
setInterval(() => {
const iosStats = iosSock.getIOSStats()
console.log('š iOS Performance:', iosStats)
// {
// reconnectCount: 2,
// averageConnectTime: 1500,
// webSocketErrors: 0,
// batteryOptimized: true
// }
}, 30000)
// Handle iOS-specific errors
iosSock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
if (connection === 'close') {
const error = lastDisconnect?.error
if (error?.message?.includes('WebSocket')) {
console.log('š§ iOS WebSocket issue - applying workaround')
// Apply iOS WebSocket workaround
}
if (error?.message?.includes('Safari')) {
console.log('š Safari compatibility issue - using fallback')
// Use Safari-compatible configuration
}
}
})
// iOS debugging
const debugIOSSock = makeWASocketIOS({
logger: P({ level: 'debug' }),
iosSupport: {
enabled: true,
debugMode: true // Enable iOS-specific debugging
}
})
Dukungan iOS & Apple Device memastikan @ajammm/baileys bekerja optimal di semua perangkat Apple, dari iPhone hingga Mac! šš±
// Simple text
await sock.sendMessage("6281234567890@s.whatsapp.net", {
text: "Hello from @ajammm/baileys-baileys!"
})
// With formatting
await sock.sendMessage(jid, {
text: "*Bold* _italic_ ~strikethrough~ ```monospace```"
})
// Long text with preview
await sock.sendMessage(jid, {
text: "Check out this amazing library: https://github.com/@ajammm/baileys-network/baileys",
linkPreview: true
})
// Contoh menambahkan footer AI pada pesan
await sock.sendMessage(jid, {
text: "Ini pesan dengan footer AI",
footer: "⨠Powered by @ajammm/baileys AI "
})
await sock.sendMessage(jid, {
sock.ev.on("messages.upsert", async ({ messages }) => {
for (const message of messages) {
if (!message.message) continue
const sender = message.key.remoteJid
const messageType = Object.keys(message.message)[0]
console.log(`šØ Message from ${sender}: ${messageType}`)
switch (messageType) {
case 'conversation':
console.log("Text:", message.message.conversation)
break
case 'extendedTextMessage':
console.log("Extended text:", message.message.extendedTextMessage.text)
break
case 'imageMessage':
console.log("Image received with caption:", message.message.imageMessage.caption)
break
case 'videoMessage':
console.log("Video received")
break
}
}
})
// Quote reply
await sock.sendMessage(jid, {
text: "This is a quoted reply!"
}, {
quoted: message
})
// Reply with different content types
await sock.sendMessage(jid, {
image: { url: "./image.jpg" },
caption: "Replied with image"
}, { quoted: message })
// Single mention
await sock.sendMessage(jid, {
text: "Hello @6281234567890!",
mentions: ["6281234567890@s.whatsapp.net"]
})
// Multiple mentions
await sock.sendMessage(jid, {
text: "Meeting today @6281234567890 @6289876543210 at 2 PM",
mentions: [
"6281234567890@s.whatsapp.net",
"6289876543210@s.whatsapp.net"
]
})
// Mention all in group
const groupMetadata = await sock.groupMetadata(jid)
const participants = groupMetadata.participants.map(p => p.id)
await sock.sendMessage(jid, {
text: "Hello everyone! š",
mentions: participants
})
await sock.sendMessage(jid, {
text: "Welcome! Choose an option:",
footer: "Powered by @ajammm/baileys-baileys",
buttons: [
{ buttonId: "menu", buttonText: { displayText: "š Main Menu" }, type: 1 },
{ buttonId: "help", buttonText: { displayText: "ā Help" }, type: 1 },
{ buttonId: "about", buttonText: { displayText: "ā¹ļø About" }, type: 1 }
],
headerType: 1
})
await sock.sendMessage(jid, {
text: "š Choose your action:",
interactiveButtons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "ā” Quick Reply",
id: "quick_reply_1"
})
},
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "š Visit Website",
url: "https://azzamdev.my.id",
merchant_url: "https://azzamdev.my.id"
})
},
{
name: "cta_copy",
buttonParamsJson: JSON.stringify({
display_text: "š Copy Code",
id: "copy_code",
copy_code: "@ajammm/baileys2025"
})
},
{
name: "cta_call",
buttonParamsJson: JSON.stringify({
display_text: "š Call Support",
phone_number: "+6281234567890"
})
}
]
})
await sock.sendMessage(jid, {
text: "Select a service:",
buttonText: "View Options",
sections: [
{
title: "š§ Development Services",
rows: [
{ title: "WhatsApp Bot", description: "Custom WhatsApp automation", rowId: "service_bot" },
{ title: "Web Development", description: "Modern web applications", rowId: "service_web" },
{ title: "Mobile App", description: "iOS & Android apps", rowId: "service_mobile" }
]
},
{
title: "āļø Cloud Services",
rows: [
{ title: "Server Hosting", description: "High-performance servers", rowId: "service_hosting" },
{ title: "Database", description: "Managed databases", rowId: "service_database" },
{ title: "CDN", description: "Content delivery network", rowId: "service_cdn" }
]
}
]
})
await sock.sendMessage(jid, {
image: { url: "https://azzamdev.my.id/assets/banner.png" },
caption: "š Welcome to AzzamDev Services!\n\nHigh-performance solutions for modern businesses.",
footer: "AzzamDev Network Ā© 2025",
interactiveButtons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "š Get Started",
id: "get_started"
})
},
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "š Visit Panel",
url: "https://azzamdev.my.id"
})
}
]
})
// Kirim album dengan gambar dan video campuran
await sock.sendAlbumMessage(
jid,
[
{
image: { url: "https://example.jpg" }, // atau buffer
caption: "Halo Dunia",
},
{
video: { url: "https://example.mp4" }, // atau buffer
caption: "Video keren!",
},
{
image: { url: "./local-image.jpg" },
caption: "Gambar lokal",
}
],
{
quoted: message, // opsional: quote pesan
delay: 2000 // delay antar pesan dalam ms (default: 500ms)
}
)
// Minimal 2 media, maksimal sesuai batas WhatsApp
// Mendukung gambar dan video dalam satu album
// Setiap media bisa memiliki caption sendiri
// Send image from URL
await sock.sendMessage(jid, {
image: { url: "https://example.com/image.jpg" },
caption: "Beautiful sunset š
"
})
// Send image from buffer
import fs from 'fs'
const imageBuffer = fs.readFileSync('./local-image.png')
await sock.sendMessage(jid, {
image: imageBuffer,
caption: "Local image with caption"
})
// Send with view once
await sock.sendMessage(jid, {
image: { url: "./secret.jpg" },
caption: "This will disappear after viewing! šļø",
viewOnce: true
})
// Send as sticker
await sock.sendMessage(jid, {
sticker: { url: "./sticker.webp" }
})
// Video with caption
await sock.sendMessage(jid, {
video: { url: "https://example.com/video.mp4" },
caption: "Amazing video content! š¬",
jpegThumbnail: thumbnailBuffer // optional thumbnail
})
// GIF support
await sock.sendMessage(jid, {
video: { url: "./animation.gif" },
caption: "Animated GIF",
gifPlayback: true
})
// Video note (circular video)
await sock.sendMessage(jid, {
video: { url: "./video-note.mp4" },
videoNote: true
})
// Audio file
await sock.sendMessage(jid, {
audio: { url: "./music.mp3" },
mimetype: "audio/mp3",
fileName: "awesome-song.mp3"
})
// Voice note (PTT)
await sock.sendMessage(jid, {
audio: { url: "./voice-note.ogg" },
mimetype: "audio/ogg; codecs=opus",
ptt: true
})
// Audio with waveform
await sock.sendMessage(jid, {
audio: { url: "./audio.mp3" },
mimetype: "audio/mp3",
waveform: [0,1,2,3,4,5,6,7,8,9], // optional waveform
contextInfo: {
externalAdReply: {
title: "Now Playing",
body: "Artist - Song Title",
thumbnailUrl: "https://example.com/cover.jpg",
sourceUrl: "https://music-platform.com/song"
}
}
})
// Send document
await sock.sendMessage(jid, {
document: { url: "./document.pdf" },
mimetype: "application/pdf",
fileName: "important-document.pdf",
caption: "Please review this document š"
})
// Excel file
await sock.sendMessage(jid, {
document: { url: "./spreadsheet.xlsx" },
mimetype: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
fileName: "data-report.xlsx"
})
// Word document
await sock.sendMessage(jid, {
document: { url: "./report.docx" },
mimetype: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
fileName: "monthly-report.docx"
})
// Point location
await sock.sendMessage(jid, {
location: {
degreesLatitude: -6.2088,
degreesLongitude: 106.8456,
name: "Jakarta, Indonesia",
address: "Jakarta Special Capital Region, Indonesia"
}
})
// Live location (for 60 seconds)
await sock.sendMessage(jid, {
liveLocation: {
degreesLatitude: -6.2088,
degreesLongitude: 106.8456,
caption: "I'm here! š",
sequenceNumber: 1,
timeOffset: 60
}
})
// Single contact
await sock.sendMessage(jid, {
contacts: {
displayName: "John Doe",
contacts: [{
vcard: `BEGIN:VCARD
VERSION:3.0
FN:John Doe
ORG:@ajammm/baileys Network
TEL;type=CELL;type=VOICE;waid=6281234567890:+62 812-3456-7890
END:VCARD`
}]
}
})
// Multiple contacts
await sock.sendMessage(jid, {
contacts: {
displayName: "Team Contacts",
contacts: [
{
displayName: "John Doe",
vcard: "BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nTEL:+6281234567890\nEND:VCARD"
},
{
displayName: "Jane Smith",
vcard: "BEGIN:VCARD\nVERSION:3.0\nFN:Jane Smith\nTEL:+6289876543210\nEND:VCARD"
}
]
}
})
// Create group
const group = await sock.groupCreate("@ajammm/baileys Developers", [
"6281234567890@s.whatsapp.net",
"6289876543210@s.whatsapp.net"
])
console.log("ā
Group created:", group.id)
// Add participants
await sock.groupParticipantsUpdate(
group.id,
["6285555555555@s.whatsapp.net"],
"add"
)
// Remove participants
await sock.groupParticipantsUpdate(
group.id,
["6281234567890@s.whatsapp.net"],
"remove"
)
// Promote to admin
await sock.groupParticipantsUpdate(
group.id,
["6289876543210@s.whatsapp.net"],
"promote"
)
// Demote admin
await sock.groupParticipantsUpdate(
group.id,
["6289876543210@s.whatsapp.net"],
"demote"
)
// Update group name
await sock.groupUpdateSubject(group.id, "š @ajammm/baileys Dev Team")
// Update group description
await sock.groupUpdateDescription(group.id,
"Official developer group for AzzamDev Network projects.\n\n" +
"Rules:\n⢠Be respectful\n⢠Share knowledge\n⢠Have fun! š"
)
// Update group photo
const groupPhoto = fs.readFileSync('./group-photo.jpg')
await sock.updateProfilePicture(group.id, groupPhoto)
// Group settings
await sock.groupSettingUpdate(group.id, 'announcement') // Only admins can send
await sock.groupSettingUpdate(group.id, 'not_announcement') // Everyone can send
await sock.groupSettingUpdate(group.id, 'locked') // Only admins can edit info
await sock.groupSettingUpdate(group.id, 'unlocked') // Everyone can edit info
// Get group metadata
const groupInfo = await sock.groupMetadata(group.id)
console.log("Group Info:", {
name: groupInfo.subject,
description: groupInfo.desc,
participantCount: groupInfo.participants.length,
admins: groupInfo.participants.filter(p => p.admin).map(p => p.id)
})
// Get group participants
const participants = await sock.groupMetadata(group.id)
participants.participants.forEach(participant => {
console.log(`${participant.id} - ${participant.admin || 'member'}`)
})
// Leave group
await sock.groupLeave(group.id)
// Add reaction
await sock.sendMessage(jid, {
react: {
text: "ā¤ļø", // emoji
key: message.key
}
})
// Remove reaction
await sock.sendMessage(jid, {
react: {
text: "",
key: message.key
}
})
// Multiple reactions example
const reactions = ["š", "ā¤ļø", "š", "š®", "š¢", "š"]
const randomReaction = reactions[Math.floor(Math.random() * reactions.length)]
await sock.sendMessage(jid, {
react: {
text: randomReaction,
key: message.key
}
})
// Mark as read
await sock.readMessages([message.key])
// Send presence (typing, recording, etc.)
await sock.sendPresenceUpdate('composing', jid) // typing
await sock.sendPresenceUpdate('recording', jid) // recording audio
await sock.sendPresenceUpdate('paused', jid) // stopped typing
// Available/Unavailable
await sock.sendPresenceUpdate('available')
await sock.sendPresenceUpdate('unavailable')
// Last seen privacy
await sock.updateLastSeenPrivacy('all') // everyone can see
await sock.updateLastSeenPrivacy('contacts') // only contacts
await sock.updateLastSeenPrivacy('contact_blacklist') // contacts except...
await sock.updateLastSeenPrivacy('none') // nobody can see
// Online status privacy
await sock.updateOnlinePrivacy('all')
await sock.updateOnlinePrivacy('match_last_seen')
// Profile photo privacy
await sock.updateProfilePicturePrivacy('all')
await sock.updateProfilePicturePrivacy('contacts')
await sock.updateProfilePicturePrivacy('none')
// Status privacy
await sock.updateStatusPrivacy('all')
await sock.updateStatusPrivacy('contacts')
await sock.updateStatusPrivacy('contact_blacklist')
// Read receipts
await sock.updateReadReceiptsPrivacy('all')
await sock.updateReadReceiptsPrivacy('none')
// Groups add privacy
await sock.updateGroupsAddPrivacy('all')
await sock.updateGroupsAddPrivacy('contacts')
await sock.updateGroupsAddPrivacy('contact_blacklist')
// Block user
await sock.updateBlockStatus("6281234567890@s.whatsapp.net", "block")
// Unblock user
await sock.updateBlockStatus("6281234567890@s.whatsapp.net", "unblock")
// Get blocked list
const blockedUsers = await sock.fetchBlocklist()
console.log("Blocked users:", blockedUsers)
// Get profile picture URL
const ppUrl = await sock.profilePictureUrl("6281234567890@s.whatsapp.net", "image")
console.log("Profile picture:", ppUrl)
// Update your profile picture
const newProfilePic = fs.readFileSync('./my-new-photo.jpg')
await sock.updateProfilePicture(sock.user.id, newProfilePic)
// Update profile name
await sock.updateProfileName("@ajammm/baileys Bot")
// Update status/about
await sock.updateProfileStatus("Building the future with @ajammm/baileys š")
// Get user status
const userStatus = await sock.fetchStatus("6281234567890@s.whatsapp.net")
console.log("User status:", userStatus)
// Get business profile
const businessProfile = await sock.getBusinessProfile("6281234567890@s.whatsapp.net")
console.log("Business info:", businessProfile)
// Update business profile
await sock.updateBusinessProfile({
description: "We provide high-performance server solutions",
email: "business@azzamdev.my.id",
category: "Technology",
address: "Jakarta, Indonesia",
website: ["https://azzamdev.my.id"]
})
// Get message info (read receipts)
const messageInfo = await sock.messageInfo(jid, message.key.id)
console.log("Message info:", messageInfo)
// Search messages
const searchResults = await sock.searchMessages("hello", jid, 10, 0)
console.log("Search results:", searchResults)
// Get chat history
const messages = await sock.fetchMessageHistory(jid, 50, message.key)
console.log("Chat history:", messages)
import { makeInMemoryStore } from "@ajammm/baileys-baileys"
// Create store
const store = makeInMemoryStore({
logger: P({ level: 'silent' })
})
// Save/load store
store.readFromFile('./baileys_store.json')
setInterval(() => {
store.writeToFile('./baileys_store.json')
}, 10_000) // save every 10 seconds
// Bind store to socket
store.bind(sock.ev)
// Use store data
const chats = store.chats.all()
const messages = store.messages[jid]?.array || []
const contacts = store.contacts
import { proto } from "@ajammm/baileys-baileys"
class CustomStore {
constructor() {
this.chats = new Map()
this.messages = new Map()
this.contacts = new Map()
}
bind(ev) {
ev.on('chats.set', ({ chats }) => {
chats.forEach(chat => this.chats.set(chat.id, chat))
})
ev.on('messages.upsert', ({ messages }) => {
messages.forEach(msg => {
const jid = msg.key.remoteJid
if (!this.messages.has(jid)) {
this.messages.set(jid, [])
}
this.messages.get(jid).push(msg)
})
})
ev.on('contacts.set', ({ contacts }) => {
contacts.forEach(contact => {
this.contacts.set(contact.id, contact)
})
})
}
async saveToDatabase() {
// Save to your database
console.log("š¾ Saving to database...")
}
}
const customStore = new CustomStore()
customStore.bind(sock.ev)
// Retry mechanism
async function sendMessageWithRetry(jid, content, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await sock.sendMessage(jid, content)
} catch (error) {
console.log(`ā Attempt ${attempt} failed:`, error.message)
if (attempt === maxRetries) {
throw new Error(`Failed to send message after ${maxRetries} attempts: ${error.message}`)
}
// Exponential backoff
const delay = Math.pow(2, attempt) * 1000
console.log(`ā³ Waiting ${delay}ms before retry...`)
await new Promise(resolve => setTimeout(resolve, delay))
}
}
}
// Usage
try {
await sendMessageWithRetry(jid, { text: "Hello with retry logic!" })
console.log("ā
Message sent successfully")
} catch (error) {
console.error("ā Final send failed:", error.message)
}
let reconnectAttempts = 0
const maxReconnectAttempts = 5
sock.ev.on("connection.update", ({ connection, lastDisconnect }) => {
if (connection === "close") {
const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
if (shouldReconnect && reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000)
console.log(`š Reconnecting... (attempt ${reconnectAttempts}/${maxReconnectAttempts})`)
setTimeout(connectToWhatsApp, delay)
} else {
console.log("ā Max reconnection attempts reached or logged out")
process.exit(1)
}
} else if (connection === "open") {
reconnectAttempts = 0 // reset on successful connection
console.log("ā
Connected successfully!")
}
})
class MessageQueue {
constructor(sock) {
this.sock = sock
this.queue = []
this.isProcessing = false
this.delay = 2000 // 2 seconds between messages
}
add(jid, content) {
this.queue.push({ jid, content, timestamp: Date.now() })
this.process()
}
async process() {
if (this.isProcessing || this.queue.length === 0) return
this.isProcessing = true
while (this.queue.length > 0) {
const { jid, content } = this.queue.shift()
try {
await this.sock.sendMessage(jid, content)
console.log("ā
Message sent from queue")
} catch (error) {
console.error("ā Queue send failed:", error)
// Could re-add to queue or handle differently
}
// Wait before next message
await new Promise(resolve => setTimeout(resolve, this.delay))
}
this.isProcessing = false
}
}
// Usage
const messageQueue = new MessageQueue(sock)
messageQueue.add(jid, { text: "Queued message 1" })
messageQueue.add(jid, { text: "Queued message 2" })
class RateLimiter {
constructor(limit = 10, window = 60000) { // 10 messages per minute
this.limit = limit
this.window = window
this.requests = new Map()
}
canSend(jid) {
const now = Date.now()
const requests = this.requests.get(jid) || []
// Remove old requests outside the window
const validRequests = requests.filter(time => now - time < this.window)
this.requests.set(jid, validRequests)
return validRequests.length < this.limit
}
recordRequest(jid) {
const requests = this.requests.get(jid) || []
requests.push(Date.now())
this.requests.set(jid, requests)
}
}
const rateLimiter = new RateLimiter(15, 60000) // 15 messages per minute
// Usage in message handler
sock.ev.on("messages.upsert", async ({ messages }) => {
for (const message of messages) {
const jid = message.key.remoteJid
if (!rateLimiter.canSend(jid)) {
console.log(`š« Rate limit exceeded for ${jid}`)
continue
}
rateLimiter.recordRequest(jid)
// Process message...
}
})
Fitur eksklusif @ajammm/baileys untuk mencegah banned akibat spam pesan terlalu cepat!
const sock = makeWASocket({
// ... konfigurasi lainnya
rateLimiter: {
enabled: true, // Aktifkan/nonaktifkan rate limiter
maxMessagesPerMinute: 60, // Maksimal 60 pesan per menit (default)
delayBetweenMessages: 1000 // Delay 1 detik antar pesan (default)
}
})
// Rate limiter akan otomatis aktif pada semua pengiriman pesan
await sock.sendMessage(jid, { text: "Pesan dengan rate limiting!" })
// Untuk album pesan
await sock.sendAlbumMessage(jid, [
{ image: { url: "image1.jpg" }, caption: "Gambar 1" },
{ video: { url: "video1.mp4" }, caption: "Video 1" }
], {
delay: 2000 // Delay tambahan antar media album
})
// Cek status rate limiter saat ini
const status = sock.getRateLimiterStatus()
console.log("Rate Limiter Status:", status)
// Output: {
// enabled: true,
// maxMessagesPerMinute: 60,
// delayBetweenMessages: 1000,
// activeUsers: 5
// }
// Update konfigurasi rate limiter
sock.setRateLimiter({
maxMessagesPerMinute: 30, // Kurangi menjadi 30 pesan/menit
delayBetweenMessages: 2000 // Tambah delay menjadi 2 detik
})
// Nonaktifkan rate limiter sementara
sock.setRateLimiter({ enabled: false })
// Reset rate limiter untuk user tertentu
sock.resetRateLimiter("6281234567890@s.whatsapp.net")
// Reset semua rate limiter
sock.resetRateLimiter()
// Untuk broadcast kecil (aman & cepat)
const broadcastSock = makeWASocket({
rateLimiter: {
maxMessagesPerMinute: 120, // 120 pesan/menit
delayBetweenMessages: 500 // 0.5 detik delay
}
})
// Untuk broadcast besar (sangat aman)
const safeBroadcastSock = makeWASocket({
rateLimiter: {
maxMessagesPerMinute: 30, // 30 pesan/menit
delayBetweenMessages: 3000 // 3 detik delay
}
})
// Untuk bot interaktif (responsif)
const interactiveBotSock = makeWASocket({
rateLimiter: {
maxMessagesPerMinute: 200, // 200 pesan/menit
delayBetweenMessages: 200 // 0.2 detik delay
}
})
// Rate limiter akan memberikan log otomatis
// ā
Rate limit OK untuk user@domain
// š« Rate limit exceeded untuk user@domain, waiting 5000ms
// š Applying delay untuk user@domain: 1000ms
// š¾ Rate limiter updated: { enabled: true, maxMessagesPerMinute: 60, ... }
// Monitor penggunaan
setInterval(() => {
const status = sock.getRateLimiterStatus()
console.log(`š Active users: ${status.activeUsers}`)
}, 60000) // Cek setiap menit
Fitur Rate Limiter & Flood Protection ini adalah solusi lengkap untuk mengamankan bot WhatsApp Anda dari risiko banned dan memastikan pengiriman pesan yang stabil dan aman! š
Masalah: Error ini terjadi karena requestPairingCode() dipanggil sebelum koneksi WebSocket terbuka.
Solusi:
sock.ev.on("connection.update", async ({ connection, lastDisconnect, qr }) => {
if (connection === "close") {
const reasonCode = lastDisconnect?.error?.output?.statusCode
console.log(`Connection closed - Reason: ${reasonCode}`)
// Handle 405 Connection Failure
if (reasonCode === 405) {
console.log("Connection Failure (405) - will retry")
setTimeout(connectToWhatsApp, 3000)
}
} else if (connection === "open") {
console.log("ā
Berhasil terhubung ke WhatsApp!")
// ā
TUNGGU koneksi terbuka sebelum request pairing code
if (!sock.authState.creds.registered && !pairingAttempted) {
pairingAttempted = true
setTimeout(async () => {
try {
const code = await sock.requestPairingCode(phoneNumber)
console.log("š Pairing Code:", code)
} catch (error) {
console.error("ā Error:", error.message)
pairingAttempted = false // Reset untuk retry
setTimeout(() => connectToWhatsApp(), 10000)
}
}, 2000) // Tunggu 2 detik setelah koneksi open
}
}
})
Masalah: WhatsApp server menolak koneksi dengan reason code 405.
Solusi:
main-fixed.js yang sudah diperbaiki@ajammm/baileys@latestSolusi: Pastikan akun WhatsApp Anda sudah mengaktifkan multi-device di pengaturan.
Solusi: Update ke versi terbaru dan pastikan koneksi internet stabil.
Bot tetap jalan meskipun koneksi terputus! Auto login dari sesi terakhir tanpa scan ulang QR!
const sock = makeWASocket({
// ... konfigurasi lainnya
autoReconnect: {
enabled: true, // Aktifkan auto reconnect (default: true)
maxRetries: 10, // Maksimal percobaan reconnect (default: 10)
retryDelay: 5000, // Delay awal retry dalam ms (default: 5000)
maxRetryDelay: 30000 // Delay maksimal retry dalam ms (default: 30000)
}
})
// Auto reconnect aktif otomatis
const sock = makeWASocket({
auth: state,
autoReconnect: { enabled: true } // Default aktif
})
// Bot akan otomatis reconnect saat:
// - Koneksi internet terputus
// - Server WhatsApp down
// - Device sleep/wake
// - Network switching
// Monitor status koneksi
sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
if (connection === 'close') {
console.log('ā Koneksi terputus:', lastDisconnect?.error?.message)
} else if (connection === 'open') {
console.log('ā
Koneksi tersambung kembali!')
}
})
// Manual reconnect
await sock.reconnect()
// Cek status koneksi
const isConnected = sock.ws.isOpen
console.log('Status koneksi:', isConnected ? 'Terhubung' : 'Terputus')
// Force reconnect dengan konfigurasi baru
const newSock = makeWASocket({
auth: state,
autoReconnect: {
enabled: true,
maxRetries: 5,
retryDelay: 3000
}
})
// Untuk bot production (sangat reliable)
const productionBot = makeWASocket({
autoReconnect: {
enabled: true,
maxRetries: 20, // Banyak retry untuk reliability
retryDelay: 2000, // Retry cepat
maxRetryDelay: 60000 // Delay maksimal 1 menit
}
})
// Untuk bot development (cepat debug)
const devBot = makeWASocket({
autoReconnect: {
enabled: true,
maxRetries: 3, // Sedikit retry untuk debug
retryDelay: 1000, // Retry sangat cepat
maxRetryDelay: 5000 // Delay maksimal 5 detik
}
})
// Untuk bot low-resource (hemat resource)
const lowResourceBot = makeWASocket({
autoReconnect: {
enabled: true,
maxRetries: 5, // Retry sedang
retryDelay: 10000, // Delay lebih lama
maxRetryDelay: 120000 // Delay maksimal 2 menit
}
})
// Auto reconnect memberikan log otomatis
// š Connection closed, attempting to reconnect (1/10) in 5000ms...
// ā Auto reconnection failed, retrying...
// ā
Auto reconnection successful!
// š Connection restored
// Monitor dengan event listener
sock.ev.on('connection.update', (update) => {
console.log('Connection Update:', update)
// {
// connection: 'close' | 'open' | 'connecting',
// lastDisconnect: { error, date },
// qr: undefined
// }
})
// Custom monitoring
let reconnectCount = 0
sock.ev.on('connection.update', ({ connection }) => {
if (connection === 'close') {
reconnectCount++
console.log(`Reconnect attempt #${reconnectCount}`)
} else if (connection === 'open') {
console.log(`Reconnected after ${reconnectCount} attempts`)
reconnectCount = 0
}
})
// Handle reconnect failure
sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
if (connection === 'close') {
const error = lastDisconnect?.error
if (error?.output?.statusCode === DisconnectReason.loggedOut) {
console.log('š Logged out - manual re-auth required')
// Handle logout: clear session, show QR, etc.
} else if (error?.message?.includes('network')) {
console.log('š Network error - will auto retry')
} else {
console.log('ā Unknown disconnect - investigating...')
}
}
})
Fitur Auto Reconnect & Session Recovery memastikan bot WhatsApp Anda berjalan 24/7 tanpa perlu intervensi manual, bahkan saat koneksi terputus atau server bermasalah! š
Fitur keamanan untuk menolak panggilan suara dan video secara otomatis! Lindungi bot dari spam call dan gangguan!
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
// Anti-call protection configuration
antiCall: {
enabled: true, // Aktifkan anti-call protection
rejectVoiceCalls: true, // Tolak panggilan suara
rejectVideoCalls: true, // Tolak panggilan video
customMessage: 'Maaf, saya sedang sibuk dan tidak dapat menerima panggilan saat ini. Silakan hubungi via chat.', // Pesan balasan
logCalls: true, // Log panggilan yang ditolak
allowedNumbers: [ // Whitelist nomor yang diizinkan
'6281234567890@s.whatsapp.net',
'6289876543210@s.whatsapp.net'
],
blockAfterReject: false // Blokir nomor setelah reject
}
})
// Bot akan otomatis menolak semua panggilan masuk
// kecuali dari nomor yang ada di whitelist
// Monitor panggilan yang ditolak
sock.ev.on('call', (callData) => {
for (const call of callData) {
if (call.status === 'offer') {
console.log(`š Panggilan ${call.isVideo ? 'video' : 'suara'} dari ${call.from} ditolak otomatis`)
}
}
})
// Manual reject call (jika diperlukan)
await sock.rejectCall(callId, callerJid)
// Anti-call dengan whitelist ekstensif
const businessBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: true,
rejectVideoCalls: true,
customMessage: 'š Bot sedang dalam mode bisnis. Silakan hubungi admin untuk panggilan darurat.',
allowedNumbers: [
'6281111111111@s.whatsapp.net', // Admin 1
'6282222222222@s.whatsapp.net', // Admin 2
'6283333333333@s.whatsapp.net' // Support
],
blockAfterReject: true, // Blokir spammer
logCalls: true
}
})
// Bot pribadi - hanya izinkan keluarga
const personalBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: false, // Izinkan panggilan suara dari keluarga
rejectVideoCalls: true, // Tolak video call
customMessage: 'š Maaf sedang meeting, nanti saya telepon balik ya!',
allowedNumbers: [
'628xxxxxxxxx@s.whatsapp.net', // Keluarga
'628xxxxxxxxx@s.whatsapp.net' // Sahabat dekat
]
}
})
// Bot publik - tolak semua
const publicBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: true,
rejectVideoCalls: true,
customMessage: 'š¤ Bot tidak dapat menerima panggilan. Silakan gunakan fitur chat.',
blockAfterReject: true, // Blokir semua yang call
logCalls: false // Jangan log untuk performa
}
})
// Bot with Time-based Rules
const smartBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: true,
rejectVideoCalls: true,
customMessage: () => {
const hour = new Date().getHours();
if (hour >= 22 || hour <= 6) {
return 'š“ Maaf, sedang waktu istirahat. Silakan hubungi besok pagi.';
}
return 'š Sedang sibuk, silakan chat saja untuk bantuan.';
},
allowedNumbers: ['628xxxxxxxxx@s.whatsapp.net'] // Emergency override
}
})
// Monitor semua aktivitas anti-call
sock.ev.on('call', (callData) => {
for (const call of callData) {
const callType = call.isVideo ? 'š¹ Video Call' : 'š Voice Call';
const status = call.status;
switch (status) {
case 'offer':
console.log(`${callType} dari ${call.from} - DITOLAK (Anti-Call)`);
break;
case 'reject':
console.log(`${callType} dari ${call.from} - Berhasil ditolak`);
break;
case 'accept':
console.log(`${callType} dari ${call.from} - DIIZINKAN (Whitelist)`);
break;
}
}
})
// Custom logging dengan detail
const antiCallLogger = (call) => {
const timestamp = new Date().toISOString();
const logData = {
timestamp,
from: call.from,
type: call.isVideo ? 'video' : 'voice',
status: call.status,
isGroup: call.isGroup,
callId: call.id
};
console.log('š”ļø Anti-Call Log:', JSON.stringify(logData, null, 2));
// Simpan ke file/database jika diperlukan
// saveCallLog(logData);
};
sock.ev.on('call', (callData) => {
callData.forEach(antiCallLogger);
});
// 1. Bot Customer Service
const csBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: true,
rejectVideoCalls: true,
customMessage: 'šāāļø Halo! Untuk bantuan, silakan chat saja. Bot tidak dapat menerima panggilan.',
allowedNumbers: ['6281234567890@s.whatsapp.net'] // Hanya supervisor
}
})
// 2. Bot Gaming Community
const gamingBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: false, // Izinkan voice chat untuk gaming
rejectVideoCalls: true, // Tolak video call
customMessage: 'š® Sedang in-game! Voice chat OK, tapi video call nanti ya.',
allowedNumbers: ['628xxxxxxxxx@s.whatsapp.net'] // Game master
}
})
// 3. Bot Emergency/Important
const emergencyBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: true,
rejectVideoCalls: true,
customMessage: 'šØ Bot emergency - hanya untuk pesan penting!',
allowedNumbers: [
'628xxxxxxxxx@s.whatsapp.net', // Emergency contact 1
'628xxxxxxxxx@s.whatsapp.net' // Emergency contact 2
],
blockAfterReject: true // Blokir yang tidak penting
}
})
// 4. Bot with Time-based Rules
const smartBot = makeWASocket({
antiCall: {
enabled: true,
rejectVoiceCalls: true,
rejectVideoCalls: true,
customMessage: () => {
const hour = new Date().getHours();
if (hour >= 22 || hour <= 6) {
return 'š“ Maaf, sedang waktu istirahat. Silakan hubungi besok pagi.';
}
return 'š Sedang sibuk, silakan chat saja untuk bantuan.';
},
allowedNumbers: ['628xxxxxxxxx@s.whatsapp.net'] // Emergency override
}
})
// Handle anti-call errors
sock.ev.on('call', (callData) => {
for (const call of callData) {
if (call.status === 'offer') {
// Attempt to reject the call
sock.rejectCall(call.id, call.from)
.then(() => console.log('ā
Call rejected successfully'))
.catch(error => {
console.error('ā Failed to reject call:', error);
// Fallback: block the number
sock.updateBlockStatus(call.from, 'block');
});
}
}
})
// Debug anti-call configuration
const debugAntiCall = () => {
const config = sock.antiCallConfig;
console.log('š§ Anti-Call Config:', {
enabled: config.enabled,
voiceCalls: config.rejectVoiceCalls,
videoCalls: config.rejectVideoCalls,
whitelistCount: config.allowedNumbers.length,
autoBlock: config.blockAfterReject
});
};
debugAntiCall();
Fitur Anti-Call Protection memastikan bot WhatsApp Anda tetap fokus pada tugas utama tanpa terganggu oleh panggilan yang tidak diinginkan! š”ļøš
FAQs
Baileys mod by ajammm - ULTRA FAST Response Engine (100x faster in groups!) - iOS & Apple device support, Anti-Call, Rate Limiter, Auto Reconnect, Fake Reply & Blue Check Quote - Production Ready v2.1.16
The npm package @ajammm/baileys receives a total of 104 weekly downloads. As such, @ajammm/baileys popularity was classified as not popular.
We found that @ajammm/baileys demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket now scans OpenVSX extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.

Product
Bringing supply chain security to the next generation of JavaScript package managers

Product
A safer, faster way to eliminate vulnerabilities without updating dependencies