maxbot

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 12 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
	APIVersion     = "1.2.5"
)
View Source
const (
	OnMessage  = "\amessage"  // any incoming message (message_created fallback)
	OnText     = "\atext"     // plain text message
	OnCallback = "\acallback" // inline button press (catch-all)
	OnPhoto    = "\aphoto"
	OnVideo    = "\avideo"
	OnAudio    = "\aaudio"
	OnDocument = "\adocument"

	// Update-type specific endpoints.
	OnMessageEdited    = "\amessage_edited"
	OnMessageRemoved   = "\amessage_removed"
	OnBotStarted       = "\abot_started"
	OnBotAdded         = "\abot_added"
	OnBotRemoved       = "\abot_removed"
	OnBotStopped       = "\abot_stopped"
	OnUserAdded        = "\auser_added"
	OnUserRemoved      = "\auser_removed"
	OnChatTitleChanged = "\achat_title_changed"
	OnDialogRemoved    = "\adialog_removed"
	OnDialogCleared    = "\adialog_cleared"
)

Common endpoint constants for message routing.

View Source
const (
	UpdateMessageCreated   = "message_created"
	UpdateMessageEdited    = "message_edited"
	UpdateMessageRemoved   = "message_removed"
	UpdateMessageCallback  = "message_callback"
	UpdateBotAdded         = "bot_added"
	UpdateBotRemoved       = "bot_removed"
	UpdateBotStarted       = "bot_started"
	UpdateBotStopped       = "bot_stopped"
	UpdateUserAdded        = "user_added"
	UpdateUserRemoved      = "user_removed"
	UpdateChatTitleChanged = "chat_title_changed"
	UpdateDialogRemoved    = "dialog_removed"
	UpdateDialogCleared    = "dialog_cleared"
)

Update type constants.

View Source
const WebhookSecretHeader = "X-Max-Bot-Api-Secret"

WebhookSecretHeader is the HTTP header MAX uses to send the webhook secret.

Variables

This section is empty.

Functions

func IsAPIError added in v0.3.0

func IsAPIError(err error, codes ...int) bool

IsAPIError reports whether err is an *APIError and optionally checks HTTP status codes.

Types

type APIError added in v0.3.0

type APIError struct {
	Code      int    // HTTP status code
	ErrorText string // "error" field — short machine-readable description
	Message   string // "code" field — dot-separated error key
	Details   string // "message" field — human-readable description
}

APIError represents an error response from the MAX API. The API body has three fields: error (short code), code (dot-separated key), message (human text).

func (*APIError) Error added in v0.3.0

func (e *APIError) Error() string

func (*APIError) IsAttachmentNotReady added in v0.3.0

func (e *APIError) IsAttachmentNotReady() bool

IsAttachmentNotReady reports whether the error means the uploaded attachment has not been processed by MAX yet and the request should be retried.

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 {
	UploadedInfo
}

Audio represents an uploaded audio file ready to send. Obtain via Bot.UploadMedia("audio", ...).

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) DeleteChat added in v0.2.0

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

DeleteChat removes a group chat.

func (*Bot) DeleteCommands

func (b *Bot) DeleteCommands() error

DeleteCommands removes all bot commands.

func (*Bot) DeleteWebhook

func (b *Bot) DeleteWebhook(webhookURL string) error

DeleteWebhook removes the webhook subscription for the given URL.

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{}) 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, *int64, error)

GetChatAdmins gets the list of chat administrators. Returns members and an optional pagination marker.

func (b *Bot) GetChatByLink(link string) (*Chat, error)

GetChatByLink retrieves chat information by its public link (e.g. "mygroup").

func (*Bot) GetChatMember

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

GetChatMember gets information about a specific chat member.

func (*Bot) GetChatMemberMe added in v0.2.0

func (b *Bot) GetChatMemberMe(chatID int64) (*ChatMember, error)

GetChatMemberMe returns the bot's own membership info in the chat.

func (*Bot) GetChatMembers added in v0.2.0

func (b *Bot) GetChatMembers(chatID, count int64, marker *int64) ([]ChatMember, *int64, error)

GetChatMembers returns members of a chat with optional pagination.

func (*Bot) GetChats added in v0.2.0

func (b *Bot) GetChats(count int, marker *int64) ([]Chat, *int64, error)

GetChats returns group chats the bot participates in. count limits results (0 = server default); marker is the pagination cursor (*nil = start). Returns chats and the next page marker (nil when no more pages).

func (*Bot) GetMessage added in v0.2.0

func (b *Bot) GetMessage(mid string) (*Message, error)

