@x-kira/database
v1.0.3
Published
RemoteDB wrapper for kira database (RemoteDB default export + RemoteDB class
Downloads
391
Maintainers
Readme
@x-kira/database — Deep Guide for Baileys WhatsApp Bots
🔮 RemoteDB — Lightweight remote-backed data store focused on WhatsApp bots (Baileys)
Package: @x-kira/database
✨ What this module gives you when used in a Baileys WhatsApp bot
When you import and initialize @x-kira/database inside your Baileys bot, you can do the following (short list):
- ✅ Per-JID storage — store arbitrary JSON per chat/group/user (e.g. prefixes, settings, counters).
- ✅ Global settings for bot#user — store global config like
welcomeEnabled,ownerNumber,prefixfallback. - ✅ Fast cache-first reads — reads return instantly from local RAM (with optional LRU hot cache for heavy usage).
- ✅ Durable persistence — writes persist to remote backend via POST so data survives restarts.
- ✅ Automatic safe key encoding — JIDs and keys are encoded so they won’t break JSON storage.
- ✅ No-op disabled mode — run locally without network for tests (
init({ conn: null })). - ✅ Session & plugin data storage — store small session objects, plugin states, moderation logs.
- ✅ Common features ready-to-build — prefixes, auto-reply, welcome messages, autorole, rate-limits, anti-spam counters.
- ✅ Multi-bot & multi-user support — namespaced by
bot+usernumber. Run multiple bot instances using same backend safely. - ✅ Administrative operations — dump, replaceAll, syncToDisk, close for graceful shutdown.
🔧 Quick checklist — where to import & init in Baileys
- Initialize after Baileys authentication so
conn.user.idis available. - Use a stable
botname (e.g.'KAISEN-MD'or'Zarisha Bot') — this namespaces the storage.
Example snippet (placement):
// after baileys conn created and authenticated
await db.init({ conn, bot: 'KAISEN-MD' });🧩 Full Baileys examples (focused & practical)
Below are practical, copy-pasteable examples that show typical things you will implement in a WhatsApp bot after importing this module.
Note: These examples assume you already have a working Baileys connection
conn.
1) Initialize DB (required)
const db = require('@x-kira/database');
// when conn.ready/authenticated
await db.init({ conn, bot: 'KAISEN-MD' });
console.log('DB initialized for', conn.user && conn.user.id);2) Simple per-group prefix (set/get)
// set: any admin command can call this
await db.setJid(groupJid, 'prefix', '!');
// use: in your message handler
const group = await db.getJid(groupJid) || {};
const prefix = group.prefix || '!';
if (text.startsWith(prefix + 'ping')) {
await conn.sendMessage(groupJid, { text: '🏓 Pong!' });
}3) Welcome message for new group members
conn.ev.on('group-participants.update', async (ev) => {
const gid = ev.id; // group JID
const cfg = await db.getJid(gid) || {};
if (!cfg.welcome || !cfg.welcome.enabled) return; // disabled
for (const participant of ev.participants) {
if (ev.action === 'add') {
const welcomeText = (cfg.welcome && cfg.welcome.message) || 'Welcome to the group 🎉';
await conn.sendMessage(gid, { text: `👋 @${participant.split('@')[0]}
${welcomeText}` }, { mentionedJid: [participant] });
}
}
});4) Enable/disable welcome (owner/group admin command)
// enable
const cfg = (await db.getJid(groupJid)) || {};
cfg.welcome = { enabled: true, message: 'Please read the rules.' };
await db.setJid(groupJid, cfg);
// disable
await db.deleteJid(groupJid, 'welcome');5) Per-user rate limiter (cooldown) — anti spam
async function canSend(jid, limitMs = 2000) {
const u = (await db.getJid(jid)) || {};
const now = Date.now();
u._lastAt = u._lastAt || 0;
if (now - u._lastAt < limitMs) return false;
u._lastAt = now;
await db.setJid(jid, u);
return true;
}
// usage in messages.upsert
if (!await canSend(senderJid)) return; // ignore spammy messages6) Save small session/state for a user (persist across restarts)
// Save
await db.setJid(userJid, 'session', { step: 'awaiting_code', createdAt: Date.now() });
// Read
const session = await db.getJid(userJid, 'session');7) Moderation logs: store recent kicks/bans per group
async function addModLog(groupJid, entry) {
const g = (await db.getJid(groupJid)) || {};
g.modLogs = g.modLogs || [];
g.modLogs.push({ ...entry, at: Date.now() });
// keep last 50
if (g.modLogs.length > 50) g.modLogs.shift();
await db.setJid(groupJid, g);
}8) Global settings example (bot-wide settings)
// set an owner number global
await db.setGlobal('owner', '[email protected]');
// read
const owner = await db.getGlobal('owner');9) Backup & debug: dump store and force sync
const snapshot = db.dump(); // local snapshot
await db.syncToDisk(); // force POST to remote10) Graceful shutdown (persist unsaved changes)
process.on('SIGINT', async () => {
console.log('Saving DB and exiting...');
await db.close();
process.exit(0);
});✅ Full feature checklist for a Baileys user (explicit)
When you import and initialize @x-kira/database in your Baileys bot you can implement the following features easily:
- Store per-chat/group settings (prefix, language, welcome message). ✅
- Store per-user state (wizard flows, session steps). ✅
- Rate-limiting / anti-spam counters per user or per group. ✅
- Moderation logs per group (kicks, bans, warnings). ✅
- Global bot configuration (owner number, global toggles). ✅
- Hot-cache for faster reads when using
lru-cache. ✅ - Persist small JSON session blobs across restarts. ✅
- Replace/restore whole dataset (
replaceAll) for migrations or restore. ✅ - Dump local store for debugging and backups. ✅
- No-op mode for tests (
init({ conn: null })) so your unit tests don’t hit network. ✅ - Multi-instance safe namespacing via
botandusernumber. ✅
const { RemoteDB } = require('@x-kira/database');
const botA = new RemoteDB();
await botA.init({ conn: connA, bot: 'bot-a' });
const botB = new RemoteDB();
await botB.init({ conn: connB, bot: 'bot-b' });Quick Reference (Methods)
Method | Description ------ | ----------- init(opts) | Initialize DB with connection and load remote data getJid(jid, key) | Get jid object or key setJid(jid, key, value) | Set jid value (persisted) deleteJid(jid, key) | Delete key or jid getGlobal(key) | Read global value setGlobal(key, value) | Set global value replaceAll(obj) | Replace local store & persist dump() | Return full local store syncToDisk() | Force persist close() | Final persist (if required)
License
MIT
