Levatain-MD
AI-first WhatsApp bot built on Baileys (Node.js, ESM) with natural-language intent engine and modular plugins.
Levatain-MD
AI-first WhatsApp bot built on Baileys (Node.js, ESM). Besides regular prefixed commands, this bot has an intent engine — an AI that reads natural chat (no prefix) and automatically routes it to the matching plugin.
Folder Structure
.
├── index.js Entry point (10 lines): wires the runtime together
├── package.json Dependencies & npm scripts
├── scripts/ CLI tools (`npm run check`)
├── docs/ARCHITECTURE.md How the code is organised and where to put new things
├── src/
│ ├── config.js Every environment variable is read here (single source of truth)
│ ├── runtime/ Process lifecycle: connection & reconnect, socket listeners, background jobs
│ ├── core/ Command engine: loader, plugin contract, pipeline, handler, access, identity, globals
│ ├── groups/ Group rules: guards (anti-link etc.) and join/leave/captcha events
│ ├── ai/ Intent engine, trigger-word gate, conversation memory, prompts/
│ ├── wa/ WhatsApp helpers: messages, interactive/rich messages, caches, session, device
│ ├── api/ External services: LLM, TTS, downloaders, youtube, giphy, ...
│ ├── storage/ Database (db.js), remote DB, GitHub sync
│ ├── limits/ Daily usage limits and plans
│ ├── menu/ Menu catalog and menu text
│ ├── media/ Audio effects and media size limits
│ ├── dashboard/ Admin web dashboard (server + static client)
│ ├── util/ Generic helpers and logger
│ └── tools/ Dev tools (plugin checker)
└── plugins/ All bot commands, grouped by category, auto-loaded
├── main/ ai/ audiochanger/ download/ fun/ group/ limit/ owner/ tools/
See docs/ARCHITECTURE.md for the rules of each folder.
How Commands Work
The bot supports two ways of invoking a command at once:
- Regular prefix — type any symbol (
.,!,#, etc.) followed by the command name, e.g..tiktok <url>. - Natural language (AI intent engine) — type an ordinary sentence with no prefix, e.g. “download this tiktok for me” or “make a sticker from this photo”. The AI (
src/ai/engine.js) reads the plugin list along with itsai.trigger/ai.examplesmetadata, then decides which command best matches and runs it automatically.
Inside groups specifically, the AI (chat or intent engine) only activates if one of the following is met (src/ai/gate.js):
- The message contains a trigger word:
lev/levatain/leva - The bot is mentioned
- The message replies/quotes a bot message
This keeps the bot from jumping into every conversation in the group.
Requirements
- Node.js version 20 or above
- ffmpeg must be installed on the system (not just the npm package) — used for the audio changer and media conversion features
- Ubuntu/Debian:
sudo apt install ffmpeg - Check it’s installed:
ffmpeg -version
- Ubuntu/Debian:
Environment Variable Configuration
All configuration goes through the .env file (never committed to the repo, already in .gitignore).
cp .env.example .env
Open .env and fill in at minimum:
-
PAIRING_NUMBER— the WA number you want to turn into the bot (format628xxxxxxxxxx, no+) -
OWNER_NUMBER— your WA number as the owner -
GEMINI_COOKIE— Gemini is the only LLM used by the bot (session cookie from gemini.google.com, see the comments in.env.example) -
BOT_THUMB— (optional) menu thumbnail. Accepts an image URL (.png/.jpg) or a video URL (.mp4/.mov/.webm). A video is sent as a looping GIF-style clip. Keep it small (under ~2 MB, no audio) so WhatsApp auto-downloads it; the recipient’s Auto-download → Video setting also has to be on, otherwise they see a download button.
Other variables (Giphy, Magic Hour, translate, dashboard port, etc.) are optional — see the comments in .env.example for an explanation of each variable.
How to Get All API Keys
All the keys below go in the .env file (not .env.example), one line per variable, in the format VARIABLE_NAME=key-value with no spaces/quotes.
| Key used for | Env var | How to get it |
|---|---|---|
| AI chat & intent engine (Gemini, the only LLM) | GEMINI_COOKIE |
Open gemini.google.com in a browser → DevTools → Network → any request → copy the cookie header. |
| Voice note TTS (optional) | NAGA_API_KEY |
Join the NagaAI Discord server → in the bot channel, type /account key get. Only used for text-to-speech, not for chat. |
| Mood/AI stickers (Giphy) | GIPHY_API_KEY |
Open developers.giphy.com → Create an App → choose API (not SDK) → copy the API Key shown. |
.editimage / .aiedit (Magic Hour) |
MAGICHOUR_KEY_1 through MAGICHOUR_KEY_3 |
Sign up at magichour.ai → go to Dashboard → API Keys menu → generate a new key. You can fill in more than one for auto-rotation. |
.pushgh / .deploy (push source to GitHub) |
GITHUB_SYNC_TOKEN (or reuses GITHUB_TOKEN), GITHUB_SYNC_REPO, GITHUB_SYNC_BRANCH |
github.com/settings/tokens → generate a token with repo scope (classic) or Contents: write (fine-grained, scoped to the target repo). GITHUB_SYNC_REPO is username/repo-name of the public repo you want the bot to push to. |
Once you have a key, open .env, paste it on the matching env var line, save, then restart the bot (npm start again / pm2 restart levatain-md).
All the keys above are free to get started with (each provider has its own free limit/quota). Never commit a filled-in
.envfile to a public repo.
Running on a Regular VPS
1. Install dependencies
npm install
2. Run the bot
npm start
There’s also npm run dev, which runs the bot with node --watch (auto-restarts on every file change, handy for development).
The npm start process runs in the foreground and will die if the terminal/SSH session closes. To keep it alive, use one of the following:
Option A — using pm2 (recommended)
npm install -g pm2
pm2 start index.js --name levatain-md
pm2 save
pm2 startup # follow the printed instructions so the bot auto-starts on VPS reboot
Check logs: pm2 logs levatain-md · Restart: pm2 restart levatain-md · Stop: pm2 stop levatain-md
Option B — using screen
screen -S levatain-md
npm start
# press Ctrl+A then D to detach (the bot keeps running in the background)
Return to the session: screen -r levatain-md
The first time it runs, the bot will show a pairing code in the terminal. Open WhatsApp on your phone → ⋮ (three dots) → Linked Devices → Link with phone number → enter that code.
Running with Docker
cp .env.example .env # fill PAIRING_NUMBER, OWNER_NUMBER, GEMINI_COOKIE
docker compose up -d --build
docker compose logs -f # the pairing code appears here on first run
WhatsApp session and database are kept in Docker volumes (levatain-session, levatain-database), so they survive updates. Update with git pull && docker compose up -d --build.
Running with systemd or pm2 (VPS)
- pm2:
pm2 start ecosystem.config.cjs && pm2 save && pm2 startup - systemd: edit
deploy/levatain.service(User,WorkingDirectory), copy it to/etc/systemd/system/, thensudo systemctl enable --now levatain. Logs:journalctl -u levatain -f.
Other hosts (Railway, Render, Koyeb, etc.)
Deploy from the Dockerfile (or use the Procfile, process type worker). Set the variables from .env.example in the host’s environment settings. Attach a persistent volume to /app/session and /app/database, otherwise you must pair WhatsApp again on every redeploy. Pick a worker/background service type if the host offers one.
Running on a Pterodactyl Panel
- Create a new server with the Node.js egg (Nodejs Generic/YSN Node.js egg or similar, minimum Node version 20).
- Upload the bot’s source code to the server directory (via the panel’s file manager, SFTP, or
git clonefrom this repo if the egg supports it). - Fill in environment variables — two options, pick one:
- Create a
.envfile directly in the project root (upload its contents manually, or fill it in from.env.example), or - If your Pterodactyl egg provides an “Environment Variables” slot on the Startup tab, fill in the same variables there (variable names must match exactly:
PAIRING_NUMBER,OWNER_NUMBER,GEMINI_KEY_1, etc.).
- Create a
- Startup command — set it to:
or if the egg already runsnpm install && npm startnpm installautomatically, just:node index.js - Bot web dashboard — if you want to access it from outside, match
DASHBOARD_PORTin.envto the port allocation Pterodactyl gave that server. - Start the server from the panel, open the Console tab to see the pairing code, then link it as usual from WhatsApp.
Note: Pterodactyl usually restarts the process automatically if it crashes — so there’s no need for extra
pm2/screeninside the container.
If isOwner Fails to Detect
Sometimes automatic owner detection fails (a WhatsApp LID edge case). If this happens:
- Set
DEBUG=truein.env, restart the bot. - Send any message to the bot from the owner’s number.
- Open
logs/bot.log, look for the[owner-check]line. - Copy the digits from
lid=XXXXXXXXXX@lid(digits only, without@lid). - Set it as
OWNER_LIDin.env, restart the bot.
AI Agent
Levatain’s AI is an agent: it can call tools in a loop, several at once when they are read-only, and answer when it has enough.
| Tool | Who | What it does |
|---|---|---|
web_search, web_read |
everyone | Search the web and read pages (no API key, private addresses blocked) |
calc, time_now |
everyone | Exact math, current time in any timezone |
note_save/find/list/delete |
everyone | Long-term notes per user |
remind, remind_list, remind_cancel |
everyone | Reminders, one-off or repeating |
run_plugin |
everyone | Run a bot command and use its text result in a multi-step plan |
schedule |
owner | Scheduled agent tasks (e.g. a daily report) |
readfile, edit_file, exec, sandbox_*, … |
owner | Workshop tools for the project itself |
Safety: web content is untrusted. After the agent reads the web, file-changing, code-running, posting and scheduling tools are locked for the rest of that run. Regular users have a smaller step budget and an hourly cap.
Setup: set GEMINI_API_KEY (free tier) as a fallback for the cookie, and BOT_TIMEZONE for reminders. Tests: npm run test:agent.
Plugin Checker
Checks every plugin for code errors, empty API keys, and unreachable API hosts. Hosts are detected automatically from each plugin’s source (including the api.* functions it calls).
- In WhatsApp (owner only):
.cekplugin·.cekplugin full·.cekplugin code(skip API check) ·.cekplugin tiktok(one plugin or file) - In the terminal:
npm run check·npm run check -- --full·npm run check -- --no-probe·npm run check -- tiktok
Status meanings: mati means the host does not respond or returns 5xx, dibatasi means the host answers 403/429 (often bot protection), and a plugin only counts as down when every host it uses is down. This confirms the host is reachable, not that the scraper still parses the result correctly.
Adding a New Plugin/Command
Every plugin is built with the plugin() builder from src/core/plugin.js. Minimal example:
import { plugin } from '../../src/core/plugin.js';
export default plugin('commandname', 'alias1') // main command + aliases, all lowercase
.in('category') // menu grouping
.desc('Short description for the menu')
.groupOnly() // optional: .adminOnly() .ownerOnly() .botAdmin() .cooldown(sec)
.signal('When the AI should trigger this command', ['example sentence 1', 'example sentence 2'])
.run(async (sock, ctx) => {
await ctx.reply('Hello!');
});
The ctx object already carries the everyday helpers, so plugins rarely touch sock directly:
| Helper | What it does |
|---|---|
reply(text | content, extra?) |
Quoted reply, e.g. reply('hi', { mentions: [id] }) or reply({ image: buf, caption }) |
send(text | content, extra?) |
Same chat, no quote |
react(emoji) / del(key?) / typing() |
Reaction, delete message, “typing…” presence |
sendTo(sock, jid, text | content) (from wa/reply.js) |
Send when there is no incoming message (timers, schedulers) |
resolveTarget(ctx) (from core/identity.js) |
Who the command points at: quoted → @mention → (opt-in) a number. Returns { id, tag, participant } |
kick promote demote addMember inviteLink … (from wa/group.js) |
Group actions, with the metadata cache refreshed afterwards |
getAbout getAvatarUrl getBusiness (from wa/profile.js) |
Profile lookups that return null instead of throwing |
Put new files in the plugins/<category>/ folder. Plugins are automatically scanned and registered by src/core/loader.js based on meta.interface.cmd — no need to register them manually anywhere else. The ai block is optional but recommended, so the command can also be triggered via natural chat, not just via prefix.
The owner can reload all plugins without restarting the process using the .reload command.
If porting a plugin from a reference bot (CommonJS /
module.exportsformat), it must be adapted to theplugin()format above, not copy-pasted directly.
Troubleshooting
| Issue | Solution |
|---|---|
| Bot exits immediately on start | Check that PAIRING_NUMBER is filled in .env |
| AI chat / intent engine feature doesn’t work | Check that GEMINI_COOKIE is filled in and not expired |
| AI doesn’t respond in a group | Mention the bot’s name / the word lev, mention the bot, or reply to a bot message — in groups the AI doesn’t auto-respond to every chat |
| Audio/effect feature errors | Make sure ffmpeg is installed on the system, check with ffmpeg -version |
| Session keeps logging out | Delete the session/ folder, restart the bot, pair again |
isOwner always false |
Follow the steps above to manually set OWNER_LID |
| Bot dies when SSH closes (VPS) | Use pm2 or screen, see the “Running on a Regular VPS” section |
| New plugin doesn’t show up | Make sure the meta.interface.cmd & meta.interface.run format is correct, then run .reload or restart the bot |
License
This project is released under the MIT License. You are free to use, copy, modify, publish, distribute, sublicense and even sell it — including turning your fork into a closed-source project — as long as the copyright notice and license text stay included.
Credits
Made by Levatain & onepunya.
Please keep these credits (and the LICENSE file) intact in any copy or fork of this project. Built on Baileys.