GetMessage retrieves a single message by its mid.

func (*Bot) GetMessages added in v0.2.0

func (b *Bot) GetMessages(chatID int64, count int, from, to int64) ([]Message, *int64, error)

GetMessages retrieves messages in a chat. from/to are optional timestamp boundaries (pass 0 to omit); count limits results.

func (*Bot) GetPinnedMessage

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

GetPinnedMessage retrieves the pinned message.

func (*Bot) GetSpecificChatMembers added in v0.4.0

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

GetSpecificChatMembers retrieves info for a specific set of users in the chat.

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) GetVideoInfo added in v0.2.0

func (b *Bot) GetVideoInfo(videoToken string) (map[string]interface{}, error)

GetVideoInfo returns video metadata by its token.

func (*Bot) GetWebhook

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

GetWebhook returns all active webhook subscriptions.

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, userID int64, block bool) error

KickChatMember removes a user from the chat. Set block=true to also ban the user from rejoining.

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) PatchBot added in v0.4.0

func (b *Bot) PatchBot(patch BotPatch) (*User, error)

PatchBot updates bot properties via PATCH /me.

func (*Bot) PinMessage

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

PinMessage pins a message in the chat. notify controls whether members are notified; pass nil to use server default.

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, userID int64, perms ...ChatAdminPermission) error

PromoteChatMember grants admin rights to a user. perms lists the permissions to grant; if empty, all permissions are granted.

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 Stop() is called.

func (*Bot) Stop added in v0.2.0

func (b *Bot) Stop()

Stop signals the poller to stop and waits for the updates channel to close.

func (*Bot) UnpinMessage

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

UnpinMessage unpins the pinned message.

func (*Bot) UpdateChat added in v0.2.0

func (b *Bot) UpdateChat(chatID int64, fields map[string]interface{}) (*Chat, error)

UpdateChat modifies a group chat (title, description, icon, etc). fields is a map of fields to update, e.g. {"title": "New title"}.

func (*Bot) UploadFile

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

UploadFile is a compatibility wrapper around UploadPhoto/UploadMedia. Deprecated: use UploadPhoto for images and UploadMedia for other types.

func (*Bot) UploadMedia added in v0.4.0

func (b *Bot) UploadMedia(fileType, fileName string, data []byte) (*UploadedInfo, error)

UploadMedia uploads an audio, video or file via multipart/form-data. fileType must be one of: "audio", "video", "file". For audio/video the token comes from the upload URL response (info.Token). For file the token comes from the upload response body.

func (*Bot) UploadPhoto added in v0.4.0

func (b *Bot) UploadPhoto(fileName string, data []byte) (*PhotoTokens, error)

UploadPhoto uploads an image file via multipart/form-data. Returns PhotoTokens containing the uploaded photo tokens.

type BotCommand

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

BotCommand represents a bot command with description.

type BotPatch added in v0.4.0

type BotPatch struct {
	Name        string       `json:"name,omitempty"`
	Username    string       `json:"username,omitempty"`
	Description string       `json:"description,omitempty"`
	Commands    []BotCommand `json:"commands,omitempty"`
}

BotPatch contains fields to update on the bot via PATCH /me.

type CallbackQuery

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

CallbackQuery represents a callback button press.

type CallbackResponse

type CallbackResponse struct {
	Text string
}

CallbackResponse represents a response to a callback query. Text is the notification toast shown to the user.

type Chat

