zalobotapi

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2025 License: MIT Imports: 10 Imported by: 0

README

go-zalo-bot-api

A batteries-included Go client for the Zalo Bot API. It wraps the HTTP endpoints with typed request/response models, retry-aware transports, and ergonomic helpers so you can focus on your bot logic instead of wiring.

Features

  • ✅ Lightweight, concurrency-safe Client abstraction with configurable base URL, custom HTTP client, and user agent.
  • ✅ Ready-made endpoint helpers for common actions (get bot info, manage webhooks, send messages, stickers, and chat actions).
  • ✅ Iterator-based long-polling helper that smooths over pagination and transient failures.
  • ✅ Pluggable logging interface with structured logging support out of the box.

Installation

go get github.com/nduyhai/go-zalo-bot-api

Quick start

Create a client with your bot token and call any endpoint helper. Each request accepts per-call options such as timeouts so you can control retry and cancellation behaviour.

package main

import (
    "context"
    "log/slog"
    "time"

    zalobotapi "github.com/nduyhai/go-zalo-bot-api"
    "github.com/nduyhai/go-zalo-bot-api/endpoints"
)

func main() {
    botToken := "<your bot token>"
    chatID := "<chat id>"

    logger := zalobotapi.NewSlogLogger(slog.Default())
    client := zalobotapi.New(botToken,
        zalobotapi.WithLogger(logger),
        zalobotapi.WithUserAgent("my-bot/1.0"),
    )

    ctx := context.Background()

    // Call any endpoint helper. This example sends a message with a per-call timeout.
    _, err := endpoints.SendMessage(ctx, client, endpoints.SendMessageReq{
        ChatID: chatID,
        Text:   "Xin chào từ go-zalo-bot-api!",
    }, zalobotapi.WithTimeout(5*time.Second))
    if err != nil {
        logger.Error("send message", map[string]any{"err": err})
    }
}

Looking for a more complete example (with retries, custom transports, and long-polling for updates)? Check out cmd/example/main.go.

Environment variables

The example program expects:

  • BOT_TOKEN – the access token of your Official Account bot.
  • CHAT_ID – the identifier of the conversation you want to send messages to.

You can use a .env file together with godotenv to load these values during development.

Development

  1. Export the required environment variables (or create a .env file) with values for BOT_TOKEN and CHAT_ID.
  2. Run the example bot:
    make run
    
    This executes go run ./cmd/example so you can verify connectivity and explore the iterator-based long-polling helpers.

License

Distributed under the MIT License.

Documentation

Index

Constants

View Source
const DefaultBaseURL = "https://bot-api.zapps.me"

Variables

This section is empty.

Functions

func IsNotFound

func IsNotFound(err error) bool

func IsRateLimited

func IsRateLimited(err error) bool

func IsTimeout

func IsTimeout(err error) bool

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized Convenience helpers

Types

type CallOpt

type CallOpt func(*callCfg)

func WithTimeout

func WithTimeout(d time.Duration) CallOpt

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is concurrency-safe and cheap to use; reuse one instance per process.

func New

func New(botToken string, opts ...Option) *Client

New returns a new client.

func (*Client) DoJSON

func (c *Client) DoJSON(ctx context.Context, method, path string, req any, out any, opts ...CallOpt) ([]byte, error)

DoJSON sends JSON body and decodes JSON response into out (if non-nil). It also maps HTTP and API (envelope) errors.

type HTTPError

type HTTPError struct {
	Status     int
	Message    string        // friendly message from the table above (or default)
	Body       string        // raw body (truncated upstream if you want)
	RetryAfter time.Duration // parsed from header when present
	Temporary  bool          // hint for retry/backoff
}

HTTPError represents non-2xx responses.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Logger

type Logger interface {
	Debug(msg string, fields map[string]any)
	Info(msg string, fields map[string]any)
	Warn(msg string, fields map[string]any)
	Error(msg string, fields map[string]any)
}

Logger is minimal to avoid dependencies; plug your own slog/zap adapter.

type Option

type Option func(*Client)

Option configures a Client.

func WithBaseURL

func WithBaseURL(u string) Option

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

func WithLogger

func WithLogger(l Logger) Option

func WithUserAgent

func WithUserAgent(ua string) Option

type SlogLogger

type SlogLogger struct {
	// contains filtered or unexported fields
}

SlogLogger implements the Logger interface using log/slog.

func NewSlogLogger

func NewSlogLogger(l *slog.Logger) *SlogLogger

NewSlogLogger wraps an existing slog.Logger.

func (*SlogLogger) Debug

func (s *SlogLogger) Debug(msg string, fields map[string]any)

func (*SlogLogger) Error

func (s *SlogLogger) Error(msg string, fields map[string]any)

func (*SlogLogger) Info

func (s *SlogLogger) Info(msg string, fields map[string]any)

func (*SlogLogger) Warn

func (s *SlogLogger) Warn(msg string, fields map[string]any)

Directories

Path Synopsis
cmd
example command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL