Skip to main content

python-zalo-bot

This SDK package is developed based on python-telegram-bot – a popular open-source library for Telegram Bot, licensed under MIT License.

This SDK version is customized and extended to meet the requirements for building Zalo Bot. All modifications comply with the MIT license and retain the original author's copyright.

python-zalo-bot

A Python wrapper for the Zalo Bot API — making it easy to build chatbots for the Zalo ecosystem, inspired by python-telegram-bot.

Require

  • Python >= 3.8

Install

pip install python-zalo-bot

Example

Introduction to the API

import asyncio
import zalo_bot

async def main():
    bot = zalo_bot.Bot("YOUR_BOT_TOKEN")
    async with bot:
        me = await bot.get_me()
        print(f"Bot's name: {me.account_name}, ID: {me.id}")
        update = await bot.get_update(timeout=60)
        chat_id = update.message.chat.id if update and update.message else "CHAT_ID"
        await bot.send_message(chat_id, "Hello from Zalo Bot!")
        await bot.send_photo(chat_id, "Ảnh demo", "https://placehold.co/600x400")
        await bot.send_sticker(chat_id, "d063f44dc80821567819")

if __name__ == '__main__':
    asyncio.run(main())

Long Polling

from zalo_bot import Update
from zalo_bot.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(f"Chào {update.effective_user.display_name}! Tôi là chatbot!")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(f"Bạn vừa nói: {update.message.text}")

if __name__ == "__main__":
    app = ApplicationBuilder().token("ZALO_BOT_TOKEN").build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    print("🤖 Bot đang chạy...")
    try:
        app.run_polling()
    except KeyboardInterrupt:
        print("Bot đã dừng lại.")

Webhook

from flask import Flask, request
from zalo_bot import Bot, Update
from zalo_bot.ext import Dispatcher, CommandHandler, MessageHandler, filters

app = Flask(__name__)
TOKEN = 'ZALO_BOT_TOKEN'
bot = Bot(token=TOKEN)

async def start(update: Update, context):
    await update.message.reply_text(f"Xin chào {update.effective_user.display_name}!")

async def echo(update: Update, context):
    await update.message.reply_text(f"Bạn vừa nói: {update.message.text}")

with app.app_context():
    webhook_url = 'your_webhook_url'
    bot.set_webhook(url=webhook_url, secret_token='your_secret_token_here')

    dispatcher = Dispatcher(bot, None, workers=0)
    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

@app.route('/webhook', methods=['POST'])
def webhook():
    update = Update.de_json(request.get_json(force=True)['result'], bot)
    dispatcher.process_update(update)
    return 'ok'

if __name__ == '__main__':
    app.run(port=8443)

API

class zalo_bot.Bot(token: str)

Khởi tạo bot với mã thông báo xác thực.

Methods

  • async get_me() -> User
    Lấy thông tin tài khoản bot.

  • async get_update(timeout: int = 60) -> Optional[Update]
    Lấy một cập nhật mới từ server.

  • async send_message(chat_id: str, text: str) -> Message
    Gửi tin nhắn văn bản.

  • async send_photo(chat_id: str, caption: str, photo_url: str) -> Message
    Gửi hình ảnh với chú thích.

  • async send_sticker(chat_id: str, sticker_id: str) -> Message
    Gửi sticker.

  • async send_chat_action(chat_id: str, action: str) -> bool
    Gửi hành động chat (typing).

  • async set_webhook(url: str, secret_token: str) -> bool
    Cài đặt webhook.

  • async get_webhook_info() -> WebhookInfo
    Lấy thông tin webhook.

  • async delete_webhook() -> bool
    Xóa webhook.


class zalo_bot.Message(...)

Đại diện cho một tin nhắn gửi đến bot. Cung cấp các phương thức trả lời nhanh.

Methods

  • async reply_text(text: str)
    Trả lời văn bản.

  • async reply_photo(photo_url: str, caption: str = "")
    Gửi ảnh kèm chú thích.

  • async reply_sticker(sticker_id: str)
    Gửi sticker trả lời.

  • async reply_action(action: str)
    Gửi hành động chat trả lời (typing).


