maxbot

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 9 Imported by: 0

README

Maxbot

Go Reference Go Report Card

Библиотека, вдохновлённая библиотекой telebot. Библиотека авторов Max max-bot-api-client-go имеет фатальный недостаток — её писал не я. Не для продакшна (not production ready). Пока что не оттестированно и не дописано.

Ссылки

Возможности

  • 🚀 Простой и понятный API
  • 🔄 Long Polling и Webhook
  • 🎨 Inline клавиатуры
  • 📁 Отправка файлов (фото, видео, аудио, документы)
  • 🛡️ Middleware система
  • 👥 Поддержка групповых чатов
  • 📊 Встроенные метрики
  • ⚡ Готовые middleware (rate limiting, whitelist, и др.)

Установка

go get github.com/demen1n/maxbot

Быстрый старт

package main

import (
    "log"
    "os"
    
    "github.com/demen1n/maxbot"
)

func main() {
    b, err := maxbot.NewBot(maxbot.Settings{
        Token: os.Getenv("MAX_BOT_TOKEN"),
    })
    if err != nil {
        log.Fatal(err)
    }
    
    b.Handle("/start", func(c maxbot.Context) error {
        return c.Send("👋 Привет!")
    })
    
    b.Start()
}

Документация

Создание бота
b, err := maxbot.NewBot(maxbot.Settings{
    Token:  "your-bot-token",
    URL:    maxbot.DefaultAPIURL, // опционально
    Logger: log.Default(),         // опционально
    Poller: &maxbot.LongPoller{    // опционально
        Timeout: 30 * time.Second,
    },
    OnError: func(err error, c maxbot.Context) {
        // глобальный обработчик ошибок
    },
})
Обработка команд
// Простая команда
b.Handle("/start", func(c maxbot.Context) error {
    return c.Send("Привет!")
})

// Команда с аргументами
b.Handle("/echo", func(c maxbot.Context) error {
    return c.Send(c.Payload())
})

// Получение аргументов как слайс
b.Handle("/user", func(c maxbot.Context) error {
    args := c.Args() // /user John Doe -> ["John", "Doe"]
    if len(args) == 0 {
        return c.Send("Укажите имя пользователя")
    }
    return c.Send("Привет, " + args[0])
})
Inline клавиатуры
b.Handle("/menu", func(c maxbot.Context) error {
    menu := &maxbot.ReplyMarkup{}
    
    // Добавляем кнопки построчно
    menu.Row(
        menu.Data("Кнопка 1", "btn1"),
        menu.Data("Кнопка 2", "btn2"),
    )
    menu.Row(
        menu.URL("Открыть сайт", "https://example.com"),
    )
    
    return c.Send("Выберите действие:", menu)
})

// Обработка нажатий
menu := &maxbot.ReplyMarkup{}
b.Handle(&menu.Data("Кнопка 1", "btn1"), func(c maxbot.Context) error {
    return c.Send("Вы нажали кнопку 1")
})
Отправка файлов
// Фото
photo := &maxbot.Photo{FileID: "file_id"}
b.Send(user, photo, &maxbot.SendOptions{
    Text: "Подпись к фото",
})

// Документ
doc := &maxbot.Document{Token: "file_token"}
b.Send(user, doc)

// Загрузка файла
token, err := b.UploadFile("image", "photo.jpg", fileData)
Редактирование сообщений
b.Handle("/edit", func(c maxbot.Context) error {
    msg := c.Message()
    return c.Edit("Отредактированный текст")
})

// Редактирование с клавиатурой
menu := &maxbot.ReplyMarkup{}
menu.Row(menu.Data("Новая кнопка", "new"))
b.Edit(msg, "Новый текст", menu)
Middleware
import "github.com/demen1n/maxbot/middleware"

// Логирование
b.Handle("/start", handler, middleware.Logger())

// Whitelist пользователей
b.Handle("/admin", adminHandler, 
    middleware.Whitelist(123456789, 987654321))

