@warriorteam/zalo-bot-sdk
v2.0.4
Published
TypeScript SDK for Zalo Bot API - Build and integrate chatbots with Zalo Bot Platform
Readme
Zalo Bot SDK - Hướng dẫn sử dụng
SDK đơn giản cho Zalo Bot API với pattern giống redai-zalo-sdk. BOT_TOKEN được truyền như parameter đầu tiên.
📦 Cài đặt
npm install redai-zalo-bot-sdk🚀 Cách sử dụng
1. Lấy Bot Token
- Mở app Zalo
- Tìm "Zalo Bot Manager" OA
- Chọn "Tạo bot" trong menu chat
- Làm theo hướng dẫn để lấy Bot Token
2. Import SDK
import { Bot, Message, Webhook } from 'redai-zalo-bot-sdk';
// hoặc
import { createBot, createBotManager } from 'redai-zalo-bot-sdk';📝 Service API (Recommended)
BOT_TOKEN được truyền như parameter đầu tiên - giống pattern redai-zalo-sdk:
Bot API
import { Bot } from 'redai-zalo-bot-sdk';
// Kiểm tra thông tin bot
const botInfo = await Bot.getMe('YOUR_BOT_TOKEN');
console.log('Bot info:', botInfo);
// Với debug logging
const botInfo = await Bot.getMe('YOUR_BOT_TOKEN', true);Message API
import { Message } from 'redai-zalo-bot-sdk';
const BOT_TOKEN = 'YOUR_BOT_TOKEN';
const CHAT_ID = 'USER_CHAT_ID';
// Gửi tin nhắn text
await Message.text(BOT_TOKEN, CHAT_ID, 'Hello World!');
// Gửi ảnh với caption
await Message.photo(BOT_TOKEN, CHAT_ID, 'https://example.com/image.jpg', 'Ảnh đẹp');
// Gửi sticker
await Message.sticker(BOT_TOKEN, CHAT_ID, 'STICKER_ID');
// Gửi typing indicator
await Message.typing(BOT_TOKEN, CHAT_ID);
// Gửi upload photo indicator
await Message.uploadPhoto(BOT_TOKEN, CHAT_ID);
// Broadcast tin nhắn cho nhiều người
const results = await Message.broadcast(BOT_TOKEN, ['CHAT_1', 'CHAT_2'], 'Hello all!');
console.log('Broadcast results:', results);
// Với debug logging
await Message.text(BOT_TOKEN, CHAT_ID, 'Hello!', true);Webhook API
import { Webhook } from 'redai-zalo-bot-sdk';
const BOT_TOKEN = 'YOUR_BOT_TOKEN';
// Set webhook
await Webhook.setWebhook(BOT_TOKEN, {
url: 'https://your-domain.com/webhook',
secret_token: 'your-secret-token-8-chars-min'
});
// Get webhook info
const webhookInfo = await Webhook.getWebhookInfo(BOT_TOKEN);
// Delete webhook
await Webhook.deleteWebhook(BOT_TOKEN);
// Get updates (long polling) - chỉ dùng khi không có webhook
const updates = await Webhook.getUpdates(BOT_TOKEN, { timeout: 30 });🏗️ Instance API (Single Bot)
Cho trường hợp chỉ có 1 bot:
import { createBot } from 'redai-zalo-bot-sdk';
const bot = createBot('YOUR_BOT_TOKEN', true); // true = enable debug
// Bot methods
const botInfo = await bot.getMe();
// Message methods
await bot.text('CHAT_ID', 'Hello!');
await bot.photo('CHAT_ID', 'https://example.com/image.jpg', 'Caption');
await bot.sticker('CHAT_ID', 'STICKER_ID');
await bot.typing('CHAT_ID');
await bot.broadcast(['CHAT_1', 'CHAT_2'], 'Hello all!');
// Webhook methods
await bot.setWebhook({
url: 'https://your-domain.com/webhook',
secret_token: 'your-secret-token'
});👥 Multi-tenant (Nhiều Bot)
Cách 1: Service API (Recommended)
import { Bot, Message } from 'redai-zalo-bot-sdk';
// API endpoint
app.post('/api/send-message', async (req, res) => {
const { botToken, chatId, text } = req.body;
try {
const result = await Message.text(botToken, chatId, text);
res.json({ success: true, result });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// Kiểm tra bot info
app.post('/api/bot-info', async (req, res) => {
const { botToken } = req.body;
try {
const botInfo = await Bot.getMe(botToken);
res.json({ success: true, botInfo });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});Cách 2: Bot Manager
import { createBotManager } from 'redai-zalo-bot-sdk';
const manager = createBotManager();
// User 1 có bot
const user1Bot = manager.getBot('USER1_BOT_TOKEN');
await user1Bot.text('CHAT_ID', 'Message from User 1');
// User 2 có bot khác
const user2Bot = manager.getBot('USER2_BOT_TOKEN');
await user2Bot.text('CHAT_ID', 'Message from User 2');
console.log(`Total bots: ${manager.size()}`);🔗 Webhook Handling
Express Middleware
import express from 'express';
import { Webhook, Message } from 'redai-zalo-bot-sdk';
const app = express();
app.use(express.json());
// Webhook handlers
const handlers = {
'message.text.received': async (event) => {
const chatId = event.message.chat.id;
const text = event.message.text;
// Lấy botToken từ database dựa vào chatId hoặc từ URL params
const botToken = 'BOT_TOKEN_FROM_DATABASE';
// Echo tin nhắn
await Message.text(botToken, chatId, `Echo: ${text}`);
},
'message.image.received': async (event) => {
const chatId = event.message.chat.id;
const botToken = 'BOT_TOKEN_FROM_DATABASE';
await Message.text(botToken, chatId, 'Nice image! 📸');
},
'message.sticker.received': async (event) => {
const chatId = event.message.chat.id;
const botToken = 'BOT_TOKEN_FROM_DATABASE';
// Gửi lại sticker
await Message.sticker(botToken, chatId, event.message.sticker);
}
};
// Webhook endpoint
app.post('/webhook', Webhook.createMiddleware('your-secret-token', handlers, true));
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});📡 Long Polling
Thay thế webhook bằng long polling:
import { Webhook, Message } from 'redai-zalo-bot-sdk';
const BOT_TOKEN = 'YOUR_BOT_TOKEN';
// Delete webhook trước
await Webhook.deleteWebhook(BOT_TOKEN);
// Handlers
const handlers = {
'message.text.received': async (event) => {
const chatId = event.message.chat.id;
const text = event.message.text;
if (text.toLowerCase() === 'hello') {
await Message.text(BOT_TOKEN, chatId, 'Hi there! 👋');
} else {
await Message.text(BOT_TOKEN, chatId, `You said: ${text}`);
}
}
};
// Start polling (chạy mãi mãi)
await Webhook.startPolling(BOT_TOKEN, handlers, { timeout: 30, interval: 1000 }, true);🚨 Error Handling
import { ZaloBotError } from 'redai-zalo-bot-sdk';
try {
await Message.text('INVALID_TOKEN', 'CHAT_ID', 'Hello');
} catch (error) {
if (error instanceof ZaloBotError) {
console.log('Error code:', error.code);
console.log('Error message:', error.message);
console.log('User message (VI):', error.getUserMessage('vi'));
console.log('User message (EN):', error.getUserMessage('en'));
console.log('Is retryable:', error.isRetryable());
console.log('Is auth error:', error.isAuthError());
console.log('Is rate limit:', error.isRateLimitError());
}
}📊 API Reference
Bot API
Bot.getMe(botToken, debug?)- Lấy thông tin bot
Message API
Message.text(botToken, chatId, text, debug?)- Gửi textMessage.photo(botToken, chatId, photo, caption?, debug?)- Gửi ảnhMessage.sticker(botToken, chatId, sticker, debug?)- Gửi stickerMessage.typing(botToken, chatId, debug?)- Typing indicatorMessage.uploadPhoto(botToken, chatId, debug?)- Upload photo indicatorMessage.broadcast(botToken, chatIds, text, debug?)- Broadcast
Webhook API
Webhook.setWebhook(botToken, params, debug?)- Set webhookWebhook.deleteWebhook(botToken, debug?)- Delete webhookWebhook.getWebhookInfo(botToken, debug?)- Get webhook infoWebhook.getUpdates(botToken, params?, debug?)- Long pollingWebhook.startPolling(botToken, handlers, options?, debug?)- Auto pollingWebhook.processWebhook(payload, handlers, debug?)- Process webhookWebhook.createMiddleware(secretToken, handlers, debug?)- Express middleware
💡 Tips
- Multi-tenant: Dùng Service API với botToken parameter
- Single bot: Dùng Instance API với createBot()
- Debug: Thêm
truelàm parameter cuối để enable logging - Error handling: Luôn wrap trong try-catch với ZaloBotError
- Webhook vs Polling: Webhook cho production, polling cho development
🔧 TypeScript Support
SDK có full TypeScript support với proper types cho tất cả methods và responses.
📚 Documentation
Detailed Guides
- Advanced Messaging - Hướng dẫn chi tiết về gửi tin nhắn, attachments, và advanced features
- Webhook Handling - Setup và xử lý webhook events từ Zalo
- Error Handling - Xử lý lỗi và retry logic
Examples
Xem thêm examples trong folder examples/:
simple-bot.ts- Bot đơn giản với instance APIstatic-api.ts- Sử dụng service API cho multi-tenant
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT License