Chat Actions

Chat actions cho phép bot hiển thị các chỉ báo trực quan như "đang soạn tin..." để cải thiện trải nghiệm người dùng.

Các hành động có sẵn

from zalo_bot.constants import ChatAction

# Các hành động cơ bản
ChatAction.TYPING              # Đang soạn tin...

Cách sử dụng

import asyncio
from zalo_bot import Update
from zalo_bot.ext import ApplicationBuilder, CommandHandler, ContextTypes
from zalo_bot.constants import ChatAction

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # Hiển thị "đang soạn tin..." trước khi trả lời
    await context.bot.send_chat_action(
        chat_id=update.message.chat.id, 
        action=ChatAction.TYPING
    )
    await asyncio.sleep(2)
    await update.message.reply_text("Chào bạn!")

zalo_bot.ext

Thư mục ext (extension) cung cấp các thành phần mở rộng giúp xây dựng bot theo cách hướng sự kiện (event-based)

ApplicationBuilder

Khởi tạo một ứng dụng bot với cấu hình tùy chỉnh.

from zalo_bot.ext import ApplicationBuilder

app = ApplicationBuilder().token("ZALO_BOT_TOKEN").build()

Phương thức:

  • token(token: str) – cấu hình token.
  • build() – khởi tạo Application từ builder.

Application

Một thực thể điều phối bot, xử lý sự kiện và chạy polling hoặc webhook.

Phương thức chính:

  • add_handler(handler: BaseHandler) – thêm handler xử lý lệnh hoặc tin nhắn.
  • run_polling() – khởi động polling để nhận update.

CommandHandler

Xử lý các lệnh kiểu /start, /echo,...

CommandHandler("start", start_callback)

MessageHandler

Xử lý tin nhắn văn bản, hình ảnh,... phù hợp với filter.

MessageHandler(filters.TEXT & ~filters.COMMAND, echo_callback)

filters

Cung cấp các filter để lọc loại dữ liệu từ tin nhắn:

  • filters.TEXT – tin nhắn dạng văn bản
  • filters.COMMAND – tin nhắn là command (bắt đầu với /)
  • filters.TEXT & ~filters.COMMAND – chỉ văn bản, không phải command

Ví dụ sử dụng ext

from zalo_bot import Update
from zalo_bot.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(f"Chào {update.effective_user.display_name}!")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(f"Bạn vừa nói: {update.message.text}")

if __name__ == "__main__":
    app = ApplicationBuilder().token("ZALO_BOT_TOKEN").build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    app.bot.delete_webhook()
    app.run_polling()

Metadata

Release files for python-zalo-bot 0.1.9

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-zalo-bot 0.1.9
File Size Uploaded
python_zalo_bot-0.1.9.tar.gz 60.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for python-zalo-bot 0.1.9
File Interpreter ABI Platform
python_zalo_bot-0.1.9-py3-none-any.whl Python 3 none any Details

Total release size: 142.6 kB

Release files / python_zalo_bot-0.1.9.tar.gz

Download URL python_zalo_bot-0.1.9.tar.gz
Size 60.3 kB
Tags Source
SHA-256 checksum
How to use checksums
6b91664355e65b97c2ac42c2abe0160aab24937c99d9b1fe5a669783bc312dda
BLAKE2b-256 checksum
How to use checksums
9df8a26819178c5f3a20f0de5cc65c3fa920dc7dc916045eeae47a261f888b7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.8.20

Release files / python_zalo_bot-0.1.9-py3-none-any.whl

Download URL python_zalo_bot-0.1.9-py3-none-any.whl
Size 82.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7cfa5fc5c8ff2c02a3b213c3e0c5f63bee83b966cd267fcb5fb13840725f453b
BLAKE2b-256 checksum
How to use checksums
9c9da058627842ef328d10e1acd49591cc4dde64c3cd912fe4fcc36b2e39eefc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.8.20

Release history Release notifications | RSS feed

This release

0.1.9 This release

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

0.0.3

2 release files

0.0.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page