A TypeScript-based WhatsApp bot using Baileys and Google Gemini AI to respond to messages in groups and private chats.
- Features
- Quick Start
- How to Connect Your WhatsApp Number
- New Features Highlights
- Project Structure
- Usage
- Admin Commands & Web UI
- Configuration
- Security
- Development
- Troubleshooting
- Dependencies
- Features Explained
- License & Contributing
- β WhatsApp Integration - Connect via QR code using Baileys
- β AI-Powered Responses - Google Gemini (or OpenAI GPT) integration
- β Smart Group Detection - Only responds when mentioned in groups
- β Message Memory - Maintains conversation context (configurable window)
- β Admin Commands - Special commands for authorized users
- β Auto-Reconnect - Handles disconnections gracefully
- β Health Monitoring - Express server for health checks
npm installCopy the example environment file and update it:
cp .env.example .envEdit .env and add:
- Your Gemini API key (get from https://ai.google.dev/)
- Admin phone numbers (format:
1234567890, without + or spaces)
Development mode:
npm run devProduction mode:
npm run build
npm run prodWhen you run the bot, a QR code will appear in your terminal. Scan it with WhatsApp on your phone.
Follow these steps to link your WhatsApp number to the bot.
- Restart the bot to show the QR code
npm run devYouβll see a QR block in the terminal with guidance to open WhatsApp β Settings β Linked Devices β Link a Device.
- Scan the QR code
- Open WhatsApp β Settings β Linked Devices β Link a Device
- Scan the terminal QR code
- Wait a few seconds for confirmation
- What happens next
- The scanned WhatsApp number becomes the botβs number
- In groups, the bot responds when mentioned (e.g.,
@bot) - In private chats, the bot responds to all messages
- Session is saved in
auth_info_baileys/so future runs wonβt require QR
- Testing tips
- Send
!statusto the bot to see current configuration and memory stats - Mention the bot in a group:
@bot what is TypeScript?
Troubleshooting
- If QR doesnβt render, ensure UTF-8 terminal support
- If connection closes, wait a few minutes and retry
- If βNot Logged Inβ shows, itβs ready and waiting for QR scan
Admin number format
Update ADMIN_NUMBERS in .env with your number in digit-only international format (no +, spaces, or punctuation):
ADMIN_NUMBERS=1234567890,9876543210whatsapp-group-bot/
βββ src/
β βββ config/
β β βββ env.ts # Environment configuration
β βββ lib/
β β βββ logger.ts # Winston logger
β βββ services/
β β βββ memory.service.ts # Message memory management
β β βββ llm.service.ts # AI/LLM integration
β β βββ whatsapp.service.ts # Baileys WhatsApp connection
β βββ handlers/
β β βββ message.handler.ts # Message processing logic
β βββ utils/
β β βββ admin.utils.ts # Admin command utilities
β βββ index.ts # Application entry point
βββ logs/ # Application logs
βββ auth_info_baileys/ # WhatsApp session (auto-generated)
βββ .env # Environment variables (DO NOT COMMIT)
βββ .env.example # Example environment file
βββ package.json
βββ tsconfig.json
The bot only responds when mentioned:
User: @bot what's the weather like?
Bot: I don't have access to real-time weather data, but...
All messages in the group are stored in memory for context.
The bot responds to every message:
You: Hello!
Bot: Hi there! How can I help you today?
Only users listed in ADMIN_NUMBERS can use these commands:
| Command | Description |
|---|---|
!help |
Show available admin commands |
!status |
Display bot status and memory info |
!clear |
Clear message memory |
!system <prompt> |
Update the system prompt |
Example:
!system You are a helpful coding assistant. Always provide code examples.
A minimalist admin UI is available at /admin (when the bot is running). It allows you to:
- Update configuration settings: Bot name, admin numbers, rate limits, system prompt, and API key
- Toggle private chat responses on or off (enable/disable)
- Save settings; these get persisted on the server and also optionally stored in your browser's localStorage for quick local recovery
When you save settings from the UI, the server validates and persists them to a runtime_config.json file; the bot picks them up immediately without a restart (where applicable).
Note: The Admin UI is intentionally minimal and does not include authentication; ensure it is only accessible on trusted networks or behind a reverse proxy with authentication.
Access the admin panel:
- Run the bot:
npm run dev - Open your browser and go to:
http://localhost:3000/admin
Changes you make in the UI are persisted to runtime_config.json server-side and stored locally in the browser's localStorage as well.
Bot responses in groups and private chats now use WhatsAppβs native reply feature. This clearly shows the quoted message the bot is responding to, improving readability in busy conversations.
Benefits:
- Clear context and threading
- Native WhatsApp UX
Prevent spam and manage usage in groups.
Defaults:
- Max requests: 2 mentions per user
- Time window: 60 seconds
- Applies to: Group members (admins exempt)
- Private chats: No rate limit
Configure via .env:
RATE_LIMIT_MAX_REQUESTS=2
RATE_LIMIT_WINDOW_MS=60000Examples:
# 3 per minute
RATE_LIMIT_MAX_REQUESTS=3
RATE_LIMIT_WINDOW_MS=60000
# 5 per 2 minutes
RATE_LIMIT_MAX_REQUESTS=5
RATE_LIMIT_WINDOW_MS=120000
# Strict: 1 per 30s
RATE_LIMIT_MAX_REQUESTS=1
RATE_LIMIT_WINDOW_MS=30000Notes:
- Admins are exempt
- Private chats are exempt
- Automatic cleanup of old records
Technical references:
src/services/ratelimit.service.tssrc/config/env.tssrc/services/whatsapp.service.ts(reply method)src/handlers/message.handler.ts(integration)
| Variable | Description | Default |
|---|---|---|
NODE_ENV |
Environment mode | development |
PORT |
Health server port | 3000 |
LOG_LEVEL |
Logging level | info |
BOT_NAME |
Bot mention trigger | @bot |
ADMIN_NUMBERS |
Comma-separated admin numbers | - |
LLM_PROVIDER |
AI provider (gemini or openai) |
gemini |
GEMINI_API_KEY |
Google Gemini API key | - |
GEMINI_MODEL |
Gemini model name | gemini-1.5-flash |
MEMORY_WINDOW_MS |
Memory retention time (ms) | 3600000 (1 hour) |
SYSTEM_PROMPT |
AI behavior instructions | Default helpful assistant |
Use international format without + or spaces:
# β
Correct
ADMIN_NUMBERS=1234567890,9876543210
# β Incorrect
ADMIN_NUMBERS=+1 234 567 890,+98 76 543 210- Never commit
.env- Contains sensitive API keys - Auth folder -
auth_info_baileys/is auto-generated, keep it private - Admin access - Only authorized numbers can use admin commands
- Rate limiting - Consider adding if bot is public
npm run dev- Start in development mode with auto-reloadnpm run start- Start in production mode with ts-nodenpm run build- Compile TypeScript to JavaScriptnpm run prod- Run compiled JavaScript
Logs are stored in the logs/ directory:
combined.log- All logserror.log- Error logs only
- Ensure your terminal supports UTF-8
- Check that
printQRInTerminal: truein WhatsApp service
- Delete
auth_info_baileys/folder - Restart the bot and scan QR code again
- Verify API key is correct in
.env - Check API quota/billing on provider dashboard
- Review
logs/error.logfor details
- Ensure phone has internet connection
- Check WhatsApp Web is not open elsewhere
- Review
logs/combined.log
- Check internet stability
- Verify WhatsApp account is not banned
- Review Baileys connection settings
@whiskeysockets/baileys- WhatsApp Web API@google/generative-ai- Google Gemini AI SDKexpress- HTTP serverwinston- Loggingdotenv- Environment variables@hapi/boom- Error handling
typescript- TypeScript compilerts-node- TypeScript executionnodemon- Auto-reload@types/*- TypeScript type definitions
- Stores last N messages (configurable)
- Auto-prunes old messages based on time window
- Provides context to AI for better responses
- Only responds when bot is mentioned in groups
- Responds to all messages in private chats
- Stores all group messages for context
- Handles network disconnections
- Preserves session across restarts
- QR code only needed on first run
MIT License β see LICENSE for full text.
Feel free to submit issues and pull requests!
This bot is for educational purposes. Ensure compliance with WhatsApp's Terms of Service when using automated tools.