// Rate limiting
b.Handle("/weather", weatherHandler,
    middleware.RateLimit(5, time.Minute))

// Только приватные чаты
b.Handle("/settings", settingsHandler,
    middleware.OnlyPrivate())

// Цепочка middleware
b.Handle("/cmd", handler,
    middleware.Chain(
        middleware.Logger(),
        middleware.AutoRespond(),
        middleware.Throttle(5 * time.Second),
    ))
Доступные middleware
  • Logger() - логирование запросов
  • AutoRespond() - автоответ на callback queries
  • Recover() - восстановление после паник
  • Whitelist(ids...) - разрешить только указанным пользователям
  • Blacklist(ids...) - заблокировать указанных пользователей
  • Throttle(duration) - ограничение частоты использования
  • RateLimit(max, window) - лимит запросов в окне времени
  • OnlyPrivate() - только приватные чаты
  • OnlyGroups() - только групповые чаты
  • IgnoreBots() - игнорировать сообщения от ботов
  • CommandArgs(min, usage) - проверка минимального числа аргументов
  • Chain(...) - объединение нескольких middleware
Webhook
webhook := &maxbot.Webhook{
    Listen:   ":8443",
    Endpoint: "/webhook",
    URL:      "https://example.com/webhook",
    Secret:   "secret_key",
}

b, err := maxbot.NewBot(maxbot.Settings{
    Token:  token,
    Poller: webhook,
})

// Регистрация webhook в MAX API
b.SetWebhook(webhook.URL, []string{"message", "callback"}, webhook.Secret)
Работа с чатами
// Получить информацию о чате
chat, err := b.GetChat(chatID)

// Получить администраторов
admins, err := b.GetChatAdmins(chatID)

// Управление участниками
b.KickChatMember(chatID, userID)
b.InviteChatMembers(chatID, []int64{user1, user2})
b.PromoteChatMember(chatID, userID)
b.DemoteChatMember(chatID, userID)

// Закрепление сообщений
b.PinMessage(chatID, messageID)
b.UnpinMessage(chatID)

// Действия в чате (typing, отправка фото и т.д.)
b.SendChatAction(chatID, maxbot.ActionTyping)
Context методы
func handler(c maxbot.Context) error {
    // Информация об обновлении
    c.Bot()      // *Bot
    c.Update()   // Update
    c.Message()  // *Message
    c.Callback() // *CallbackQuery
    c.Sender()   // *User
    c.Chat()     // *Chat
    
    // Текст и аргументы
    c.Text()     // текст сообщения
    c.Args()     // аргументы команды как слайс
    c.Payload()  // всё после команды как строка
    
    // Отправка
    c.Send("текст", opts...)
    c.Reply("текст", opts...)
    c.Edit("новый текст", opts...)
    c.Delete()
    c.Respond() // ответ на callback
    
    // Хранилище
    c.Set("key", value)
    c.Get("key")
    
    return nil
}
Метрики
metrics := &middleware.Metrics{}

b.Handle("/start", handler, metrics.Middleware())

// Получить статистику
b.Handle("/stats", func(c maxbot.Context) error {
    return c.Send(metrics.GetStats())
})

Documentation

Index

Constants

View Source
const (
	DefaultAPIURL  = "https://platform-api.max.ru"
	DefaultTimeout = 10 * time.Second
)
View Source
const (
	OnMessage  = "\amessage"  // любое входящее сообщение
	OnText     = "\atext"     // текстовое сообщение (без команд)
	OnCallback = "\acallback" // нажатие inline-кнопки
	OnPhoto    = "\aphoto"
	OnVideo    = "\avideo"
	OnAudio    = "\aaudio"
	OnDocument = "\adocument"
)

Common endpoint constants for message routing.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Type    string                 `json:"type"`
	Payload map[string]interface{} `json:"payload,omitempty"`
}

Attachment represents a message attachment (keyboard, file, etc).

type Audio

type Audio struct {
	FileID    string `json:"file_id"`
	Duration  int    `json:"duration"`
	Title     string `json:"title,omitempty"`
	Performer string `json:"performer,omitempty"`
	Token     string `json:"token,omitempty"`
}

