npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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

  1. Mở app Zalo
  2. Tìm "Zalo Bot Manager" OA
  3. Chọn "Tạo bot" trong menu chat
  4. 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 text
  • Message.photo(botToken, chatId, photo, caption?, debug?) - Gửi ảnh
  • Message.sticker(botToken, chatId, sticker, debug?) - Gửi sticker
  • Message.typing(botToken, chatId, debug?) - Typing indicator
  • Message.uploadPhoto(botToken, chatId, debug?) - Upload photo indicator
  • Message.broadcast(botToken, chatIds, text, debug?) - Broadcast

Webhook API

  • Webhook.setWebhook(botToken, params, debug?) - Set webhook
  • Webhook.deleteWebhook(botToken, debug?) - Delete webhook
  • Webhook.getWebhookInfo(botToken, debug?) - Get webhook info
  • Webhook.getUpdates(botToken, params?, debug?) - Long polling
  • Webhook.startPolling(botToken, handlers, options?, debug?) - Auto polling
  • Webhook.processWebhook(payload, handlers, debug?) - Process webhook
  • Webhook.createMiddleware(secretToken, handlers, debug?) - Express middleware

💡 Tips

  1. Multi-tenant: Dùng Service API với botToken parameter
  2. Single bot: Dùng Instance API với createBot()
  3. Debug: Thêm true làm parameter cuối để enable logging
  4. Error handling: Luôn wrap trong try-catch với ZaloBotError
  5. 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

Examples

Xem thêm examples trong folder examples/:

  • simple-bot.ts - Bot đơn giản với instance API
  • static-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