type Chat struct {
	ID                int64      `json:"chat_id"`
	Type              string     `json:"type"`
	Status            ChatStatus `json:"status,omitempty"`
	Title             string     `json:"title,omitempty"`
	Description       string     `json:"description,omitempty"`
	Icon              *Image     `json:"icon,omitempty"`
	LastEventTime     int64      `json:"last_event_time,omitempty"`
	ParticipantsCount int        `json:"participants_count,omitempty"`
	OwnerID           int64      `json:"owner_id,omitempty"`
	IsPublic          bool       `json:"is_public,omitempty"`
	Link              string     `json:"link,omitempty"`
	MessagesCount     int64      `json:"messages_count,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 ChatAdminPermission added in v0.4.0

type ChatAdminPermission string

ChatAdminPermission is a named permission that can be granted to a chat admin.

const (
	PermReadAllMessages  ChatAdminPermission = "read_all_messages"
	PermAddRemoveMembers ChatAdminPermission = "add_remove_members"
	PermAddAdmins        ChatAdminPermission = "add_admins"
	PermChangeChatInfo   ChatAdminPermission = "change_chat_info"
	PermPinMessage       ChatAdminPermission = "pin_message"
	PermWrite            ChatAdminPermission = "write"
)

type ChatMember

type ChatMember struct {
	User           *User                 `json:"-"`
	IsOwner        bool                  `json:"is_owner"`
	IsAdmin        bool                  `json:"is_admin"`
	JoinTime       int64                 `json:"join_time"`
	LastAccessTime int64                 `json:"last_access_time"`
	Permissions    []ChatAdminPermission `json:"permissions,omitempty"`
}

ChatMember represents a chat participant. The MAX API returns user fields flat alongside member-specific fields; UnmarshalJSON populates the nested User from those flat fields.

func (*ChatMember) UnmarshalJSON added in v0.4.0

func (m *ChatMember) UnmarshalJSON(data []byte) error

UnmarshalJSON reads flat user fields from the API response into the nested User struct.

type ChatStatus added in v0.4.0

type ChatStatus string

ChatStatus represents the bot's membership state in a chat.

const (
	ChatActive    ChatStatus = "active"
	ChatRemoved   ChatStatus = "removed"
	ChatLeft      ChatStatus = "left"
	ChatClosed    ChatStatus = "closed"
	ChatSuspended ChatStatus = "suspended"
)

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 {
	UploadedInfo
}

Document represents an uploaded file ready to send. Obtain via Bot.UploadMedia("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 Image added in v0.4.0

type Image struct {
	URL string `json:"url"`
}

Image holds a URL to an image resource.

type InlineButton

type InlineButton struct {
	Text   string `json:"text"`
	Intent Intent `json:"intent,omitempty"`

	// Callback button
	Payload string `json:"payload,omitempty"`

	// Link button
	URL string `json:"url,omitempty"`

	// OpenApp button (type: "open_app")
	WebApp    string `json:"web_app,omitempty"`
	ContactID int64  `json:"contact_id,omitempty"`

	// Geolocation button (type: "request_geo_location")
	Quick bool `json:"quick,omitempty"`

	// Clipboard button (type: "clipboard")
	ClipboardPayload string `json:"clipboard_payload,omitempty"`

	// Chat button (type: "chat")
	ChatTitle        string `json:"chat_title,omitempty"`
	ChatDescription  string `json:"chat_description,omitempty"`
	ChatStartPayload string `json:"start_payload,omitempty"`
	ChatUUID         string `json:"uuid,omitempty"`

	// Internal routing hint; not serialised.
	Data string `json:"-"`

	// Internal type selectors; not serialised.
	Contact  bool `json:"-"`
	Location bool `json:"-"`
	Message  bool `json:"-"` // forces type:"message"
}

InlineButton represents an inline keyboard button. The button type is determined automatically by MarshalJSON based on which fields are set.

func (*InlineButton) MarshalJSON added in v0.4.0

func (b *InlineButton) MarshalJSON() ([]byte, error)

MarshalJSON serialises the button with an auto-computed "type" field.

type Intent added in v0.3.0

type Intent string

Intent controls the visual style of a button.

const (
	IntentDefault  Intent = "default"
	IntentPositive Intent = "positive"
	IntentNegative Intent = "negative"
)

type LinkedMessage added in v0.1.1

type LinkedMessage struct {
	Type    string       `json:"type"`
	Sender  *User        `json:"sender,omitempty"`
	ChatID  int64        `json:"chat_id,omitempty"`
	Message *MessageBody `json:"message,omitempty"`
}

LinkedMessage представляет цитируемое или пересланное сообщение. Type может быть "reply" или "forward".

func (*LinkedMessage) Text added in v0.1.2

func (l *LinkedMessage) Text() string

Text возвращает текст цитируемого сообщения. Используется как msg.ReplyTo.Text

type LongPoller

type LongPoller struct {
	Limit   int
	Timeout time.Duration
	Marker  *int64
	// Types filters which update types are requested from the server.
	// Empty slice means all types.
	Types []string
}

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"`
	// Link is the quoted/forwarded message reference at the top-level Message object per spec.
	Link *LinkedMessage `json:"link,omitempty"`

	// ReplyTo is populated automatically from Link when type == "reply".
	ReplyTo *LinkedMessage `json:"-"`
}

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) 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) Text

func (m *Message) Text() string

Text returns message text content.

func (*Message) UnmarshalJSON added in v0.1.2

func (m *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON populates ReplyTo from the top-level link field when type is "reply".

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"`
	// ReplyTo is the mid of the message being replied to (used when sending).
	// Do not confuse with Message.ReplyTo which is the full LinkedMessage object.
	ReplyTo string `json:"reply_to,omitempty"`
}