Audio represents an audio file.

func (*Audio) Send

func (a *Audio) Send(b *Bot, to Recipient, opts *SendOptions) (*Message, error)

Send implements Sendable interface for Audio.

type Bot

type Bot struct {
	Token  string
	URL    string
	Poller Poller
	Client *http.Client
	Logger *log.Logger
	// contains filtered or unexported fields
}

Bot represents a MAX bot instance.

func NewBot

func NewBot(s Settings) (*Bot, error)

NewBot creates a new bot instance with the given settings.

func (*Bot) Delete

func (b *Bot) Delete(msg Editable) error

Delete deletes a message.

func (*Bot) DeleteCommands

func (b *Bot) DeleteCommands() error

DeleteCommands removes all bot commands.

func (*Bot) DeleteWebhook

func (b *Bot) DeleteWebhook() error

DeleteWebhook removes the webhook subscription.

func (*Bot) DemoteChatMember

func (b *Bot) DemoteChatMember(chatID int64, userID int64) error

DemoteChatMember removes administrator rights from a user.

func (*Bot) Edit

func (b *Bot) Edit(msg Editable, what interface{}, opts ...interface{}) (*Message, error)

Edit edits an existing message. For MAX API, uses message mid for editing.

func (*Bot) GetChat

func (b *Bot) GetChat(chatID int64) (*Chat, error)

GetChat retrieves chat information by ID.

func (*Bot) GetChatAdmins

func (b *Bot) GetChatAdmins(chatID int64) ([]ChatMember, error)

GetChatAdmins gets the list of chat administrators.

func (*Bot) GetChatMember

func (b *Bot) GetChatMember(chatID int64, userID int64) (*ChatMember, error)

GetChatMember gets information about a specific chat member.

func (*Bot) GetPinnedMessage

func (b *Bot) GetPinnedMessage(chatID int64) (*Message, error)

GetPinnedMessage retrieves the pinned message.

func (*Bot) GetUploadURL

func (b *Bot) GetUploadURL(fileType string) (*UploadInfo, error)

GetUploadURL gets a URL for uploading files. fileType can be: "image", "video", "audio", "file"

func (*Bot) GetWebhook

func (b *Bot) GetWebhook() (*WebhookInfo, error)

GetWebhook returns current webhook information.

func (*Bot) Handle

func (b *Bot) Handle(endpoint interface{}, handler HandlerFunc, m ...MiddlewareFunc)

Handle registers a handler for the specified endpoint. Endpoint can be a string (command or endpoint constant) or *InlineButton. Middleware is applied in the order provided.

func (*Bot) InviteChatMembers

func (b *Bot) InviteChatMembers(chatID int64, userIDs []int64) error

InviteChatMembers adds users to the chat.

func (*Bot) KickChatMember

func (b *Bot) KickChatMember(chatID int64, userID int64) error

KickChatMember removes a user from the chat.

func (*Bot) LeaveChat

func (b *Bot) LeaveChat(chatID int64) error

LeaveChat makes the bot leave the chat.

func (*Bot) Me

func (b *Bot) Me() (*User, error)

Me returns information about the bot.

func (*Bot) PinMessage

func (b *Bot) PinMessage(chatID int64, messageID string) error

PinMessage pins a message in the chat.

func (*Bot) ProcessUpdate

func (b *Bot) ProcessUpdate(u Update)

ProcessUpdate processes a single update by finding and executing the appropriate handler.

func (*Bot) PromoteChatMember

func (b *Bot) PromoteChatMember(chatID int64, userID int64) error

PromoteChatMember promotes a user to administrator.

func (*Bot) Raw

func (b *Bot) Raw(method, endpoint string, payload interface{}) ([]byte, error)

Raw makes a raw API request.

func (*Bot) Send

func (b *Bot) Send(to Recipient, what interface{}, opts ...interface{}) (*Message, error)

