@gqb333/based
v3.0.3
Published
Whatsapp api by GabWT333
Downloads
1,658
Maintainers
Readme
╭──────────────────────────────────────────────────────────────────╮
│ │
│ > based is a WhatsApp Web API library maintained by │
│ GabWT333, forked from Baileys with serious improvements. │
│ │
│ > native LID/JID resolution · smart cache · anti-ban │
│ > full TypeScript · multi-device · 2025 features │
│ │
╰──────────────────────────────────────────────────────────────────╯⚡ Install
npm install @GabWT333/basedyarn add @GabWT333/basedpnpm add @GabWT333/based🚀 Quickstart
import makeWASocket, {
useMultiFileAuthState,
DisconnectReason,
setPerformanceConfig
} from '@GabWT333/based';
setPerformanceConfig({
performance: { enableCache: true, syncFullHistory: false },
debug: { enableLidLogging: true, logLevel: 'info' }
});
async function start() {
const { state, saveCreds } = await useMultiFileAuthState('auth');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
browser: ['GabWT333', 'Chrome', '4.0.0'],
markOnlineOnConnect: false,
syncFullHistory: false
});
sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
if (connection === 'open') console.log('✦ connected!');
if (connection === 'close') {
const shouldReconnect =
(lastDisconnect?.error as any)?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) start();
}
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0];
if (!msg.message) return;
await sock.sendMessage(msg.key.remoteJid!, { text: 'pong 🏓' }, { quoted: msg });
});
}
start();setPerformanceConfig({
performance: {
enableCache: true,
batchSize: 50,
maxRetries: 5,
retryDelay: 5000,
retryBackoffMultiplier: 1.5,
maxRetryDelay: 60000,
maxMsgRetryCount: 3
}
});
const sock = makeWASocket({
markOnlineOnConnect: false, // ← never appear online automatically
syncFullHistory: false, // ← don't pull chat history on connect
generateHighQualityLinkPreview: true
});🔵 LID/JID
WhatsApp is migrating to a new identifier format called LID. Without proper handling, group messages return
undefinedsenders. based solves this natively.
import { getSenderLid, validateJid, toJid, normalizeJid } from '@GabWT333/based';
sock.ev.on('messages.upsert', ({ messages }) => {
for (const msg of messages) {
const info = getSenderLid(msg);
// info.jid → '[email protected]'
// info.lid → '123@lid'
// info.isValid → true / false
// info.timestamp → Date.now()
const { isValid, error } = validateJid(info.jid);
if (!isValid) { console.warn('bad jid:', error); continue; }
const normalized = toJid(info.lid); // always get a safe JID
sock.sendMessage(normalized, { text: 'received ✓' });
}
});Fields auto-injected into every event payload:
| Field | Type | Description |
|---|---|---|
| msg.key.remoteJid | string | Standard JID (@s.whatsapp.net) |
| msg.key.remoteLid | string? | Raw LID when available |
| msg.key.participantLid | string? | Group sender LID |
| msg.key.remoteJidNormalized | string | Always-safe normalized JID |
🧠 Cache
setPerformanceConfig({
cache: {
lidCache: { ttl: 300_000, maxSize: 10000, cleanupInterval: 120_000 },
jidCache: { ttl: 300_000, maxSize: 10000, cleanupInterval: 120_000 },
lidToJidCache: { ttl: 300_000, maxSize: 5000, cleanupInterval: 180_000 },
groupMetadataCache: { ttl: 600_000, maxSize: 2000, cleanupInterval: 300_000 }
}
});
// monitor
const stats = getCacheStats();
console.log(`hit rate: ${stats.lidCache.hits / (stats.lidCache.hits + stats.lidCache.misses) * 100}%`);
// flush
clearCache(); lidCache ──────────── 80–90% fewer API calls
jidCache ──────────── instant normalization
lidToJidCache ──────── zero-latency conversion
groupMetadataCache ─── group ops at warp speed💬 Messages
await sock.sendMessage(jid, {
text: '*bold* _italic_ ~strike~ `mono`',
mentions: ['[email protected]']
});// image
await sock.sendMessage(jid, { image: { url: './img.jpg' }, caption: 'caption' });
// video
await sock.sendMessage(jid, { video: { url: './clip.mp4' }, gifPlayback: false });
// voice note
await sock.sendMessage(jid, { audio: { url: './voice.mp3' }, mimetype: 'audio/mp4', ptt: true });
// document
await sock.sendMessage(jid, {
document: { url: './file.pdf' },
mimetype: 'application/pdf',
fileName: 'doc.pdf'
});
// album (multi-image)
await sock.sendMessage(jid, { album: buffers.map(b => ({ image: b })) });// quick reply buttons
await sock.sendMessage(jid, {
text: 'choose:',
footer: 'GabWT333',
buttons: [
{ buttonId: 'a', buttonText: { displayText: 'Option A' }, type: 1 },
{ buttonId: 'b', buttonText: { displayText: 'Option B' }, type: 1 }
]
});
// list menu
await sock.sendMessage(jid, {
text: 'menu', title: 'Pick one', buttonText: 'Open',
sections: [{
title: 'Options',
rows: [
{ title: 'Item 1', rowId: 'i1', description: 'subtitle' },
{ title: 'Item 2', rowId: 'i2', description: 'subtitle' }
]
}]
});await sock.sendMessage(jid, {
poll: {
name: 'Best runtime?',
values: ['Node', 'Deno', 'Bun'],
selectableCount: 1
}
});
// poll result snapshot
await sock.sendMessage(jid, {
pollResultSnapshot: {
name: 'Best runtime?',
pollVotes: [
{ optionName: 'Node', optionVoteCount: 12 },
{ optionName: 'Deno', optionVoteCount: 4 }
],
pollType: 0
}
});await sock.sendMessage(jid, {
text: 'swipe →',
cards: [
{
title: 'Card 1', body: 'description',
image: { url: './img1.jpg' },
buttons: [{ name: 'quick_reply', buttonParamsJson: '{"display_text":"Go"}' }]
},
{ title: 'Card 2', body: 'description', video: { url: './clip.mp4' } }
],
carouselCardType: 1 // 1 = horizontal scroll
});// single sticker
await sock.sendMessage(jid, { sticker: { url: './s.webp' } });
// full sticker pack
await sock.sendMessage(jid, {
stickerPack: {
name: 'My Pack', publisher: 'GabWT333',
stickers: [
{ sticker: { url: './s1.webp' }, emojis: ['🔥'] },
{ sticker: { url: './s2.webp' }, emojis: ['💙'], isAnimated: true }
]
}
});// request
await sock.sendMessage(jid, {
requestPayment: { currency: 'EUR', amount1000: 5000, requestFrom: jid, note: 'invoice' }
});
// send payment
await sock.sendMessage(jid, {
sendPayment: {
requestMessageKey: { remoteJid: jid, fromMe: false, id: 'msgId' },
noteMessage: { text: 'paid ✓' }
}
});
// decline / cancel
await sock.sendMessage(jid, { declinePayment: { key: { remoteJid: jid, fromMe: false, id: 'msgId' } } });
await sock.sendMessage(jid, { cancelPayment: { key: { remoteJid: jid, fromMe: true, id: 'msgId' } } });// pin / unpin
await sock.sendMessage(jid, {
pin: { key: { remoteJid: jid, fromMe: false, id: 'msgId' }, type: 1, time: 86400 }
});
// AI rich response
await sock.sendMessage(jid, {
ai: true,
richResponse: {
messageType: 1,
submessages: [
{ messageType: 2, messageText: 'Here is the answer' },
{ messageType: 5, codeMetadata: { codeLanguage: 'js', codeBlocks: [{ codeContent: 'console.log("hi")' }] } }
]
}
});
// scheduled call
await sock.sendMessage(jid, {
call: {
callKey: { fromMe: true, id: Date.now().toString(), remoteJid: jid },
type: 'OFFER',
time: Date.now() + 3_600_000,
title: 'Team sync'
}
});
// status sticker on broadcast
await sock.sendMessage('status@broadcast',
{ sticker: { url: './s.webp' } },
{ statusJidList: [jid] }
);👥 Groups
// ── create ──────────────────────────────────────────────────────────
const g = await sock.groupCreate('My Group 🔵', ['[email protected]']);
// ── participants ─────────────────────────────────────────────────────
await sock.groupParticipantsUpdate(jid, [user], 'add');
await sock.groupParticipantsUpdate(jid, [user], 'remove');
await sock.groupParticipantsUpdate(jid, [user], 'promote');
await sock.groupParticipantsUpdate(jid, [user], 'demote');
// ── settings ─────────────────────────────────────────────────────────
await sock.groupUpdateSubject(jid, 'New name');
await sock.groupUpdateDescription(jid, 'New description');
await sock.groupSettingUpdate(jid, 'announcement'); // admin-only
await sock.groupToggleEphemeral(jid, 86400); // 24h disappearing
await sock.groupJoinApprovalMode(jid, 'on'); // approval required
await sock.groupMemberAddMode(jid, 'admin_add'); // admin-only invites
// ── invite ───────────────────────────────────────────────────────────
const code = await sock.groupInviteCode(jid);
await sock.groupRevokeInvite(jid);
await sock.groupAcceptInvite(code);
await sock.groupLeave(jid);📡 Events
| Event | Trigger |
|---|---|
| connection.update | Connection state changed |
| creds.update | Auth credentials rotated — always save |
| messages.upsert | New or updated message |
| messages.update | Delivery / read receipt |
| group-participants.update | Member join / leave / promote |
// status tracking
sock.ev.on('messages.update', updates => {
for (const { key, update } of updates) {
const status = ['', 'sent', 'delivered', 'read'][update.status ?? 0];
console.log(`[${key.id}] → ${status}`);
}
});
// group events
sock.ev.on('group-participants.update', ({ id, action, participants }) => {
console.log(`[${id}] ${action}:`, participants);
});📖 API Reference
| Method | Returns | Description |
|---|---|---|
| makeWASocket(cfg) | WASocket | Create the socket |
| useMultiFileAuthState(dir) | { state, saveCreds } | Persistent auth |
| getSenderLid(msg) | SenderInfo | Safe sender extraction |
| validateJid(jid) | { isValid, error } | JID validation |
| toJid(lid) | string | LID → JID conversion |
| normalizeJid(jid) | string | Normalize any JID |
| isValidJid(jid) | boolean | Quick validity check |
| getCacheStats() | CacheStats | Hit/miss/size metrics |
| clearCache() | void | Flush all caches |
| setPerformanceConfig(cfg) | void | Tune perf settings |
| getPerformanceConfig() | Config | Read live config |
🔧 Troubleshooting
Use exponential backoff — set maxRetries: 5 and retryBackoffMultiplier: 1.5. Never reconnect immediately on close.
Always use getSenderLid(msg) instead of reading msg.key.participant raw. The library patches this automatically in events but getSenderLid provides additional metadata.
Reduce maxSize or ttl on cache entries. Call clearCache() periodically or on connection.open.
Critical settings: markOnlineOnConnect: false + syncFullHistory: false. Lower batchSize to 30–50. Add natural delays between bulk sends.
🛡️ Security
| Layer | Tech | |---|---| | End-to-End Encryption | Signal Protocol | | Key Management | Auto-generation & rotation | | Authentication | QR code or pairing code | | Storage | Encrypted local credentials |
🙏 Credits
| Project | Contribution | |---|---| | Baileys | Core WhatsApp Web engine | | Yupra | LID/JID resolution research | | Signal Protocol | E2E encryption layer |
⚠️ Disclaimer
Not affiliated with WhatsApp Inc. or Meta Platforms. For educational and personal development use only. Use responsibly — abuse may result in account termination.
MIT License © 2025 GabWT333