MessageBody represents message content.

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc represents middleware that wraps a handler.

type NetworkError added in v0.3.0

type NetworkError struct {
	Op  string
	Err error
}

NetworkError wraps a network-level failure.

func (*NetworkError) Error added in v0.3.0

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap added in v0.3.0

func (e *NetworkError) Unwrap() error

type Photo

type Photo struct {
	PhotoTokens
}

Photo represents an uploaded image ready to send. Obtain via Bot.UploadPhoto.

func (*Photo) Send

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

Send implements Sendable interface for Photo.

type PhotoToken added in v0.4.0

type PhotoToken struct {
	Token string `json:"token"`
}

PhotoToken holds the token for a single uploaded photo.

type PhotoTokens added in v0.4.0

type PhotoTokens struct {
	Photos map[string]PhotoToken `json:"photos"`
}

PhotoTokens is the response from a photo upload: a map keyed by photo size/index.

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) Chat added in v0.4.0

func (r *ReplyMarkup) Chat(text, title, description, startPayload string) InlineButton

Chat creates a button that initiates a new chat creation flow.

func (*ReplyMarkup) Clipboard added in v0.4.0

func (r *ReplyMarkup) Clipboard(text, payload string) InlineButton

Clipboard creates a button that copies text to the clipboard when pressed.

func (*ReplyMarkup) Contact added in v0.3.0

func (r *ReplyMarkup) Contact(text string) InlineButton

Contact creates a button that requests the user's phone number.

func (*ReplyMarkup) Data

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

Data creates a callback button with the given payload.

func (*ReplyMarkup) Geolocation added in v0.3.0

func (r *ReplyMarkup) Geolocation(text string, quick bool) InlineButton

Geolocation creates a button that requests the user's location. If quick is true, the location is sent immediately without a confirmation dialog.

func (*ReplyMarkup) MessageBtn added in v0.4.0

func (r *ReplyMarkup) MessageBtn(text string) InlineButton

MessageBtn creates a template message button.

func (*ReplyMarkup) OpenApp added in v0.3.0

func (r *ReplyMarkup) OpenApp(text, webApp, payload string, contactID int64) InlineButton

OpenApp creates a button that opens a MAX mini-app. webApp is the app URL/identifier, payload is passed to the app on launch, contactID optionally pins the launch to a specific contact.

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 {
	UserID      string       // recipient user ID (private chats)
	ChatID      string       // recipient chat/channel ID
	Text        string       `json:"text"`
	Format      string       `json:"format,omitempty"`
	Attachments []Attachment `json:"attachments,omitempty"`
	Link        *linkedRef   `json:"link,omitempty"`
}

SendMessage represents an outgoing message request. Exactly one of UserID or ChatID must be set.

type SendOptions

type SendOptions struct {
	Text        string
	Format      string
	Attachments []Attachment
	ReplyToMid  string // mid of message to reply to
}

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 SimpleQueryResult added in v0.4.0

type SimpleQueryResult struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
}

SimpleQueryResult is the response body for write operations that return only success status.

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 TimeoutError added in v0.3.0

type TimeoutError struct {
	Op     string
	Reason string
}

TimeoutError represents a timeout during an API operation.

func (*TimeoutError) Error added in v0.3.0

func (e *TimeoutError) Error() string

func (*TimeoutError) Timeout added in v0.3.0

func (e *TimeoutError) Timeout() bool

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"`

	// Fields for bot_started, bot_added, bot_removed, bot_stopped,
	// user_added, user_removed, chat_title_changed.
	ChatID  int64  `json:"chat_id,omitempty"`
	User    *User  `json:"user,omitempty"`
	Payload string `json:"payload,omitempty"` // bot_started deeplink
	Title   string `json:"title,omitempty"`   // chat_title_changed

	// Fields for message_removed.
	MessageID string `json:"message_id,omitempty"`
	UserID    int64  `json:"user_id,omitempty"`

	// Fields for user_added.
	InviterID int64 `json:"inviter_id,omitempty"`

	// Fields for user_added / user_removed.
	IsChannel bool `json:"is_channel,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 UploadedInfo added in v0.4.0

type UploadedInfo struct {
	FileID int64  `json:"file_id,omitempty"`
	Token  string `json:"token,omitempty"`
}

UploadedInfo is the response from an audio/video/file upload.

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"`
	AvatarURL      string `json:"avatar_url,omitempty"`
	FullAvatarURL  string `json:"full_avatar_url,omitempty"`
}

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 {
	UploadedInfo
}

Video represents an uploaded video ready to send. Obtain via Bot.UploadMedia("video", ...).

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