Send sends a message to the specified recipient. Returns the sent message or an error.

func (*Bot) SendChatAction

func (b *Bot) SendChatAction(chatID int64, action ChatAction) error

SendChatAction sends a chat action (typing, sending photo, etc).

func (*Bot) SetCommands

func (b *Bot) SetCommands(commands []BotCommand) error

SetCommands sets the bot's command list.

func (*Bot) SetWebhook

func (b *Bot) SetWebhook(url string, updateTypes []string, secret string) error

SetWebhook registers a webhook URL with MAX API.

func (*Bot) Start

func (b *Bot) Start()

Start begins the bot polling loop and blocks until stopped.

func (*Bot) UnpinMessage

func (b *Bot) UnpinMessage(chatID int64) error

UnpinMessage unpins the pinned message.

func (*Bot) UploadFile

func (b *Bot) UploadFile(fileType string, fileName string, fileData []byte) (string, error)

UploadFile uploads a file to MAX servers.

type BotCommand

type BotCommand struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

BotCommand represents a bot command with description.

type CallbackQuery

type CallbackQuery struct {
	CallbackID string `json:"callback_id"`
	Timestamp  int64  `json:"timestamp"`
	User       *User  `json:"user"`
	Payload    string `json:"payload"`
}

CallbackQuery represents a callback button press.

type CallbackResponse

type CallbackResponse struct {
	Text      string `json:"text,omitempty"`
	ShowAlert bool   `json:"show_alert,omitempty"`
	URL       string `json:"url,omitempty"`
}

CallbackResponse represents a response to callback query.

type Chat

type Chat struct {
	ID          int64  `json:"chat_id"`
	Type        string `json:"type"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
}

Chat represents a MAX chat.

func (*Chat) Recipient

func (c *Chat) Recipient() string

Recipient returns chat ID as recipient identifier.

type ChatAction

type ChatAction string

ChatAction represents a bot action in chat (typing, sending media, etc).

const (
	ActionTyping       ChatAction = "typing_on"
	ActionSendingPhoto ChatAction = "sending_photo"
	ActionSendingVideo ChatAction = "sending_video"
	ActionSendingAudio ChatAction = "sending_audio"
	ActionSendingFile  ChatAction = "sending_file"
	ActionMarkSeen     ChatAction = "mark_seen"
)

type ChatMember

type ChatMember struct {
	User   *User  `json:"user"`
	Status string `json:"status"`
}

ChatMember represents a chat member with their status.

type Context

type Context interface {
	Bot() *Bot
	Update() Update
	Message() *Message
	Callback() *CallbackQuery

	Sender() *User
	Chat() *Chat
	Text() string
	Args() []string
	Payload() string

	Send(what interface{}, opts ...interface{}) error
	Reply(what interface{}, opts ...interface{}) error
	Edit(what interface{}, opts ...interface{}) error
	Delete() error
	Respond(opts ...*CallbackResponse) error

	Get(key string) interface{}
	Set(key string, val interface{})
}

Context represents the context of an incoming update. It provides convenient methods to access update data and respond to users.

type Document

type Document struct {
	FileID   string `json:"file_id"`
	FileName string `json:"file_name"`
	FileSize int    `json:"file_size"`
	Token    string `json:"token,omitempty"`
}

Document represents a document file.

func (*Document) Send

func (d *Document) Send(b *Bot, to Recipient, opts *SendOptions) (*Message, error)

Send implements Sendable interface for Document.

type EditMessage

type EditMessage struct {
	MessageID int    `json:"message_id"`
	ChatID    int64  `json:"chat_id"`
	Text      string `json:"text"`
}

EditMessage represents a message edit request.

type Editable

type Editable interface {
	MessageSig() (messageID int, chatID int64)
}

Editable is any object that provides message signature for editing.

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc represents a handler function for processing updates.

type InlineButton

type InlineButton struct {
	Text    string `json:"text"`
	Type    string `json:"type"`
	Payload string `json:"payload,omitempty"`
	URL     string `json:"url,omitempty"`
	Data    string `json:"-"` // используется для роутинга
}

InlineButton represents an inline keyboard button.

type LinkedMessage added in v0.1.1

type LinkedMessage struct {
	// type может быть "reply" или "forward"
	Type    string       `json:"type"`
	Sender  *User        `json:"sender,omitempty"`
	ChatID  int64        `json:"chat_id,omitempty"`
	Message *MessageBody `json:"message,omitempty"`
}

LinkedMessage представляет цитируемое или пересланное сообщение.

type LongPoller

type LongPoller struct {
	Limit   int
	Timeout time.Duration
	Marker  *int64
}

LongPoller implements long polling for receiving updates.

func (*LongPoller) Poll

func (p *LongPoller) Poll(b *Bot, updates chan Update, stop chan struct{})

Poll starts the long polling loop.

type MarkupElement added in v0.1.1

type MarkupElement struct {
	From   int    `json:"from"`
	Length int    `json:"length"`
	Type   string `json:"type"` // "emphasized", "strong", "strikethrough", etc.
}

MarkupElement представляет элемент форматирования текста (bold, italic и т.д.).

type Message

type Message struct {
	RecipientInfo *RecipientInfo `json:"recipient,omitempty"`
	Sender        *User          `json:"sender,omitempty"`
	Timestamp     int64          `json:"timestamp"`
	Body          *MessageBody   `json:"body,omitempty"`
}

Message represents a MAX message.

func (*Message) Chat

func (m *Message) Chat() *Chat

Chat converts recipient info to Chat object.

func (*Message) From

func (m *Message) From() *User

From returns message sender.

func (*Message) IsReply added in v0.1.1

func (m *Message) IsReply() bool

IsReply reports whether the message is a reply to another message.

func (*Message) MessageSig

func (m *Message) MessageSig() (int, int64)

MessageSig returns message signature for compatibility with Editable interface. Note: MAX API uses string mid, so message_id is always 0.

func (*Message) Mid

func (m *Message) Mid() string

Mid returns MAX message ID as string.

func (*Message) ReplyTo added in v0.1.1

func (m *Message) ReplyTo() *LinkedMessage

ReplyTo returns the message this message is a reply to, or nil.

func (*Message) Text

func (m *Message) Text() string

Text returns message text content.

type MessageAttachment added in v0.1.1

type MessageAttachment struct {
	Type       string                 `json:"type"`
	CallbackID string                 `json:"callback_id,omitempty"`
	Payload    map[string]interface{} `json:"payload,omitempty"`
}

MessageAttachment представляет вложение в полученном сообщении.

type MessageBody

type MessageBody struct {
	Mid         string              `json:"mid"`
	Seq         int64               `json:"seq"`
	Text        string              `json:"text"`
	Attachments []MessageAttachment `json:"attachments,omitempty"`
	Markup      []MarkupElement     `json:"markup,omitempty"`
	// link содержит информацию о цитируемом сообщении (reply/forward).
	// в MAX API это поле называется "link".
	Link *LinkedMessage `json:"link,omitempty"`
}

MessageBody represents message content.

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc represents middleware that wraps a handler.

type Photo

type Photo struct {
	FileID string `json:"file_id"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
	URL    string `json:"url,omitempty"`
}

Photo represents a photo attachment.

func (*Photo) Send

func (p *Photo) Send(b *Bot, to Recipient, opts *SendOptions) (*Message, error)

Send implements Sendable interface for Photo.

type Poller

type Poller interface {
	Poll(b *Bot, updates chan Update, stop chan struct{})
}

Poller is an interface for receiving updates.

type Recipient

type Recipient interface {
	Recipient() string
}

Recipient is any object that can receive messages.

type RecipientInfo

type RecipientInfo struct {
	ChatID   int64  `json:"chat_id"`
	ChatType string `json:"chat_type"`
	UserID   int64  `json:"user_id"`
}

RecipientInfo contains message recipient information.

type ReplyMarkup

type ReplyMarkup struct {
	InlineKeyboard [][]InlineButton `json:"inline_keyboard,omitempty"`
}

ReplyMarkup represents inline keyboard markup.

func (*ReplyMarkup) Data

func (r *ReplyMarkup) Data(text, data string, payload ...interface{}) InlineButton

Data creates a callback button. If payload is provided as structured data, it will be marshaled to JSON.

func (*ReplyMarkup) Row

func (r *ReplyMarkup) Row(buttons ...InlineButton)

Row adds a row of buttons to the keyboard.

func (*ReplyMarkup) URL

func (r *ReplyMarkup) URL(text, url string) InlineButton

URL creates a link button.

type SendMessage

type SendMessage struct {
	ChatID      string       `json:"chat_id"`
	Text        string       `json:"text"`
	Format      string       `json:"format,omitempty"`
	Attachments []Attachment `json:"attachments,omitempty"`
}

SendMessage represents an outgoing message request.

type SendOptions

type SendOptions struct {
	Text        string
	Format      string
	Attachments []Attachment
}

SendOptions represents message sending options.

type Sendable

type Sendable interface {
	Send(*Bot, Recipient, *SendOptions) (*Message, error)
}

Sendable is any object that can send itself (photos, videos, etc).

type Settings

type Settings struct {
	URL     string
	Token   string
	Poller  Poller
	Logger  *log.Logger
	OnError func(error, Context)
}

Settings represents bot configuration.

type StoredMessage

type StoredMessage struct {
	MessageID int   `json:"message_id"`
	ChatID    int64 `json:"chat_id"`
}

StoredMessage is a lightweight message reference for database storage.

func (*StoredMessage) MessageSig

func (sm *StoredMessage) MessageSig() (int, int64)

type Update

type Update struct {
	UpdateType    string         `json:"update_type"`
	Timestamp     int64          `json:"timestamp"`
	UserLocale    string         `json:"user_locale,omitempty"`
	Message       *Message       `json:"message,omitempty"`
	CallbackQuery *CallbackQuery `json:"callback,omitempty"`
}

Update represents an incoming update from MAX API.

type UploadInfo

type UploadInfo struct {
	URL   string `json:"url"`
	Token string `json:"token,omitempty"`
}

UploadInfo represents upload URL information from MAX API.

type User

type User struct {
	ID             int64  `json:"user_id"`
	Name           string `json:"name"`
	FirstName      string `json:"first_name"`
	LastName       string `json:"last_name"`
	Username       string `json:"username,omitempty"`
	IsBot          bool   `json:"is_bot"`
	LastActivityAt int64  `json:"last_activity_time"`
}

User represents a MAX user.

func (*User) Recipient

func (u *User) Recipient() string

Recipient returns user ID as recipient identifier.

type Video

type Video struct {
	FileID   string `json:"file_id"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
	Duration int    `json:"duration"`
	Token    string `json:"token,omitempty"`
}

Video represents a video attachment.

func (*Video) Send

func (v *Video) Send(b *Bot, to Recipient, opts *SendOptions) (*Message, error)

Send implements Sendable interface for Video.

type Webhook

type Webhook struct {
	Listen   string // адрес для прослушивания, например ":8443"
	Endpoint string // endpoint для webhook, например "/webhook"
	URL      string // публичный URL бота для регистрации
	Secret   string // секретный ключ для проверки
	// contains filtered or unexported fields
}

Webhook implements webhook receiver for getting updates.

func (*Webhook) Poll

func (w *Webhook) Poll(b *Bot, updates chan Update, stop chan struct{})

Poll starts the webhook server.

type WebhookInfo

type WebhookInfo struct {
	URL         string   `json:"url"`
	UpdateTypes []string `json:"update_types,omitempty"`
	Secret      string   `json:"secret,omitempty"`
}

WebhookInfo represents webhook subscription information.

Directories

Path Synopsis
Package middleware provides common middleware implementations for maxbot.
Package middleware provides common middleware implementations for maxbot.

Jump to

Keyboard shortcuts

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