tbb

package module
v0.0.0-...-20ae276 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 37 Imported by: 0

README

tbb (TBotBase): a batteries-included Telegram bot framework for Go.
Sessions, scenes, i18n, persistence and clean keyboards, built on a fork of telebot v4.

Go Reference CI Bot API 10.1 MIT


Telegram libraries hand you updates. Everything a real bot needs on top of them gets rewritten in every project: remembering where each user is in a conversation, translations, persisting state, keeping chats free of dead buttons, and escaping MarkdownV2 so Telegram doesn't reject the message.

tbb (short for TBotBase) is that layer, distilled from several production bots over the years (most recently Boteland) and merged with a fork of telebot v4 into one package.

app, _ := tbb.New[State](cfg) // SQLite, sessions, i18n: ready

app.Callback(TopUp, func(c tbb.Ctx[State]) error {
	c.Enter(SceneTopUp, AskAmount)                  // multi-step flow
	return c.CleanEdit(c.GetL8d("topup.ask"), kb)   // localized, escaped, no stale buttons
})

app.Scene(SceneTopUp).On(AskAmount, func(c tbb.Ctx[State]) error {
	c.State().Amount = c.Text()                     // typed state, persisted automatically
	c.ResetScene()
	return c.SendL8d("topup.done")
})

Contents

Features

🧭 Scenes and questions Route free text by where the user is in a flow, with no hand-rolled state machines.
🧠 Typed sessions Session[T] carries the framework's state plus your own struct T, saved after every handler that changes it.
🗄 Database included Zero-config SQLite (pure Go, no CGO); Postgres via a DSN. The framework migrates its own tables, and you get the *bun.DB for yours.
🌍 i18n Translations as Go maps, {placeholder} templates, fallback language, a built-in language picker, reply buttons matched in every language.
🧹 Clean keyboards CleanEdit, CleanSend and CleanSendDelete keep a single "control panel" message instead of a trail of dead buttons.
🛡 Safe formatting Escaping helpers for every parse mode and context. Markup errors come back typed, with the offending spot highlighted.
🔒 Correct under concurrency Updates from one chat run one at a time; different chats run in parallel. Panics are recovered.
⚙️ Ops-ready slog logging, env/.env config with validation, graceful shutdown that waits for in-flight handlers.
📦 All of telebot The full Bot API 10.1 client, webhooks, middleware, payments, stars, rich messages. Same package, no adapter layer.

Install

go get github.com/arshamalh/tbb

Requires Go 1.25+. No C toolchain is needed: SQLite is modernc.org/sqlite.

Quick start

package main

import "github.com/arshamalh/tbb"

type State struct{} // your per-chat data; empty for now

func main() {
	var cfg tbb.Config
	if err := tbb.LoadConfig(&cfg); err != nil { // reads TELEGRAM__TOKEN, .env, ...
		panic(err)
	}

	app, err := tbb.New[State](cfg) // opens ./bot.db and migrates it
	if err != nil {
		panic(err)
	}

	app.I18n().Register("en", "English 🇬🇧", tbb.Translations{
		"hello": "Hi {name}! 👋",
	})

	app.Command("/start", func(c tbb.Ctx[State]) error {
		return c.Send(c.GetL8d("hello", "name", c.Sender().FirstName))
	})

	if err := app.Start(); err != nil { // polls until SIGINT/SIGTERM
		panic(err)
	}
}
TELEGRAM__TOKEN=123456:ABC go run .

A complete bot with a language picker, menus, a two-step scene and a localized Cancel button is in examples/basic:

TELEGRAM__TOKEN=123456:ABC go run ./examples/basic

Tutorial: a two-step flow in 5 minutes

We'll build a feedback flow: the user taps Feedback, sends a rating, then a comment, and can cancel at any point.

1. Declare your state, scenes and buttons. They're plain constants, so the compiler catches typos.

type State struct {
	Rating string `json:"rating,omitempty"` // saved with the session
}

const (
	SceneFeedback tbb.Scene = iota + 1
)

const (
	AskRating tbb.Question = iota + 1
	AskComment
)

const BtnFeedback tbb.BtnKey = "feedback"

2. Write translations. One map per language; keys are yours.

var en = tbb.Translations{
	tbb.LangNameKey: "English 🇬🇧",
	"menu":        "What would you like to do?",
	"btn.feedback": "📝 Feedback",
	"btn.cancel":  "Cancel ❌",
	"ask.rating":  "Rate us from 1 to 5.",
	"ask.comment": "Thanks! Any comment? (you gave {rating})",
	"thanks":      "✅ Saved: {rating}/5, \"{comment}\".",
}

3. Wire the handlers.

type Ctx = tbb.Ctx[State]

func register(app *tbb.App[State]) {
	app.I18n().Register("en", "", en)

	app.Command("/start", menu)
	app.Callback(BtnFeedback, func(c Ctx) error {
		_ = c.Respond()
		c.Enter(SceneFeedback, AskRating)
		return c.CleanEdit(c.GetL8d("ask.rating"))
	})

	app.Scene(SceneFeedback).
		On(AskRating, func(c Ctx) error {
			c.State().Rating = c.Text()
			c.IncQuestion() // → AskComment
			return c.Send(c.GetL8d("ask.comment", "rating", c.Text()))
		}).
		On(AskComment, func(c Ctx) error {
			text := c.GetL8d("thanks", "rating", c.State().Rating, "comment", c.Text())
			c.ResetScene()
			*c.State() = State{}
			if err := c.Send(text); err != nil {
				return err
			}
			return menu(c)
		})

	// A reply-keyboard button, matched by its label in every language and
	// from inside any scene.
	app.Reply("btn.cancel", func(c Ctx) error {
		c.ResetScene()
		return menu(c)
	})
}

func menu(c Ctx) error {
	kb := &tbb.ReplyMarkup{}
	kb.Inline(BtnFeedback.AsRow(c.GetL8dBtn("btn.feedback")))
	return c.CleanEdit(c.GetL8d("menu"), kb)
}

What you didn't write: session storage, loading, saving, per-chat locking, callback-data parsing, the scene router, language fallback, MarkdownV2 escaping of ", !, . and the user's comment, or the cleanup of old keyboards.

How it works

flowchart LR
    TG[Telegram] -->|update| P[Poller<br/>long polling / webhook]
    P --> R{telebot router}
    R -->|/command| W[wrap]
    R -->|\f unique| W
    R -->|text| TR[text router]
    TR --> W
    R -->|document, payment, ...| W
    W --> L[per-chat lock]
    L --> S[(session cache)]
    S -. miss .-> DB[(SQLite / Postgres)]
    L --> A[link account]
    A --> MW[your middleware]
    MW --> H[your handler]
    H --> D{session changed?}
    D -- yes --> DB

For every update, the framework does the following around your handler:

  1. Routes it. Commands, buttons (\f<unique>), reply buttons, scenes and raw events. Callback data is split exactly once, before routing.
  2. Locks the chat. Updates from one chat are processed in order; different chats run in parallel.
  3. Loads the session from memory, or from the database on first contact or after a restart.
  4. Links the account. In private chats, the Telegram user gets an accounts row; the language stored there is restored into a cold session.
  5. Runs your middleware and handler, recovering from panics.
  6. Persists the session if (and only if) the handler changed it, including your State.

Guide

App and routing

app, err := tbb.New[State](cfg, opts...)

T is your session state (use struct{} if you have none). Register handlers with:

Method Fires on
app.Command("/start", h) a command (/start, /start@yourbot, /start payload)
app.Callback(btnKey, h) an inline button built from that BtnKey
app.Reply("btn.cancel", h) a reply-keyboard button whose label is that translation key, in any language
app.Text("exact text", h) a text message equal to that string
app.Scene(s).On(q, h) text while the chat is in scene s at question q
app.Scene(s).Default(h) text in scene s at a question without its own handler
app.DefaultText(h) any other text
app.DefaultCallback(h) buttons without a registered Callback
app.Handle(tbb.OnDocument, h) any other telebot event: OnPhoto, OnCheckout, OnPayment, OnLocation, …
app.OnLanguageSelected(h) the built-in language picker (see Localization)
app.Use(mw...) middleware around all of the above

Text routing order: Text → Reply → current scene's question → scene's Default → DefaultText. Because Text and Reply come first, a "Cancel" or "Main menu" button works from inside any flow.

Options:

Option Purpose
WithLogger[T](*slog.Logger) logger (default slog.Default())
WithI18n[T](*I18n) bring your own translation registry
WithDB[T](*bun.DB) share an existing database pool (tbb migrates its tables in it, never closes it)
WithStore[T](Store) replace persistence entirely, e.g. NewMemoryStore() in tests
WithSettings[T](func(*Settings)) tweak telebot settings: poller, parse mode, HTTP client, Synchronous, Offline…
WithShutdownTimeout[T](d) how long Run waits for in-flight handlers (default 10s)

Escape hatches: app.Bot() (the telebot *Bot), app.DB(), app.Store(), app.Sessions(), app.I18n(), app.Logger().

The context: Ctx[T]

Ctx[T] is a telebot Context (Send, Edit, Respond, Message, Callback, Sender, Args, …) plus:

Group Methods
Session Session(), State() *T, ID() (chat), UserID() (account)
Scenes Enter(s, q), SetScene(s), GetScene(), SetNextQuestion(q), IncQuestion(), GetCurrentQuestion(), ResetScene()
Language GetLanguage(), SetLanguage(code) error
i18n GetL8d(key, kv...), GetL8dRaw(key, kv...), GetL8dBtn(key, kv...), SendL8d(key, opts...), RespondL8d(key, kv...)
Keyboards CleanSend, CleanEdit, CleanSendDelete
Misc Account(), I18n(), Logger() (pre-tagged with chat_id)

Buttons and callback data

Give every inline button a typed key and use it both to build and to route, so the two can't drift apart:

const TopUpAmount tbb.BtnKey = "tuAmt"

kb := &tbb.ReplyMarkup{}
kb.Inline(
	tbb.Row{
		TopUpAmount.Build("$5", "ton", "500"),   // callback data: "\ftuAmt|ton|500"
		TopUpAmount.Build("$10", "ton", "1000"),
	},
)

app.Callback(TopUpAmount, func(c tbb.Ctx[State]) error {
	args := c.Args()            // ["ton", "500"]
	_ = c.Callback().Unique     // "tuAmt"
	_ = c.Callback().Data       // "ton|500"
	_ = c.Callback().RawData    // "\ftuAmt|ton|500"
	return c.Respond()
})
  • Keys must match [A-Za-z0-9_-]+, and unique plus data must fit Telegram's 64-byte callback_data limit.
  • Data is split once, before routing, for every handler including DefaultCallback. Never parse \f… yourself; use ParseCallbackData if you need it outside a handler.
  • Renaming a key? Messages already in users' chats still carry the old one. Keep the old key registered (app.Callback(old, h)) for a while, or switch on c.Callback().Unique in DefaultCallback.

Sessions and scenes

type Session[T any] struct {
	ChatID        int64    // Telegram chat
	UID           int64    // accounts.id (private chats)
	Scene         Scene    // 0 = main menu
	Question      Question // step inside the scene
	Language      string
	KeyboardMsgID int      // used by the Clean* helpers
	State         T        // yours
}
  • Your state is any JSON-serializable struct. Mutate it through c.State(); it's saved when the handler returns, and only if something changed (the framework compares JSON snapshots).
  • Lazy loading. Nothing is preloaded at startup. A chat's session is read on its first update and then served from memory.
  • SetScene(s) starts at question 0. Use Enter(s, q) to set both.
  • Group chats get one session per group; account linking only happens in private chats, where a chat is a user.

Changing a session outside a handler (a scheduler, a webhook, an admin command acting on someone else):

unlock := app.Sessions().Lock(chatID) // same lock the handlers use
s, err := app.Sessions().Get(ctx, chatID)
if err == nil {
	s.State.PendingInvoice = 0
	err = app.Sessions().Save(ctx, s)
}
unlock()

Localization

app.I18n().Register("en", "English 🇬🇧", en) // order = order in the picker
app.I18n().Register("fa", "پارسی 🇮🇷", fa)
Call Returns
c.GetL8d("welcome", "name", n) translated, {name} filled, escaped for the bot's parse mode
c.GetL8dRaw(key, kv...) / c.GetL8dBtn(...) translated and filled, no escaping (for button labels, toasts, plain text)
c.SendL8d(key, opts...) sends GetL8d(key)
c.RespondL8d(key) answers a callback with a toast
app.I18n().Get(lang, key) raw template, for use outside handlers
tbb.Replace(tpl, "k", v) fills placeholders in any string

Fallback: a missing key or language falls back to Config.DefaultLanguage ("en"), then renders as [missing: key], so gaps are visible rather than blank.

Language picker:

c.CleanSend(c.GetL8d("choose_language"), app.LanguageKeyboard())

app.OnLanguageSelected(showMainMenu)              // sets session + account language
app.OnLanguageSelected(showMainMenu, "setLang")   // also accept an older button key

Localized reply buttons: app.Reply("btn.cancel", h) matches the label of btn.cancel in every registered language, so a Farsi user's "انصراف ❌" and an English user's "Cancel ❌" reach the same handler.

Parse modes and escaping

Bots send with MarkdownV2 by default (change it with WithSettings(func(s *Settings){ s.ParseMode = tbb.ModeHTML })). In MarkdownV2, _ * [ ] ( ) ~ \ > # + - = | { } . !are all reserved. One unescaped.` and Telegram rejects the whole message (telebot#553).

With GetL8d you rarely think about it: templates keep their *bold*, _italic_ and `code`, everything else is escaped, and placeholder values (user input!) are escaped completely.

For hand-built text, pick the helper by where the text goes:

Context Helper Escapes
plain text, any mode tbb.Escape(mode, s) per mode
MarkdownV2 text EscapeMarkdownV2(s) every reserved char
your own MarkdownV2 template EscapeMarkdownV2Basics(s) all but `* _ ``
inside `code` / ```pre``` EscapeMarkdownV2Code(s) only ` and \
inside [text](url) EscapeMarkdownV2URL(s) only ) and \
legacy Markdown EscapeMarkdown(s) _ * \ [`
HTML EscapeHTML(s) & < > "
msg := fmt.Sprintf("Login with `%s`", tbb.EscapeMarkdownV2Code(cmd))
c.Send("Plain text, no formatting at all.", tbb.ModeDefault) // one message without parse mode

When Telegram still says no, the error tells you where:

_, err := c.Bot().Send(to, text)
if errors.Is(err, tbb.ErrCantParseEntities) {
	// telegram: can't parse entities: Can't find end of the entity starting
	// at byte offset 7 near "Hi john▶_doe!" (400)
	var pe *tbb.ParseEntitiesError
	errors.As(err, &pe) // pe.Offset, pe.Text, pe.Excerpt()
}

Clean keyboards

Menus built from inline keyboards quickly leave a trail of old messages whose buttons still look clickable. tbb remembers the last keyboard message per chat (Session.KeyboardMsgID):

Call Effect
c.CleanEdit(text, kb) edits the current keyboard message in place, so one message morphs as the user navigates. Falls back to delete + send when it can't edit (none yet, a photo, too old). "Not modified" is a no-op.
c.CleanSend(what, kb) strips the old message's keyboard, sends a new one
c.CleanSendDelete(what, kb) deletes the old message (or strips it if deletion fails), sends a new one

Rule of thumb: CleanEdit for menu navigation, CleanSend when the history matters (receipts, results), and CleanSendDelete when leaving a flow.

Database and accounts

Configuration Result
(nothing) SQLite at ./bot.db: WAL, busy timeout, foreign keys
DB__DSN=file:data/bot.db?_pragma=busy_timeout(5000) SQLite at that path
DB__DSN=postgres://user:pass@host:5432/bot?sslmode=disable Postgres
WithDB(db) your existing *bun.DB

The framework owns three tables and migrates them on startup:

Table Content
accounts one row per Telegram user: id, telegram_id, username, first_name, last_name, language
sessions one JSON document per chat
tbb_schema the framework's migration history (separate from yours)

Your own tables live in the same database. Key them by accounts.id (c.UserID()), and migrate them with whatever tool you like:

type Feedback struct {
	ID        int64 `bun:",pk,autoincrement"`
	AccountID int64 `bun:",notnull"`
	Rating    int
	Comment   string
}

_, err := app.DB().NewInsert().Model(&Feedback{AccountID: c.UserID(), Rating: 5}).Exec(ctx)

c.Account() returns the caller's row; app.Store().AccountByID(...) works anywhere, for example to look up the chat to notify from a background job.

Configuration

LoadConfig(&cfg) applies default:"…" tags, loads .env (real environment variables win), reads the environment with __ as the nesting separator, and validates validate:"…" tags. Embed tbb.Config to inherit the framework's keys next to yours:

type Config struct {
	tbb.Config                                            // framework keys
	AdminID int64  `json:"admin_id" validate:"required"`     // ADMIN_ID
	Wallet  string `json:"wallet"   default:"UQ…"`           // WALLET
}

var cfg Config
if err := tbb.LoadConfig(&cfg); err != nil { log.Fatal(err) }
app, _ := tbb.New[State](cfg.Config)
Variable Default
TELEGRAM__TOKEN — required
TELEGRAM__URL https://api.telegram.org e.g. a local telegram-bot-api server
TELEGRAM__POLLER_TIMEOUT 10s long-polling timeout
DB__DRIVER inferred sqlite or postgres
DB__DSN ./bot.db
DEFAULT_LANGUAGE en fallback language

Middleware

Framework middleware sees the full Ctx[T], session included:

func adminsOnly(ids ...int64) tbb.Middleware[State] {
	return func(next tbb.Handler[State]) tbb.Handler[State] {
		return func(c tbb.Ctx[State]) error {
			if !slices.Contains(ids, c.Sender().ID) {
				return c.RespondL8d("error.forbidden")
			}
			return next(c)
		}
	}
}

app.Use(adminsOnly(cfg.AdminID))

telebot's middleware package (github.com/arshamalh/tbb/middleware: Logger, AutoRespond, Whitelist, Recover, …) still works at the bot level via app.Bot().Use(...).

Long polling, webhooks and shutdown

Long polling is the default. For a webhook, swap the poller:

app, err := tbb.New[State](cfg, tbb.WithSettings[State](func(s *tbb.Settings) {
	s.Poller = &tbb.Webhook{
		Listen:   ":8443",
		Endpoint: &tbb.WebhookEndpoint{PublicURL: "https://bot.example.com"},
	}
}))

app.Start() runs until SIGINT/SIGTERM; app.Run(ctx) until ctx is cancelled. Either way, shutdown stops polling, waits for in-flight handlers (up to WithShutdownTimeout), and closes the database if tbb opened it. Sessions are written through as they change, so nothing needs flushing.

Files

app.Handle(tbb.OnDocument, func(c tbb.Ctx[State]) error {
	doc := c.Message().Document
	// Stream straight to S3/GCS/another service, no temp file:
	return c.Bot().DownloadToWriter(&doc.File, uploader)
})

Download(file, path) and File(file) (io.ReadCloser, error) are there too.

Testing your bot

Use an in-memory store and point the bot at a fake Bot API server; then feed updates synchronously:

func TestStart(t *testing.T) {
	api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Record r.URL.Path / body here to assert on what was sent.
		fmt.Fprint(w, `{"ok":true,"result":{"message_id":1,"chat":{"id":7}}}`)
	}))
	defer api.Close()

	app, err := tbb.New[State](
		tbb.Config{Telegram: tbb.TelegramConfig{Token: "test", URL: api.URL}},
		tbb.WithStore[State](tbb.NewMemoryStore()),
		tbb.WithSettings[State](func(s *tbb.Settings) {
			s.Offline = true     // skip getMe
			s.Synchronous = true // ProcessUpdate returns after the handler
		}),
	)
	require.NoError(t, err)
	register(app)

	app.Bot().ProcessUpdate(tbb.Update{Message: &tbb.Message{
		Text:   "/start",
		Sender: &tbb.User{ID: 7},
		Chat:   &tbb.Chat{ID: 7, Type: tbb.ChatPrivate},
	}})

	s, _ := app.Sessions().Get(context.Background(), 7)
	assert.Equal(t, tbb.Scene(0), s.GetScene())
}

tbb's own app_test.go has a fuller fake server that records every call, which is useful as a template.

Deployment

SQLite is pure Go, so a static binary works anywhere:

FROM golang:1.25 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /bot ./cmd/bot

FROM gcr.io/distroless/static
COPY --from=build /bot /bot
WORKDIR /data                # bot.db lives here; mount a volume
ENTRYPOINT ["/bot"]
  • With SQLite, run one replica and put /data on a persistent volume.
  • For several replicas, use Postgres and a webhook behind a load balancer. The per-chat lock is in-process, so make sure one chat's updates reach one instance at a time (or accept rare races between instances).

What the fork changes in telebot

tbb vendors telebot v4 at upstream ee8708c (Bot API 10.1) as the root package. The upstream guide, with updated import paths, is in docs/telebot.md. Changes compared with upstream:

Change Why
Callback data is split for every callback before dispatch; OnCallback gets Unique/Data too; new Callback.RawData and ParseCallbackData upstream only split when a unique handler existed, so apps parsed \f… a second time; empty and multi-line payloads were rejected
ParseEntitiesError / ErrCantParseEntities with offset and excerpt markup errors were untyped strings without context (#553)
Escaping helpers for all parse modes none existed (#553)
&SendOptions{} without ParseMode keeps the bot's mode it silently dropped it, so escapes printed as backslashes
Bot.DownloadToWriter stream files without touching disk (#704)
layout package removed replaced by tbb's i18n and BtnKey; drops viper/yaml deps
Go 1.25, CI with -race generics, modern toolchain

Project layout

tbb/
├── app.go              App[T], options, routing, the per-update wrapper, Run/Start
├── ctx.go              Ctx[T]: session access, i18n, Clean* helpers, rendering
├── session.go          Session[T], Scene, Question
├── session_store.go    write-through session cache + per-chat locks
├── store.go            Store interface, Account
├── sql_store.go        SQLite/Postgres store (bun), OpenDB
├── migrate.go          framework migrations (tbb_schema)
├── memory_store.go     in-memory Store for tests
├── i18n.go             translation registry, Replace
├── language.go         built-in language picker
├── button_key.go       BtnKey
├── escape.go           escaping helpers for every parse mode
├── parse_error.go      ParseEntitiesError
├── env_config.go       LoadConfig
├── *.go                the telebot fork (bot.go, context.go, update.go, ...)
├── middleware/         telebot middleware
├── react/              reaction helpers
├── examples/basic/     a complete example bot
├── logo.png            project logo
└── docs/telebot.md     upstream telebot guide

FAQ

Why one package instead of a wrapper around telebot? A wrapper means two Context types, two routers and constant conversion between them. Owning the code let us fix things at the source (callback parsing, parse errors, SendOptions) instead of working around them.

Can I still use plain telebot handlers? Yes: app.Bot().Handle(endpoint, func(c tbb.Context) error {...}). They just don't get sessions. Prefer app.Handle, which does.

Do I have to use scenes? No. Ignore them and use Command, Callback and DefaultText. The session is still there for your State.

Is the session saved if my handler returns an error? Yes. Changes made before the error are kept. A panic, however, skips the save.

Why does GetL8d output contain backslashes in my button labels? GetL8d escapes for the parse mode, and button labels aren't parsed. Use GetL8dBtn for labels.

Can I keep using my own migration tool? Yes. The framework only touches accounts, sessions and tbb_schema.

How do I upgrade the SQLite driver or bun? go get -u modernc.org/sqlite. For bun, all github.com/uptrace/bun/... modules (core, sqlitedialect, pgdialect, pgdriver) must share one version, or sqlitedialect panics at startup.

Roadmap

  • Align bun modules on the latest release (currently pinned to v1.2.15)
  • Session eviction (TTL / LRU) for very large bots
  • Optional distributed lock for multi-instance deployments
  • go generate for typed translation keys
  • Rate-limit-aware sender (honouring FloodError.RetryAfter)
  • Admin helpers: broadcast, roles

Contributing

go vet ./...
go test -race ./...

# Run the store tests against Postgres too:
TBB_TEST_POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/tbb_test?sslmode=disable \
  go test -race -run 'SQLStore|SessionStoreOverSQL' .

Commits are small and self-contained, with a message explaining why. The telebot files keep upstream's formatting to ease future syncs.

Credits and license

  • The Telegram client is telebot by Ilya Kowalewski, Demian and all its contributors.
  • Framework patterns come from years of production bots by Arsham Arya.

MIT, see LICENSE.

Documentation

Overview

Package tbb (TBotBase) is a Telegram bot framework: a fork of telebot v4 extended with typed per-chat sessions, scene/question routing, i18n, a SQLite/Postgres store, clean inline keyboards and parse-mode-aware escaping. Every telebot type (Bot, Context, ReplyMarkup, ...) lives in this package too.

Start with New, register handlers on the returned App and call Start. See the README for a guide and examples/basic for a complete bot.

Package telebot is a framework for Telegram bots.

Example:

package main

import (
	"time"
	tele "github.com/arshamalh/tbb"
)

func main() {
	b, err := tele.NewBot(tele.Settings{
		Token:  "...",
		Poller: &tele.LongPoller{Timeout: 10 * time.Second},
	})
	if err != nil {
		return
	}

	b.Handle("/start", func(c tele.Context) error {
		return c.Send("Hello world!")
	})

	b.Start()
}

Index

Constants

View Source
const (
	ReactionTypeEmoji       = "emoji"
	ReactionTypeCustomEmoji = "custom_emoji"
)
View Source
const (
	RichBlockParagraph     = "paragraph"
	RichBlockHeading       = "heading"
	RichBlockPre           = "pre"
	RichBlockFooter        = "footer"
	RichBlockDivider       = "divider"
	RichBlockMath          = "mathematical_expression"
	RichBlockAnchor        = "anchor"
	RichBlockList          = "list"
	RichBlockBlockquote    = "blockquote"
	RichBlockPullquote     = "pullquote"
	RichBlockCollage       = "collage"
	RichBlockSlideshow     = "slideshow"
	RichBlockTable         = "table"
	RichBlockDetails       = "details"
	RichBlockMap           = "map"
	RichBlockAnimationType = "animation"
	RichBlockAudioType     = "audio"
	RichBlockPhotoType     = "photo"
	RichBlockVideoType     = "video"
	RichBlockVoiceNote     = "voice_note"
	RichBlockThinking      = "thinking"
)

RichBlock type discriminators, as carried in the "type" field of a received rich block (Bot API 10.1).

View Source
const (
	RichBold                   = "bold"
	RichItalic                 = "italic"
	RichUnderline              = "underline"
	RichStrikethrough          = "strikethrough"
	RichSpoiler                = "spoiler"
	RichDateTime               = "date_time"
	RichTextMentionType        = "text_mention"
	RichSubscript              = "subscript"
	RichSuperscript            = "superscript"
	RichMarked                 = "marked"
	RichCode                   = "code"
	RichCustomEmoji            = "custom_emoji"
	RichMathematicalExpression = "mathematical_expression"
	RichURL                    = "url"
	RichEmailAddress           = "email_address"
	RichPhoneNumber            = "phone_number"
	RichBankCardNumber         = "bank_card_number"
	RichMention                = "mention"
	RichHashtag                = "hashtag"
	RichCashtag                = "cashtag"
	RichBotCommand             = "bot_command"
	RichAnchor                 = "anchor"
	RichAnchorLink             = "anchor_link"
	RichReference              = "reference"
	RichReferenceLink          = "reference_link"
)

RichText type discriminators, as carried in the "type" field of a tagged RichText entity (Bot API 10.1).

View Source
const (
	DriverSQLite   = "sqlite"
	DriverPostgres = "postgres"
)

Supported database drivers.

View Source
const (
	// Basic message handlers.
	OnText                 = "\atext"
	OnForward              = "\aforward"
	OnReply                = "\areply"
	OnEdited               = "\aedited"
	OnPhoto                = "\aphoto"
	OnAudio                = "\aaudio"
	OnAnimation            = "\aanimation"
	OnDocument             = "\adocument"
	OnSticker              = "\asticker"
	OnVideo                = "\avideo"
	OnVoice                = "\avoice"
	OnVideoNote            = "\avideo_note"
	OnContact              = "\acontact"
	OnLocation             = "\alocation"
	OnVenue                = "\avenue"
	OnDice                 = "\adice"
	OnInvoice              = "\ainvoice"
	OnPayment              = "\apayment"
	OnRefund               = "\arefund"
	OnGame                 = "\agame"
	OnPoll                 = "\apoll"
	OnPollAnswer           = "\apoll_answer"
	OnPinned               = "\apinned"
	OnChannelPost          = "\achannel_post"
	OnEditedChannelPost    = "\aedited_channel_post"
	OnTopicCreated         = "\atopic_created"
	OnTopicReopened        = "\atopic_reopened"
	OnTopicClosed          = "\atopic_closed"
	OnTopicEdited          = "\atopic_edited"
	OnGeneralTopicHidden   = "\ageneral_topic_hidden"
	OnGeneralTopicUnhidden = "\ageneral_topic_unhidden"
	OnWriteAccessAllowed   = "\awrite_access_allowed"
	OnChatOwnerLeft        = "\achat_owner_left"
	OnChatOwnerChanged     = "\achat_owner_changed"

	OnAddedToGroup      = "\aadded_to_group"
	OnUserJoined        = "\auser_joined"
	OnUserLeft          = "\auser_left"
	OnUserShared        = "\auser_shared"
	OnChatShared        = "\achat_shared"
	OnNewGroupTitle     = "\anew_chat_title"
	OnNewGroupPhoto     = "\anew_chat_photo"
	OnGroupPhotoDeleted = "\achat_photo_deleted"
	OnGroupCreated      = "\agroup_created"
	OnSuperGroupCreated = "\asupergroup_created"
	OnChannelCreated    = "\achannel_created"

	// OnMigration happens when group switches to
	// a supergroup. You might want to update
	// your internal references to this chat
	// upon switching as its ID will change.
	OnMigration = "\amigration"

	OnMedia           = "\amedia"
	OnCallback        = "\acallback"
	OnQuery           = "\aquery"
	OnInlineResult    = "\ainline_result"
	OnShipping        = "\ashipping_query"
	OnCheckout        = "\apre_checkout_query"
	OnMyChatMember    = "\amy_chat_member"
	OnChatMember      = "\achat_member"
	OnChatJoinRequest = "\achat_join_request"
	OnProximityAlert  = "\aproximity_alert_triggered"
	OnAutoDeleteTimer = "\amessage_auto_delete_timer_changed"
	OnWebApp          = "\aweb_app"

	OnVideoChatStarted      = "\avideo_chat_started"
	OnVideoChatEnded        = "\avideo_chat_ended"
	OnVideoChatParticipants = "\avideo_chat_participants_invited"
	OnVideoChatScheduled    = "\avideo_chat_scheduled"

	OnBoost        = "\aboost_updated"
	OnBoostRemoved = "\aboost_removed"

	OnBusinessConnection      = "\abusiness_connection"
	OnBusinessMessage         = "\abusiness_message"
	OnEditedBusinessMessage   = "\aedited_business_message"
	OnDeletedBusinessMessages = "\adeleted_business_messages"
	OnGuestMessage            = "\aguest_message"
	OnPurchasedPaidMedia      = "\apurchased_paid_media"
)

These are one of the possible events Handle() can deal with.

For convenience, all Telebot-provided endpoints start with an "alert" character \a.

View Source
const DefaultApiURL = "https://api.telegram.org"
View Source
const DefaultSQLiteDSN = "file:bot.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)"

DefaultSQLiteDSN is used when no database is configured: a bot.db file in the working directory, in WAL mode with a busy timeout so concurrent handlers wait for the write lock instead of failing.

View Source
const LangNameKey = "lang"

LangNameKey is the conventional translation key that holds a language's own display name (e.g. "English 🇬🇧"). It is used by the built-in language picker when no explicit name is passed to Register.

View Source
const LiveForever = math.MaxInt32

LiveForever is an alias for math.MaxInt32. Use it for LivePeriod of the Location.

View Source
const Stars = "XTR"

Stars is a provider token for Telegram Stars.

Variables

View Source
var (
	ErrTooLarge     = NewError(400, "Request Entity Too Large")
	ErrUnauthorized = NewError(401, "Unauthorized")
	ErrNotFound     = NewError(404, "Not Found")
	ErrInternal     = NewError(500, "Internal Server Error")
)

General errors

View Source
var (
	ErrBadButtonData          = NewError(400, "Bad Request: BUTTON_DATA_INVALID")
	ErrBadUserID              = NewError(400, "Bad Request: USER_ID_INVALID")
	ErrBadPollOptions         = NewError(400, "Bad Request: expected an Array of String as options")
	ErrBadURLContent          = NewError(400, "Bad Request: failed to get HTTP URL content")
	ErrCantEditMessage        = NewError(400, "Bad Request: message can't be edited")
	ErrCantRemoveOwner        = NewError(400, "Bad Request: can't remove chat owner")
	ErrCantUploadFile         = NewError(400, "Bad Request: can't upload file by URL")
	ErrCantUseMediaInAlbum    = NewError(400, "Bad Request: can't use the media of the specified type in the album")
	ErrChatAboutNotModified   = NewError(400, "Bad Request: chat description is not modified")
	ErrChatNotFound           = NewError(400, "Bad Request: chat not found")
	ErrEmptyChatID            = NewError(400, "Bad Request: chat_id is empty")
	ErrEmptyMessage           = NewError(400, "Bad Request: message must be non-empty")
	ErrEmptyText              = NewError(400, "Bad Request: text is empty")
	ErrFailedImageProcess     = NewError(400, "Bad Request: IMAGE_PROCESS_FAILED", "Image process failed")
	ErrGroupMigrated          = NewError(400, "Bad Request: group chat was upgraded to a supergroup chat")
	ErrMessageNotModified     = NewError(400, "Bad Request: message is not modified")
	ErrNoRightsToDelete       = NewError(400, "Bad Request: message can't be deleted")
	ErrNoRightsToRestrict     = NewError(400, "Bad Request: not enough rights to restrict/unrestrict chat member")
	ErrNoRightsToSend         = NewError(400, "Bad Request: have no rights to send a message")
	ErrNoRightsToSendGifs     = NewError(400, "Bad Request: CHAT_SEND_GIFS_FORBIDDEN", "sending GIFS is not allowed in this chat")
	ErrNoRightsToSendPhoto    = NewError(400, "Bad Request: not enough rights to send photos to the chat")
	ErrNoRightsToSendStickers = NewError(400, "Bad Request: not enough rights to send stickers to the chat")
	ErrNotFoundToDelete       = NewError(400, "Bad Request: message to delete not found")
	ErrNotFoundToForward      = NewError(400, "Bad Request: message to forward not found")
	ErrNotFoundToReply        = NewError(400, "Bad Request: reply message not found")
	ErrQueryTooOld            = NewError(400, "Bad Request: query is too old and response timeout expired or query ID is invalid")
	ErrSameMessageContent     = NewError(400, "Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message")
	ErrStickerEmojisInvalid   = NewError(400, "Bad Request: invalid sticker emojis")
	ErrStickerSetInvalid      = NewError(400, "Bad Request: STICKERSET_INVALID", "Stickerset is invalid")
	ErrStickerSetInvalidName  = NewError(400, "Bad Request: invalid sticker set name is specified")
	ErrStickerSetNameOccupied = NewError(400, "Bad Request: sticker set name is already occupied")
	ErrTooLongMarkup          = NewError(400, "Bad Request: reply markup is too long")
	ErrTooLongMessage         = NewError(400, "Bad Request: message is too long")
	ErrUserIsAdmin            = NewError(400, "Bad Request: user is an administrator of the chat")
	ErrWrongFileID            = NewError(400, "Bad Request: wrong file identifier/HTTP URL specified")
	ErrWrongFileIDCharacter   = NewError(400, "Bad Request: wrong remote file id specified: Wrong character in the string")
	ErrWrongFileIDLength      = NewError(400, "Bad Request: wrong remote file id specified: Wrong string length")
	ErrWrongFileIDPadding     = NewError(400, "Bad Request: wrong remote file id specified: Wrong padding in the string")
	ErrWrongFileIDSymbol      = NewError(400, "Bad Request: wrong remote file id specified: can't unserialize it. Wrong last symbol")
	ErrWrongTypeOfContent     = NewError(400, "Bad Request: wrong type of the web page content")
	ErrWrongURL               = NewError(400, "Bad Request: wrong HTTP URL specified")
	ErrForwardMessage         = NewError(400, "Bad Request: administrators of the chat restricted message forwarding")
	ErrUserAlreadyParticipant = NewError(400, "Bad Request: USER_ALREADY_PARTICIPANT", "User is already a participant")
	ErrHideRequesterMissing   = NewError(400, "Bad Request: HIDE_REQUESTER_MISSING")
	ErrChannelsTooMuch        = NewError(400, "Bad Request: CHANNELS_TOO_MUCH")
	ErrChannelsTooMuchUser    = NewError(400, "Bad Request: USER_CHANNELS_TOO_MUCH")
)

Bad request errors

View Source
var (
	ErrBlockedByUser        = NewError(403, "Forbidden: bot was blocked by the user")
	ErrKickedFromGroup      = NewError(403, "Forbidden: bot was kicked from the group chat")
	ErrKickedFromSuperGroup = NewError(403, "Forbidden: bot was kicked from the supergroup chat")
	ErrKickedFromChannel    = NewError(403, "Forbidden: bot was kicked from the channel chat")
	ErrNotStartedByUser     = NewError(403, "Forbidden: bot can't initiate conversation with a user")
	ErrUserIsDeactivated    = NewError(403, "Forbidden: user is deactivated")
	ErrNotChannelMember     = NewError(403, "Forbidden: bot is not a member of the channel chat")
)

Forbidden errors

View Source
var (
	Cube = &Dice{Type: "🎲"}
	Dart = &Dice{Type: "🎯"}
	Ball = &Dice{Type: "🏀"}
	Goal = &Dice{Type: "⚽"}
	Slot = &Dice{Type: "🎰"}
	Bowl = &Dice{Type: "🎳"}
)
View Source
var (
	ErrBadRecipient    = errors.New("telebot: recipient is nil")
	ErrUnsupportedWhat = errors.New("telebot: unsupported what argument")
	ErrCouldNotUpdate  = errors.New("telebot: could not fetch new updates")
	ErrTrueResult      = errors.New("telebot: result is True")
	ErrBadContext      = errors.New("telebot: context does not contain message")
)
View Source
var AllowedUpdates = []string{
	"message",
	"edited_message",
	"channel_post",
	"edited_channel_post",
	"message_reaction",
	"message_reaction_count",
	"inline_query",
	"chosen_inline_result",
	"callback_query",
	"shipping_query",
	"pre_checkout_query",
	"poll",
	"poll_answer",
	"my_chat_member",
	"chat_member",
	"chat_join_request",
	"chat_boost",
	"removed_chat_boost",
	"guest_message",
}
View Source
var ErrCantParseEntities = NewError(400, "Bad Request: can't parse entities")

ErrCantParseEntities matches, with errors.Is, every error Telegram returns when a message's markup is invalid for its parse mode ("Bad Request: can't parse entities: ..."). Use errors.As with *ParseEntitiesError for details.

View Source
var ErrRecordNotFound = errors.New("tbb: not found")

ErrRecordNotFound is returned by a Store when a record does not exist. (ErrNotFound is taken by the Telegram API error of the same name.)

View Source
var SupportedCurrencies = make(map[string]Currency)

Functions

func Err

func Err(s string) error

Err returns Error instance by given description.

func ErrIs

func ErrIs(s string, err error) bool

ErrIs checks if the error with given description matches an error err.

func Escape

func Escape(mode ParseMode, s string) string

Escape escapes plain text so it renders literally under mode. For ModeDefault (no parse mode) the text is returned unchanged.

func EscapeHTML

func EscapeHTML(s string) string

EscapeHTML escapes text for ModeHTML: '&', '<', '>' and '"'.

func EscapeMarkdown

func EscapeMarkdown(s string) string

EscapeMarkdown escapes text for the legacy ModeMarkdown, where '_', '*', '`' and '[' start entities. Telegram recommends MarkdownV2 or HTML instead.

func EscapeMarkdownV2

func EscapeMarkdownV2(s string) string

EscapeMarkdownV2 escapes every MarkdownV2 reserved character, making any string safe to embed as plain text. Use it for user-supplied values before inserting them into a template.

func EscapeMarkdownV2Basics

func EscapeMarkdownV2Basics(s string) string

EscapeMarkdownV2Basics prepares an authored template for ModeMarkdownV2: punctuation is escaped but *bold*, _italic_ and `code` markers survive. This is what localized sends (SendL8d, GetL8d) apply.

Do not use it for user-supplied text (names, usernames, free input); a stray "_" or "*" there would break parsing. Use EscapeMarkdownV2 instead.

func EscapeMarkdownV2Code

func EscapeMarkdownV2Code(s string) string

EscapeMarkdownV2Code escapes text placed inside a MarkdownV2 code span or pre block, where only '`' and '\' are special. Other characters must NOT be escaped there, or the backslashes show up in the code.

func EscapeMarkdownV2URL

func EscapeMarkdownV2URL(s string) string

EscapeMarkdownV2URL escapes a URL placed in a MarkdownV2 inline link: [text](url). Only ')' and '\' are special inside the parentheses.

func Flag

func Flag(b bool) *bool

Flag returns a pointer to the given bool. Useful for passing the three-state flags to a Bot API. For example, see ReplyRecipient type.

func Forever

func Forever() int64

Forever is a ExpireUnixtime of "forever" banning.

func LoadConfig

func LoadConfig(cfg any, envFiles ...string) error

LoadConfig fills cfg, a pointer to a struct, in this order:

  1. `default:"..."` struct tags,
  2. environment variables, after loading envFiles (".env" when none are given; missing files are ignored and real environment variables win),

then validates it against `validate:"..."` tags.

Fields are matched by their json tag; nested structs are separated by a double underscore and names are case-insensitive:

type Config struct {
	tbb.Config             // embedded: TELEGRAM__TOKEN, DB__DSN, ...
	AdminID int64 `json:"admin_id"` // ADMIN_ID
}

var cfg Config
if err := tbb.LoadConfig(&cfg); err != nil { ... }

func OpenDB

func OpenDB(cfg DBConfig) (*bun.DB, error)

OpenDB opens the configured database and verifies the connection. The returned *bun.DB can be shared with the app for its own tables.

func ParseCallbackData

func ParseCallbackData(data string) (unique, payload string, ok bool)

ParseCallbackData splits callback data produced by a button with a Unique ("\f<unique>" or "\f<unique>|<payload>"). ok is false when data doesn't start with "\f" or the unique is not made of letters, digits, '_' and '-'. The payload is everything after the first '|', and may itself contain '|' (use Context.Args to split it), be empty, or span several lines.

func Replace

func Replace(template string, kv ...string) string

Replace fills {placeholders} in template using key/value pairs:

Replace("Hi {name}!", "name", "Arsham") // "Hi Arsham!"

Keys are given without braces. A trailing key without a value is ignored.

Types

type API

type API interface {
	Raw(method string, payload interface{}) ([]byte, error)

	Accept(query *PreCheckoutQuery, errorMessage ...string) error
	AddStickerToSet(of Recipient, name string, sticker InputSticker) error
	AdminsOf(chat *Chat) ([]ChatMember, error)
	Answer(query *Query, resp *QueryResponse) error
	AnswerGuest(msg *Message, result Result) (*SentGuestMessage, error)
	AnswerWebApp(query *Query, r Result) (*WebAppMessage, error)
	ApproveJoinRequest(chat Recipient, user *User) error
	Ban(chat *Chat, member *ChatMember, revokeMessages ...bool) error
	BanSenderChat(chat *Chat, sender Recipient) error
	BusinessConnection(id string) (*BusinessConnection, error)
	ChatByID(id int64) (*Chat, error)
	ChatByUsername(name string) (*Chat, error)
	ChatFullInfo(chat Recipient) (*ChatFullInfo, error)
	ChatMemberOf(chat, user Recipient) (*ChatMember, error)
	Close() (bool, error)
	CloseGeneralTopic(chat *Chat) error
	CloseTopic(chat *Chat, topic *Topic) error
	Commands(opts ...interface{}) ([]Command, error)
	Copy(to Recipient, msg Editable, opts ...interface{}) (*Message, error)
	CopyMany(to Recipient, msgs []Editable, opts ...*SendOptions) ([]Message, error)
	CreateInviteLink(chat Recipient, link *ChatInviteLink) (*ChatInviteLink, error)
	CreateInvoiceLink(i Invoice) (string, error)
	CreateStickerSet(of Recipient, set *StickerSet) error
	CreateTopic(chat *Chat, topic *Topic) (*Topic, error)
	CustomEmojiStickers(ids []string) ([]Sticker, error)
	DeclineJoinRequest(chat Recipient, user *User) error
	DefaultRights(forChannels bool) (*Rights, error)
	Delete(msg Editable) error
	DeleteCommands(opts ...interface{}) error
	DeleteGroupPhoto(chat *Chat) error
	DeleteGroupStickerSet(chat *Chat) error
	DeleteMany(msgs []Editable) error
	DeleteSticker(sticker string) error
	DeleteStickerSet(name string) error
	DeleteTopic(chat *Chat, topic *Topic) error
	Download(file *File, localFilename string) error
	DownloadToWriter(file *File, w io.Writer) error
	Edit(msg Editable, what interface{}, opts ...interface{}) (*Message, error)
	EditCaption(msg Editable, caption string, opts ...interface{}) (*Message, error)
	EditGeneralTopic(chat *Chat, topic *Topic) error
	EditInviteLink(chat Recipient, link *ChatInviteLink) (*ChatInviteLink, error)
	EditMedia(msg Editable, media Inputtable, opts ...interface{}) (*Message, error)
	EditReplyMarkup(msg Editable, markup *ReplyMarkup) (*Message, error)
	EditTopic(chat *Chat, topic *Topic) error
	File(file *File) (io.ReadCloser, error)
	FileByID(fileID string) (File, error)
	Forward(to Recipient, msg Editable, opts ...interface{}) (*Message, error)
	ForwardMany(to Recipient, msgs []Editable, opts ...*SendOptions) ([]Message, error)
	GameScores(user Recipient, msg Editable) ([]GameHighScore, error)
	GetAvailableGifts() ([]Gift, error)
	HideGeneralTopic(chat *Chat) error
	InviteLink(chat *Chat) (string, error)
	Leave(chat Recipient) error
	Len(chat *Chat) (int, error)
	Logout() (bool, error)
	MenuButton(chat *User) (*MenuButton, error)
	MyDescription(language string) (*BotInfo, error)
	MyName(language string) (*BotInfo, error)
	MyShortDescription(language string) (*BotInfo, error)
	Notify(to Recipient, action ChatAction, threadID ...int) error
	Pin(msg Editable, opts ...interface{}) error
	ProfileAudiosOf(user *User, offset, limit int) (*UserProfileAudios, error)
	ProfilePhotosOf(user *User) ([]Photo, error)
	Promote(chat *Chat, member *ChatMember) error
	React(to Recipient, msg Editable, r Reactions) error
	RefundStars(to Recipient, chargeID string) error
	EditUserStarSubscription(user Recipient, chargeID string, isCanceled bool) error
	RemoveMyProfilePhoto() error
	RemoveWebhook(dropPending ...bool) error
	ReopenGeneralTopic(chat *Chat) error
	ReopenTopic(chat *Chat, topic *Topic) error
	ReplaceStickerInSet(of Recipient, stickerSet, oldSticker string, sticker InputSticker) (bool, error)
	Reply(to *Message, what interface{}, opts ...interface{}) (*Message, error)
	Respond(c *Callback, resp ...*CallbackResponse) error
	Restrict(chat *Chat, member *ChatMember) error
	RevokeInviteLink(chat Recipient, link string) (*ChatInviteLink, error)
	Send(to Recipient, what interface{}, opts ...interface{}) (*Message, error)
	SendAlbum(to Recipient, a Album, opts ...interface{}) ([]Message, error)
	SendDraft(to Recipient, draftID int, text string, opts ...interface{}) error
	SendPaidMedia(to Recipient, stars int, a PaidAlbum, opts ...interface{}) (*Message, error)
	SendGift(to Recipient, giftID string, opts ...interface{}) error
	SavePreparedInlineMessage(user Recipient, result Result, opts ...interface{}) (*PreparedInlineMessage, error)
	SetAdminTitle(chat *Chat, user *User, title string) error
	SetMemberTag(chat *Chat, user *User, tag string) error
	SetCommands(opts ...interface{}) error
	SetCustomEmojiStickerSetThumb(name, id string) error
	SetDefaultRights(rights Rights, forChannels bool) error
	SetGameScore(user Recipient, msg Editable, score GameHighScore) (*Message, error)
	SetGroupDescription(chat *Chat, description string) error
	SetGroupPermissions(chat *Chat, perms Rights) error
	SetGroupStickerSet(chat *Chat, setName string) error
	SetGroupTitle(chat *Chat, title string) error
	SetMenuButton(chat *User, mb interface{}) error
	SetMyDescription(desc, language string) error
	SetMyName(name, language string) error
	SetMyProfilePhoto(photo InputProfilePhoto) error
	SetMyShortDescription(desc, language string) error
	SetStickerEmojis(sticker string, emojis []string) error
	SetStickerKeywords(sticker string, keywords []string) error
	SetStickerMaskPosition(sticker string, mask MaskPosition) error
	SetStickerPosition(sticker string, position int) error
	SetStickerSetThumb(of Recipient, set *StickerSet) error
	SetStickerSetTitle(s StickerSet) error
	SetUserEmojiStatus(user Recipient, emojiStatusCustomEmojiID string, expirationDate ...int64) error
	SetWebhook(w *Webhook) error
	Ship(query *ShippingQuery, what ...interface{}) error
	StarTransactions(offset, limit int) ([]StarTransaction, error)
	StickerSet(name string) (*StickerSet, error)
	StopLiveLocation(msg Editable, opts ...interface{}) (*Message, error)
	StopPoll(msg Editable, opts ...interface{}) (*Poll, error)
	TopicIconStickers() ([]Sticker, error)
	Unban(chat *Chat, user *User, forBanned ...bool) error
	UnbanSenderChat(chat *Chat, sender Recipient) error
	UnhideGeneralTopic(chat *Chat) error
	Unpin(chat Recipient, messageID ...int) error
	UnpinAll(chat Recipient) error
	UnpinAllGeneralTopicMessages(chat *Chat) error
	UnpinAllTopicMessages(chat *Chat, topic *Topic) error
	UploadSticker(to Recipient, format StickerSetFormat, f File) (*File, error)
	UserBoosts(chat, user Recipient) ([]Boost, error)
	Webhook() (*Webhook, error)
}

API is the interface that wraps all basic methods for interacting with Telegram Bot API.

type Account

type Account struct {
	ID         int64     `bun:",pk,autoincrement"`
	TelegramID int64     `bun:",unique,notnull"`
	Username   string    `bun:",nullzero"`
	FirstName  string    `bun:",nullzero"`
	LastName   string    `bun:",nullzero"`
	Language   string    `bun:",nullzero"`
	CreatedAt  time.Time `bun:",notnull,default:current_timestamp"`
	UpdatedAt  time.Time `bun:",notnull,default:current_timestamp"`
}

Account is a Telegram user the bot has seen, stored in the "accounts" table. The table is owned by the framework; apps that need more columns keep them in their own tables keyed by accounts.id.

type AffiliateInfo

type AffiliateInfo struct {
	// (Optional) Information about the affiliate program that paid the transaction
	AffiliateProgram *TransactionPartnerAffiliateProgram `json:"affiliate_program,omitempty"`

	// (Optional) The number of Telegram Stars received by the affiliate program for each 1000 Telegram Stars received by the bot
	CommissionPerMille int `json:"commission_per_mille"`

	// (Optional) Monetary amount of the commission
	Amount int `json:"amount,omitempty"`

	// (Optional) Nanostar amount of the commission
	NanostarAmount int `json:"nanostar_amount,omitempty"`
}

AffiliateInfo contains information about the affiliate program from which the transaction was made.

func (*AffiliateInfo) CommissionPercentage

func (a *AffiliateInfo) CommissionPercentage() float64

CommissionPercentage returns the commission rate as a percentage.

func (*AffiliateInfo) HasNanostarAmount

func (a *AffiliateInfo) HasNanostarAmount() bool

HasNanostarAmount returns whether the affiliate info has a nanostar amount.

func (*AffiliateInfo) IsAffiliateProgram

func (a *AffiliateInfo) IsAffiliateProgram() bool

IsAffiliateProgram returns whether this is an affiliate program transaction.

func (*AffiliateInfo) NanostarAmountAsTON

func (a *AffiliateInfo) NanostarAmountAsTON() float64

NanostarAmountAsTON returns the nanostar commission amount as TON value.

type Album

type Album []Inputtable

Album lets you group multiple media into a single message.

func (Album) SetCaption

func (a Album) SetCaption(caption string)

type Animation

type Animation struct {
	File

	Width    int `json:"width"`
	Height   int `json:"height"`
	Duration int `json:"duration,omitempty"`

	// (Optional)
	Caption      string `json:"caption,omitempty"`
	Thumbnail    *Photo `json:"thumbnail,omitempty"`
	MIME         string `json:"mime_type,omitempty"`
	FileName     string `json:"file_name,omitempty"`
	HasSpoiler   bool   `json:"has_spoiler,omitempty"`
	CaptionAbove bool   `json:"show_caption_above_media,omitempty"`
}

Animation object represents a animation file.

func (*Animation) InputMedia

func (a *Animation) InputMedia() InputMedia

func (*Animation) MediaFile

func (a *Animation) MediaFile() *File

func (*Animation) MediaType

func (a *Animation) MediaType() string

func (*Animation) Send

func (a *Animation) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers animation through bot b to recipient.

type App

type App[T any] struct {
	// contains filtered or unexported fields
}

App is a Telegram bot with sessions, scenes, localization and persistence. T is the app-specific session state; use struct{} when there is none.

func New

func New[T any](cfg Config, opts ...AppOption[T]) (*App[T], error)

New creates the bot, opens and migrates the database (SQLite by default) and installs the text and callback routers.

func (*App[T]) Bot

func (a *App[T]) Bot() *Bot

Bot returns the underlying bot for anything the framework doesn't cover.

func (*App[T]) Callback

func (a *App[T]) Callback(key BtnKey, h Handler[T])

Callback registers the handler of an inline button.

func (*App[T]) Close

func (a *App[T]) Close() error

Close releases the database if the app opened it. Run calls it on exit.

func (*App[T]) Command

func (a *App[T]) Command(command string, h Handler[T])

Command registers a handler for a command such as "/start".

func (*App[T]) DB

func (a *App[T]) DB() *bun.DB

DB returns the database handle so the app can keep its own tables in the same database. It is nil when a custom Store was given.

func (*App[T]) DefaultCallback

func (a *App[T]) DefaultCallback(h Handler[T])

DefaultCallback handles button presses without a registered Callback. By default the spinner is dismissed and a warning is logged. As for every callback, button data is already split: Callback().Unique holds the unregistered unique (empty for data not produced by a BtnKey), Data the payload and RawData the original string.

func (*App[T]) DefaultText

func (a *App[T]) DefaultText(h Handler[T])

DefaultText handles text that no Text, Reply or Scene route matched. By default such messages are ignored.

func (*App[T]) Handle

func (a *App[T]) Handle(endpoint any, h Handler[T])

Handle registers a handler for any other telebot endpoint, such as OnDocument, OnPhoto, OnCheckout or OnPayment, with the framework context. OnText and OnCallback are owned by the routers: use DefaultText and DefaultCallback instead.

func (*App[T]) I18n

func (a *App[T]) I18n() *I18n

I18n returns the translation registry.

func (*App[T]) LanguageKeyboard

func (a *App[T]) LanguageKeyboard() *ReplyMarkup

LanguageKeyboard returns an inline keyboard with one button per registered language, in registration order, labelled with the language's name.

func (*App[T]) Logger

func (a *App[T]) Logger() *slog.Logger

Logger returns the app's logger.

func (*App[T]) OnLanguageSelected

func (a *App[T]) OnLanguageSelected(next Handler[T], legacy ...BtnKey)

OnLanguageSelected handles presses on LanguageKeyboard buttons: the chat's language is set (and stored on the account), the button's spinner is dismissed, then next runs, typically to show the main menu in the new language. next may be nil.

legacy lists older button keys whose payload is also a language code, so language keyboards already sitting in chats keep working after a bot switches to the built-in picker (e.g. Boteland's "setLang").

func (*App[T]) Reply

func (a *App[T]) Reply(i18nKey string, h Handler[T])

Reply registers the handler of a reply-keyboard button whose label is the translation of i18nKey: a message equal to the key's text in any registered language triggers it, whatever the chat's current scene.

func (*App[T]) Run

func (a *App[T]) Run(ctx context.Context) error

Run polls for updates until ctx is cancelled, then stops polling, waits (up to the shutdown timeout) for running handlers to finish, and closes the database if the app opened it.

func (*App[T]) Scene

func (a *App[T]) Scene(scene Scene) *SceneRouter[T]

Scene returns the router of a scene, creating it on first use. Text messages of chats in that scene are dispatched by their current question.

func (*App[T]) Sessions

func (a *App[T]) Sessions() *SessionStore[T]

Sessions returns the session cache, e.g. to update a session from outside a handler (a scheduler, a webhook). Hold Lock while doing so and Save after.

func (*App[T]) Start

func (a *App[T]) Start() error

Start runs the bot until SIGINT or SIGTERM.

func (*App[T]) Store

func (a *App[T]) Store() Store

Store returns the store holding accounts and sessions.

func (*App[T]) Text

func (a *App[T]) Text(text string, h Handler[T])

Text registers a handler for messages exactly equal to text, whatever the chat's current scene.

func (*App[T]) Use

func (a *App[T]) Use(mw ...Middleware[T])

Use adds middlewares that run around every framework handler, in order.

type AppOption

type AppOption[T any] func(*App[T])

AppOption customizes an App. (Option is telebot's send option.)

func WithDB

func WithDB[T any](db *bun.DB) AppOption[T]

WithDB uses an already open database instead of opening one from Config.DB. The framework migrates its tables in it but does not close it.

func WithI18n

func WithI18n[T any](i *I18n) AppOption[T]

WithI18n sets the translation registry. By default an empty one with the configured DefaultLanguage is created; register languages with app.I18n().Register.

func WithLogger

func WithLogger[T any](l *slog.Logger) AppOption[T]

WithLogger sets the logger (slog.Default() otherwise).

func WithSettings

func WithSettings[T any](fn func(*Settings)) AppOption[T]

WithSettings adjusts the telebot Settings before the bot is created, e.g. to use a webhook poller, set Offline for tests, or change ParseMode (ModeMarkdownV2 by default).

func WithShutdownTimeout

func WithShutdownTimeout[T any](d time.Duration) AppOption[T]

WithShutdownTimeout bounds how long Run waits for running handlers after polling stops (10s by default).

func WithStore

func WithStore[T any](s Store) AppOption[T]

WithStore replaces the default SQL store, e.g. with NewMemoryStore() in tests. No database is opened when a store is given.

type ArticleResult

type ArticleResult struct {
	ResultBase

	// Title of the result.
	Title string `json:"title"`

	// Message text. Shortcut (and mutually exclusive to) specifying
	// InputMessageContent.
	Text string `json:"message_text,omitempty"`

	// Optional. URL of the result.
	URL string `json:"url,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. URL of the thumbnail for the result.
	ThumbURL string `json:"thumbnail_url,omitempty"`

	// Optional. Width of the thumbnail for the result.
	ThumbWidth int `json:"thumbnail_width,omitempty"`

	// Optional. Height of the thumbnail for the result.
	ThumbHeight int `json:"thumbnail_height,omitempty"`
}

ArticleResult represents a link to an article or web page.

type Audio

type Audio struct {
	File

	Duration int `json:"duration,omitempty"`

	// (Optional)
	Caption   string `json:"caption,omitempty"`
	Thumbnail *Photo `json:"thumbnail,omitempty"`
	Title     string `json:"title,omitempty"`
	Performer string `json:"performer,omitempty"`
	MIME      string `json:"mime_type,omitempty"`
	FileName  string `json:"file_name,omitempty"`
}

Audio object represents an audio file.

func (*Audio) InputMedia

func (a *Audio) InputMedia() InputMedia

func (*Audio) MediaFile

func (a *Audio) MediaFile() *File

func (*Audio) MediaType

func (a *Audio) MediaType() string

func (*Audio) Send

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

Send delivers media through bot b to recipient.

type AudioResult

type AudioResult struct {
	ResultBase

	// Title.
	Title string `json:"title"`

	// A valid URL for the audio file.
	URL string `json:"audio_url"`

	// Optional. Performer.
	Performer string `json:"performer,omitempty"`

	// Optional. Audio duration in seconds.
	Duration int `json:"audio_duration,omitempty"`

	// Optional. Caption, 0-1024 characters.
	Caption string `json:"caption,omitempty"`

	// If Cache != "", it'll be used instead
	Cache string `json:"audio_file_id,omitempty"`
}

AudioResult represents a link to an mp3 audio file.

type AutoDeleteTimer

type AutoDeleteTimer struct {
	Unixtime int `json:"message_auto_delete_time"`
}

AutoDeleteTimer represents a service message about a change in auto-delete timer settings.

type BackgroundFill

type BackgroundFill struct {
	// Type of the background fill.
	Type string `json:"type"`

	// The color of the background fill in the RGB24 format
	SolidColor int `json:"color,omitempty"`

	// Top color of the gradient in the RGB24 format
	GradientTopColor int `json:"top_color,omitempty"`

	// Bottom color of the gradient in the RGB24 format
	GradientBottomColor int `json:"bottom_color,omitempty"`

	// Clockwise rotation angle of the background fill in degrees; 0-359
	GradientRotationAngle int `json:"rotation_angle,omitempty"`

	// A list of the 3 or 4 base colors that are used to generate
	// the freeform gradient in the RGB24 format
	GradientColors []int `json:"colors,omitempty"`
}

type BackgroundType

type BackgroundType struct {
	// Type of the background, always “fill”
	Type string `json:"type"`

	// The background fill
	Fill BackgroundFill `json:"fill,omitempty"`

	// Document with the wallpaper
	Document Document `json:"document,omitempty"`

	// Dimming of the background in dark themes, as a percentage; 0-100
	DarkThemeDimming int `json:"dark_theme_dimming,omitempty"`

	// Intensity of the pattern when it is shown above the filled background; 0-100
	Intensity int `json:"intensity,omitempty"`

	// (Optional) True, if the wallpaper is downscaled to fit in a 450x450
	// square and then box-blurred with radius 12
	Blurred bool `json:"is_blurred,omitempty"`

	// (Optional) True, if the background moves slightly when the device is tilted
	Moving bool `json:"is_moving,omitempty"`

	// (Optional) True, if the background fill must be applied only to the pattern itself.
	// All other pixels are black in this case. For dark themes only
	Inverted bool `json:"is_inverted,omitempty"`

	// Name of the chat theme, which is usually an emoji
	ThemeName string `json:"theme_name,omitempty"`
}

type Birthdate

type Birthdate struct {
	// Day of the user's birth; 1-31
	Day int `json:"day"`

	// Month of the user's birth; 1-12
	Month int `json:"month"`

	// (Optional) Year of the user's birth
	Year int `json:"year"`
}

type Boost

type Boost struct {
	// Unique identifier of the boost.
	ID string `json:"boost_id"`

	// Point in time (Unix timestamp) when the chat was boosted.
	AddUnixtime int64 `json:"add_date"`

	// Point in time (Unix timestamp) when the boost will automatically expire,
	// unless the booster's Telegram Premium subscription is prolonged.
	ExpirationUnixtime int64 `json:"expiration_date"`

	// Source of the added boost.
	Source *BoostSource `json:"source"`
}

Boost contains information about a chat boost.

func (*Boost) AddDate

func (c *Boost) AddDate() time.Time

AddDate returns the moment of time when the chat has been boosted in local time.

func (*Boost) ExpirationDate

func (c *Boost) ExpirationDate() time.Time

ExpirationDate returns the moment of time when the boost of the channel will expire in local time.

type BoostAdded

type BoostAdded struct {
	// Number of boosts added by the user.
	Count int `json:"boost_count"`
}

BoostAdded represents a service message about a user boosting a chat.

type BoostRemoved

type BoostRemoved struct {
	// Chat which was boosted.
	Chat *Chat `json:"chat"`

	// Unique identifier of the boost.
	BoostID string `json:"boost_id"`

	// Point in time (Unix timestamp) when the boost was removed.
	RemoveUnixtime int64 `json:"remove_date"`

	// Source of the removed boost.
	Source *BoostSource `json:"source"`
}

BoostRemoved represents a boost removed from a chat.

type BoostSource

type BoostSource struct {
	// Source of the boost, always (“premium”, “gift_code”, “giveaway”).
	Source BoostSourceType `json:"source"`

	// User that boosted the chat.
	Booster *User `json:"user"`

	// Identifier of a message in the chat with the giveaway; the message
	// could have been deleted already. May be 0 if the message isn't sent yet.
	GiveawayMessageID int `json:"giveaway_message_id,omitempty"`

	// (Optional) True, if the giveaway was completed, but there was
	// no user to win the prize.
	Unclaimed bool `json:"is_unclaimed,omitempty"`

	// (Optional) The number of Telegram Stars to be split between giveaway winners;
	// for Telegram Star giveaways only.
	PrizeStarCount int `json:"prize_star_count,omitempty"`
}

BoostSource describes the source of a chat boost.

type BoostSourceType

type BoostSourceType = string

BoostSourceType describes a type of boost.

const (
	BoostPremium  BoostSourceType = "premium"
	BoostGiftCode BoostSourceType = "gift_code"
	BoostGiveaway BoostSourceType = "giveaway"
)

type BoostUpdated

type BoostUpdated struct {
	// Chat which was boosted.
	Chat *Chat `json:"chat"`

	// Information about the chat boost.
	Boost *Boost `json:"boost"`
}

BoostUpdated represents a boost added to a chat or changed.

type Bot

type Bot struct {
	Me      *User
	Token   string
	URL     string
	Updates chan Update
	Poller  Poller
	// contains filtered or unexported fields
}

Bot represents a separate Telegram bot instance.

func NewBot

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

NewBot does try to build a Bot with token `token`, which is a secret API key assigned to particular bot.

func (*Bot) Accept

func (b *Bot) Accept(query *PreCheckoutQuery, errorMessage ...string) error

Accept finalizes the deal.

func (*Bot) AddStickerToSet

func (b *Bot) AddStickerToSet(of Recipient, name string, sticker InputSticker) error

AddStickerToSet adds a new sticker to the existing sticker set.

func (*Bot) AdminsOf

func (b *Bot) AdminsOf(chat *Chat) ([]ChatMember, error)

AdminsOf returns a member list of chat admins.

On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.

If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

func (*Bot) Answer

func (b *Bot) Answer(query *Query, resp *QueryResponse) error

Answer sends a response for a given inline query. A query can only be responded to once, subsequent attempts to respond to the same query will result in an error.

func (*Bot) AnswerGuest

func (b *Bot) AnswerGuest(msg *Message, result Result) (*SentGuestMessage, error)

AnswerGuest sends a response for a given guest message.

func (*Bot) AnswerWebApp

func (b *Bot) AnswerWebApp(query *Query, r Result) (*WebAppMessage, error)

AnswerWebApp sends a response for a query from Web App and returns information about an inline message sent by a Web App on behalf of a user

func (*Bot) ApproveJoinRequest

func (b *Bot) ApproveJoinRequest(chat Recipient, user *User) error

ApproveJoinRequest approves a chat join request.

func (*Bot) Ban

func (b *Bot) Ban(chat *Chat, member *ChatMember, revokeMessages ...bool) error

Ban will ban user from chat until `member.RestrictedUntil`.

func (*Bot) BanSenderChat

func (b *Bot) BanSenderChat(chat *Chat, sender Recipient) error

BanSenderChat will use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels.

func (*Bot) BusinessConnection

func (b *Bot) BusinessConnection(id string) (*BusinessConnection, error)

BusinessConnection returns the information about the connection of the bot with a business account.

func (*Bot) ChatByID

func (b *Bot) ChatByID(id int64) (*Chat, error)

ChatByID fetches chat info of its ID.

Including current name of the user for one-on-one conversations, current username of a user, group or channel, etc.

func (*Bot) ChatByUsername

func (b *Bot) ChatByUsername(name string) (*Chat, error)

ChatByUsername fetches chat info by its username.

func (*Bot) ChatFullInfo

func (b *Bot) ChatFullInfo(chat Recipient) (*ChatFullInfo, error)

ChatFullInfo fetches full information about a chat.

func (*Bot) ChatMemberOf

func (b *Bot) ChatMemberOf(chat, user Recipient) (*ChatMember, error)

ChatMemberOf returns information about a member of a chat.

func (*Bot) Close

func (b *Bot) Close() (bool, error)

Close closes the bot instance before moving it from one local server to another.

func (*Bot) CloseGeneralTopic

func (b *Bot) CloseGeneralTopic(chat *Chat) error

CloseGeneralTopic closes an open 'General' topic in a forum supergroup chat.

func (*Bot) CloseTopic

func (b *Bot) CloseTopic(chat *Chat, topic *Topic) error

CloseTopic closes an open topic in a forum supergroup chat.

func (*Bot) Commands

func (b *Bot) Commands(opts ...interface{}) ([]Command, error)

Commands returns the current list of the bot's commands for the given scope and user language.

func (*Bot) Copy

func (b *Bot) Copy(to Recipient, msg Editable, opts ...interface{}) (*Message, error)

Copy behaves just like Forward() but the copied message doesn't have a link to the original message (see Bots API).

This function will panic upon nil Editable.

func (*Bot) CopyMany

func (b *Bot) CopyMany(to Recipient, msgs []Editable, opts ...*SendOptions) ([]Message, error)

CopyMany this method makes a copy of messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages.

func (b *Bot) CreateInviteLink(chat Recipient, link *ChatInviteLink) (*ChatInviteLink, error)

CreateInviteLink creates an additional invite link for a chat.

func (b *Bot) CreateInvoiceLink(i Invoice) (string, error)

CreateInvoiceLink creates a link for a payment invoice.

func (*Bot) CreateStickerSet

func (b *Bot) CreateStickerSet(of Recipient, set *StickerSet) error

CreateStickerSet creates a new sticker set.

func (*Bot) CreateTopic

func (b *Bot) CreateTopic(chat *Chat, topic *Topic) (*Topic, error)

CreateTopic creates a topic in a forum supergroup chat.

func (*Bot) CustomEmojiStickers

func (b *Bot) CustomEmojiStickers(ids []string) ([]Sticker, error)

CustomEmojiStickers returns the information about custom emoji stickers by their ids.

func (*Bot) DeclineJoinRequest

func (b *Bot) DeclineJoinRequest(chat Recipient, user *User) error

DeclineJoinRequest declines a chat join request.

func (*Bot) DefaultRights

func (b *Bot) DefaultRights(forChannels bool) (*Rights, error)

DefaultRights returns the current default administrator rights of the bot.

func (*Bot) Delete

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

Delete removes the message, including service messages. This function will panic upon nil Editable.

  • A message can only be deleted if it was sent less than 48 hours ago.
  • A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
  • Bots can delete outgoing messages in private chats, groups, and supergroups.
  • Bots can delete incoming messages in private chats.
  • Bots granted can_post_messages permissions can delete outgoing messages in channels.
  • If the bot is an administrator of a group, it can delete any message there.
  • If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.

func (*Bot) DeleteCommands

func (b *Bot) DeleteCommands(opts ...interface{}) error

DeleteCommands deletes the list of the bot's commands for the given scope and user language.

func (*Bot) DeleteGroupPhoto

func (b *Bot) DeleteGroupPhoto(chat *Chat) error

DeleteGroupPhoto should be used to just remove group photo.

func (*Bot) DeleteGroupStickerSet

func (b *Bot) DeleteGroupStickerSet(chat *Chat) error

DeleteGroupStickerSet should be used to just remove group sticker set.

func (*Bot) DeleteMany

func (b *Bot) DeleteMany(msgs []Editable) error

DeleteMany deletes multiple messages simultaneously. If some of the specified messages can't be found, they are skipped.

func (*Bot) DeleteSticker

func (b *Bot) DeleteSticker(sticker string) error

DeleteSticker deletes a sticker from a set created by the bot.

func (*Bot) DeleteStickerSet

func (b *Bot) DeleteStickerSet(name string) error

DeleteStickerSet deletes a sticker set that was created by the bot.

func (*Bot) DeleteTopic

func (b *Bot) DeleteTopic(chat *Chat, topic *Topic) error

DeleteTopic deletes a forum topic along with all its messages in a forum supergroup chat.

func (*Bot) Download

func (b *Bot) Download(file *File, localFilename string) error

Download saves the file from Telegram servers locally. Maximum file size to download is 20 MB.

func (*Bot) DownloadToWriter

func (b *Bot) DownloadToWriter(file *File, w io.Writer) error

DownloadToWriter streams a file from Telegram servers into w, e.g. to forward it to object storage or another service without saving it to disk first. file.FilePath is filled in, as with File and Download. Maximum file size to download is 20 MB.

func (*Bot) Edit

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

Edit is magic, it lets you change already sent message. This function will panic upon nil Editable.

If edited message is sent by the bot, returns it, otherwise returns nil and ErrTrueResult.

Use cases:

b.Edit(m, m.Text, newMarkup)
b.Edit(m, "new <b>text</b>", tele.ModeHTML)
b.Edit(m, &tele.ReplyMarkup{...})
b.Edit(m, &tele.Photo{File: ...})
b.Edit(m, tele.Location{42.1337, 69.4242})
b.Edit(c, "edit inline message from the callback")
b.Edit(r, "edit message from chosen inline result")

func (*Bot) EditCaption

func (b *Bot) EditCaption(msg Editable, caption string, opts ...interface{}) (*Message, error)

EditCaption edits already sent photo caption with known recipient and message id. This function will panic upon nil Editable.

If edited message is sent by the bot, returns it, otherwise returns nil and ErrTrueResult.

func (*Bot) EditGeneralTopic

func (b *Bot) EditGeneralTopic(chat *Chat, topic *Topic) error

EditGeneralTopic edits name of the 'General' topic in a forum supergroup chat.

func (b *Bot) EditInviteLink(chat Recipient, link *ChatInviteLink) (*ChatInviteLink, error)

EditInviteLink edits a non-primary invite link created by the bot.

func (*Bot) EditMedia

func (b *Bot) EditMedia(msg Editable, media Inputtable, opts ...interface{}) (*Message, error)

EditMedia edits already sent media with known recipient and message id. This function will panic upon nil Editable.

If edited message is sent by the bot, returns it, otherwise returns nil and ErrTrueResult.

Use cases:

b.EditMedia(m, &tele.Photo{File: tele.FromDisk("chicken.jpg")})
b.EditMedia(m, &tele.Video{File: tele.FromURL("http://video.mp4")})

func (*Bot) EditReplyMarkup

func (b *Bot) EditReplyMarkup(msg Editable, markup *ReplyMarkup) (*Message, error)

EditReplyMarkup edits reply markup of already sent message. This function will panic upon nil Editable. Pass nil or empty ReplyMarkup to delete it from the message.

If edited message is sent by the bot, returns it, otherwise returns nil and ErrTrueResult.

func (*Bot) EditTopic

func (b *Bot) EditTopic(chat *Chat, topic *Topic) error

EditTopic edits name and icon of a topic in a forum supergroup chat.

func (*Bot) EditUserStarSubscription

func (b *Bot) EditUserStarSubscription(user Recipient, chargeID string, isCanceled bool) error

EditUserStarSubscription allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars.

func (*Bot) File

func (b *Bot) File(file *File) (io.ReadCloser, error)

File gets a file from Telegram servers.

func (*Bot) FileByID

func (b *Bot) FileByID(fileID string) (File, error)

FileByID returns full file object including File.FilePath, allowing you to download the file from the server.

Usually, Telegram-provided File objects miss FilePath so you might need to perform an additional request to fetch them.

func (*Bot) Forward

func (b *Bot) Forward(to Recipient, msg Editable, opts ...interface{}) (*Message, error)

Forward behaves just like Send() but of all options it only supports Silent (see Bots API). This function will panic upon nil Editable.

func (*Bot) ForwardMany

func (b *Bot) ForwardMany(to Recipient, msgs []Editable, opts ...*SendOptions) ([]Message, error)

ForwardMany method forwards multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages.

func (*Bot) GameScores

func (b *Bot) GameScores(user Recipient, msg Editable) ([]GameHighScore, error)

GameScores returns the score of the specified user and several of their neighbors in a game.

This function will panic upon nil Editable.

Currently, it returns scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them.

func (*Bot) GetAvailableGifts

func (b *Bot) GetAvailableGifts() ([]Gift, error)

GetAvailableGifts returns the list of gifts that can be sent by the bot to users.

func (*Bot) Group

func (b *Bot) Group() *Group

Group returns a new group.

func (*Bot) Handle

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

Handle lets you set the handler for some command name or one of the supported endpoints. It also applies middleware if such passed to the function.

Example:

b.Handle("/start", func (c tele.Context) error {
	return c.Reply("Hello!")
})

b.Handle(&inlineButton, func (c tele.Context) error {
	return c.Respond(&tele.CallbackResponse{Text: "Hello!"})
})

Middleware usage:

b.Handle("/ban", onBan, middleware.Whitelist(ids...))

func (*Bot) HideGeneralTopic

func (b *Bot) HideGeneralTopic(chat *Chat) error

HideGeneralTopic hides the 'General' topic in a forum supergroup chat.

func (b *Bot) InviteLink(chat *Chat) (string, error)

InviteLink should be used to export chat's invite link.

func (*Bot) Leave

func (b *Bot) Leave(chat Recipient) error

Leave makes bot leave a group, supergroup or channel.

func (*Bot) Len

func (b *Bot) Len(chat *Chat) (int, error)

Len returns the number of members in a chat.

func (*Bot) Logout

func (b *Bot) Logout() (bool, error)

Logout logs out from the cloud Bot API server before launching the bot locally.

func (*Bot) MenuButton

func (b *Bot) MenuButton(chat *User) (*MenuButton, error)

MenuButton returns the current value of the bot's menu button in a private chat, or the default menu button.

func (*Bot) MyDescription

func (b *Bot) MyDescription(language string) (*BotInfo, error)

MyDescription the current bot description for the given user language.

func (*Bot) MyName

func (b *Bot) MyName(language string) (*BotInfo, error)

MyName returns the current bot name for the given user language.

func (*Bot) MyShortDescription

func (b *Bot) MyShortDescription(language string) (*BotInfo, error)

MyShortDescription the current bot short description for the given user language.

func (*Bot) NewContext

func (b *Bot) NewContext(u Update) Context

NewContext returns a new native context object, field by the passed update.

func (*Bot) NewMarkup

func (b *Bot) NewMarkup() *ReplyMarkup

NewMarkup simply returns newly created markup instance.

func (*Bot) Notify

func (b *Bot) Notify(to Recipient, action ChatAction, threadID ...int) error

Notify updates the chat action for recipient.

Chat action is a status message that recipient would see where you typically see "Harry is typing" status message. The only difference is that bots' chat actions live only for 5 seconds and die just once the client receives a message from the bot.

Currently, Telegram supports only a narrow range of possible actions, these are aligned as constants of this package.

func (*Bot) OnError

func (b *Bot) OnError(err error, c Context)

func (*Bot) Pin

func (b *Bot) Pin(msg Editable, opts ...interface{}) error

Pin pins a message in a supergroup or a channel.

It supports Silent option. This function will panic upon nil Editable.

func (*Bot) ProcessContext

func (b *Bot) ProcessContext(c Context)

ProcessContext processes the given context. A started bot calls this function automatically.

func (*Bot) ProcessUpdate

func (b *Bot) ProcessUpdate(u Update)

ProcessUpdate processes a single incoming update. A started bot calls this function automatically.

func (*Bot) ProfileAudiosOf

func (b *Bot) ProfileAudiosOf(user *User, offset, limit int) (*UserProfileAudios, error)

ProfileAudiosOf returns a list of profile audios for a user. offset is the sequential number of the first audio to be returned (0 to start). limit caps the number of audios; values 1-100 are accepted (0 means default 100).

func (*Bot) ProfilePhotosOf

func (b *Bot) ProfilePhotosOf(user *User) ([]Photo, error)

ProfilePhotosOf returns list of profile pictures for a user.

func (*Bot) Promote

func (b *Bot) Promote(chat *Chat, member *ChatMember) error

Promote lets you update member's admin rights, such as:

  • can change info
  • can post messages
  • can edit messages
  • can delete messages
  • can invite users
  • can restrict members
  • can pin messages
  • can promote members

func (*Bot) Raw

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

Raw lets you call any method of Bot API manually. It also handles API errors, so you only need to unwrap result field from json data.

func (*Bot) React

func (b *Bot) React(to Recipient, msg Editable, r Reactions) error

React changes the chosen reactions on a message. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bot API 8.3+: Reactions are now allowed on most service messages.

func (*Bot) RefundStars

func (b *Bot) RefundStars(to Recipient, chargeID string) error

RefundStars returns a successful payment in Telegram Stars.

func (*Bot) RemoveChatVerification

func (b *Bot) RemoveChatVerification(chat *Chat) error

RemoveChatVerification removes verification from a chat.

func (*Bot) RemoveMyProfilePhoto

func (b *Bot) RemoveMyProfilePhoto() error

RemoveMyProfilePhoto removes the profile photo of the bot.

func (*Bot) RemoveUserVerification

func (b *Bot) RemoveUserVerification(user Recipient) error

RemoveUserVerification removes verification from a user.

func (*Bot) RemoveWebhook

func (b *Bot) RemoveWebhook(dropPending ...bool) error

RemoveWebhook removes webhook integration.

func (*Bot) ReopenGeneralTopic

func (b *Bot) ReopenGeneralTopic(chat *Chat) error

ReopenGeneralTopic reopens a closed 'General' topic in a forum supergroup chat.

func (*Bot) ReopenTopic

func (b *Bot) ReopenTopic(chat *Chat, topic *Topic) error

ReopenTopic reopens a closed topic in a forum supergroup chat.

func (*Bot) ReplaceStickerInSet

func (b *Bot) ReplaceStickerInSet(of Recipient, stickerSet, oldSticker string, sticker InputSticker) (bool, error)

ReplaceStickerInSet returns True on success, if existing sticker was replaced with a new one.

func (*Bot) Reply

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

Reply behaves just like Send() with an exception of "reply-to" indicator. This function will panic upon nil Message.

func (*Bot) Respond

func (b *Bot) Respond(c *Callback, resp ...*CallbackResponse) error

Respond sends a response for a given callback query. A callback can only be responded to once, subsequent attempts to respond to the same callback will result in an error.

Example:

b.Respond(c)
b.Respond(c, response)

func (*Bot) Restrict

func (b *Bot) Restrict(chat *Chat, member *ChatMember) error

Restrict lets you restrict a subset of member's rights until member.RestrictedUntil, such as:

  • can send messages
  • can send media
  • can send other
  • can add web page previews
func (b *Bot) RevokeInviteLink(chat Recipient, link string) (*ChatInviteLink, error)

RevokeInviteLink revokes an invite link created by the bot.

func (*Bot) SavePreparedInlineMessage

func (b *Bot) SavePreparedInlineMessage(user Recipient, result Result, opts ...interface{}) (*PreparedInlineMessage, error)

SavePreparedInlineMessage stores a message that can be sent by a user of a Mini App.

func (*Bot) Send

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

Send accepts 2+ arguments, starting with destination chat, followed by some Sendable (or string!) and optional send options.

NOTE:

Since most arguments are of type interface{}, but have pointer
method receivers, make sure to pass them by-pointer, NOT by-value.

What is a send option exactly? It can be one of the following types:

  • *SendOptions (the actual object accepted by Telegram API)
  • *ReplyMarkup (a component of SendOptions)
  • Option (a shortcut flag for popular options)
  • ParseMode (HTML, Markdown, etc)

func (*Bot) SendAlbum

func (b *Bot) SendAlbum(to Recipient, a Album, opts ...interface{}) ([]Message, error)

SendAlbum sends multiple instances of media as a single message. To include the caption, make sure the first Inputtable of an album has it. From all existing options, it only supports tele.Silent.

func (*Bot) SendDraft

func (b *Bot) SendDraft(to Recipient, draftID int, text string, opts ...interface{}) error

SendDraft streams a partial message to a user while the message is being generated. The streamed draft is ephemeral and acts as a temporary 30-second preview — once the output is finalized, you must call Send with the complete message to persist it. draftID must be non-zero; updates with the same identifier are animated client-side. Pass an empty text to show a "Thinking…" placeholder.

Only ParseMode, Entities and ThreadID send options are honored; other fields are not accepted by sendMessageDraft.

func (*Bot) SendGift

func (b *Bot) SendGift(to Recipient, giftID string, opts ...interface{}) error

SendGift sends a gift to the given user or chat member. The gift can't be converted to Telegram Stars by the user. Additional text can be passed as a string option. PayForUpgrade can be passed as a bool to pay for upgrading the gift. For Bot API 8.3+, you can pass a chat as the first parameter to send gifts to specific chat members.

func (*Bot) SendPaidMedia

func (b *Bot) SendPaidMedia(to Recipient, stars int, a PaidAlbum, opts ...interface{}) (*Message, error)

SendPaidMedia sends multiple instances of paid media as a single message. To include the caption, make sure the first PaidInputtable of an album has it.

func (*Bot) SendRichDraft

func (b *Bot) SendRichDraft(to Recipient, draftID int, rich *InputRichMessage, opts ...interface{}) error

SendRichDraft streams a partial rich message to a private chat while it is being generated (the sendRichMessageDraft method). The streamed draft is ephemeral and acts as a temporary 30-second preview; once the output is finalized you must Send the complete InputRichMessage to persist it. draftID must be non-zero — updates sharing the same identifier are animated client-side. Of the send options only ThreadID is honored.

func (*Bot) SetAdminTitle

func (b *Bot) SetAdminTitle(chat *Chat, user *User, title string) error

SetAdminTitle sets a custom title for an administrator. A title should be 0-16 characters length, emoji are not allowed.

func (*Bot) SetCommands

func (b *Bot) SetCommands(opts ...interface{}) error

SetCommands changes the list of the bot's commands.

func (*Bot) SetCustomEmojiStickerSetThumb

func (b *Bot) SetCustomEmojiStickerSetThumb(name, id string) error

SetCustomEmojiStickerSetThumb sets the thumbnail of a custom emoji sticker set.

func (*Bot) SetDefaultRights

func (b *Bot) SetDefaultRights(rights Rights, forChannels bool) error

SetDefaultRights changes the default administrator rights requested by the bot when it's added as an administrator to groups or channels.

func (*Bot) SetGameScore

func (b *Bot) SetGameScore(user Recipient, msg Editable, score GameHighScore) (*Message, error)

SetGameScore sets the score of the specified user in a game.

If the message was sent by the bot, returns the edited Message, otherwise returns nil and ErrTrueResult.

func (*Bot) SetGroupDescription

func (b *Bot) SetGroupDescription(chat *Chat, description string) error

SetGroupDescription should be used to update group description.

func (*Bot) SetGroupPermissions

func (b *Bot) SetGroupPermissions(chat *Chat, perms Rights) error

SetGroupPermissions sets default chat permissions for all members.

func (*Bot) SetGroupPhoto

func (b *Bot) SetGroupPhoto(chat *Chat, p *Photo) error

SetGroupPhoto should be used to update group photo.

func (*Bot) SetGroupStickerSet

func (b *Bot) SetGroupStickerSet(chat *Chat, setName string) error

SetGroupStickerSet should be used to update group's group sticker set.

func (*Bot) SetGroupTitle

func (b *Bot) SetGroupTitle(chat *Chat, title string) error

SetGroupTitle should be used to update group title.

func (*Bot) SetMemberTag

func (b *Bot) SetMemberTag(chat *Chat, user *User, tag string) error

SetMemberTag sets a tag for a regular member in a group or a supergroup. The bot must be an administrator with the can_manage_tags right. A tag should be 0-16 characters length, emoji are not allowed.

func (*Bot) SetMenuButton

func (b *Bot) SetMenuButton(chat *User, mb interface{}) error

SetMenuButton changes the bot's menu button in a private chat, or the default menu button.

It accepts two kinds of menu button arguments:

  • MenuButtonType for simple menu buttons (default, commands)
  • MenuButton complete structure for web_app menu button type

func (*Bot) SetMyDescription

func (b *Bot) SetMyDescription(desc, language string) error

SetMyDescription change's the bot description, which is shown in the chat with the bot if the chat is empty.

func (*Bot) SetMyName

func (b *Bot) SetMyName(name, language string) error

SetMyName change's the bot name.

func (*Bot) SetMyProfilePhoto

func (b *Bot) SetMyProfilePhoto(photo InputProfilePhoto) error

SetMyProfilePhoto changes the profile photo of the bot.

func (*Bot) SetMyShortDescription

func (b *Bot) SetMyShortDescription(desc, language string) error

SetMyShortDescription change's the bot short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.

func (*Bot) SetStickerEmojis

func (b *Bot) SetStickerEmojis(sticker string, emojis []string) error

SetStickerEmojis changes the list of emoji assigned to a regular or custom emoji sticker.

func (*Bot) SetStickerKeywords

func (b *Bot) SetStickerKeywords(sticker string, keywords []string) error

SetStickerKeywords changes search keywords assigned to a regular or custom emoji sticker.

func (*Bot) SetStickerMaskPosition

func (b *Bot) SetStickerMaskPosition(sticker string, mask MaskPosition) error

SetStickerMaskPosition changes the mask position of a mask sticker.

func (*Bot) SetStickerPosition

func (b *Bot) SetStickerPosition(sticker string, position int) error

SetStickerPosition moves a sticker in set to a specific position.

func (*Bot) SetStickerSetThumb

func (b *Bot) SetStickerSetThumb(of Recipient, set *StickerSet) error

SetStickerSetThumb sets a thumbnail of the sticker set. Animated thumbnails can be set for animated sticker sets only.

Thumbnail must be a PNG image, up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation up to 32 kilobytes in size.

Animated sticker set thumbnail can't be uploaded via HTTP URL.

func (*Bot) SetStickerSetTitle

func (b *Bot) SetStickerSetTitle(s StickerSet) error

SetStickerSetTitle sets the title of a created sticker set.

func (*Bot) SetUserEmojiStatus

func (b *Bot) SetUserEmojiStatus(user Recipient, emojiStatusCustomEmojiID string, expirationDate ...int64) error

SetUserEmojiStatus changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App Bot API.

func (*Bot) SetWebhook

func (b *Bot) SetWebhook(w *Webhook) error

SetWebhook configures a bot to receive incoming updates via an outgoing webhook.

func (*Bot) Ship

func (b *Bot) Ship(query *ShippingQuery, what ...interface{}) error

Ship replies to the shipping query, if you sent an invoice requesting an address and the parameter is_flexible was specified.

Example:

b.Ship(query)          // OK
b.Ship(query, opts...) // OK with options
b.Ship(query, "Oops!") // Error message

func (*Bot) StarTransactions

func (b *Bot) StarTransactions(offset, limit int) ([]StarTransaction, error)

func (*Bot) Start

func (b *Bot) Start()

Start brings bot into motion by consuming incoming updates (see Bot.Updates channel).

func (*Bot) StickerSet

func (b *Bot) StickerSet(name string) (*StickerSet, error)

StickerSet returns a sticker set on success.

func (*Bot) Stop

func (b *Bot) Stop()

Stop gracefully shuts the poller down.

func (*Bot) StopLiveLocation

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

StopLiveLocation stops broadcasting live message location before Location.LivePeriod expires.

It supports ReplyMarkup. This function will panic upon nil Editable.

If the message is sent by the bot, returns it, otherwise returns nil and ErrTrueResult.

func (*Bot) StopPoll

func (b *Bot) StopPoll(msg Editable, opts ...interface{}) (*Poll, error)

StopPoll stops a poll which was sent by the bot and returns the stopped Poll object with the final results.

It supports ReplyMarkup. This function will panic upon nil Editable.

func (*Bot) TopicIconStickers

func (b *Bot) TopicIconStickers() ([]Sticker, error)

TopicIconStickers gets custom emoji stickers, which can be used as a forum topic icon by any user.

func (*Bot) Trigger

func (b *Bot) Trigger(endpoint interface{}, c Context) error

Trigger executes the registered handler by the endpoint.

func (*Bot) Unban

func (b *Bot) Unban(chat *Chat, user *User, forBanned ...bool) error

Unban will unban user from chat, who would have thought eh? By default, it kicks the user if it is not banned, because it ensures the user is not a chat member but is able to join it. forBanned = true should be provided to ignore users that are not banned.

func (*Bot) UnbanSenderChat

func (b *Bot) UnbanSenderChat(chat *Chat, sender Recipient) error

UnbanSenderChat will use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights.

func (*Bot) UnhideGeneralTopic

func (b *Bot) UnhideGeneralTopic(chat *Chat) error

UnhideGeneralTopic unhides the 'General' topic in a forum supergroup chat.

func (*Bot) Unpin

func (b *Bot) Unpin(chat Recipient, messageID ...int) error

Unpin unpins a message in a supergroup or a channel. It supports tb.Silent option.

func (*Bot) UnpinAll

func (b *Bot) UnpinAll(chat Recipient) error

UnpinAll unpins all messages in a supergroup or a channel. It supports tb.Silent option.

func (*Bot) UnpinAllGeneralTopicMessages

func (b *Bot) UnpinAllGeneralTopicMessages(chat *Chat) error

UnpinAllGeneralTopicMessages clears the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup.

func (*Bot) UnpinAllTopicMessages

func (b *Bot) UnpinAllTopicMessages(chat *Chat, topic *Topic) error

UnpinAllTopicMessages clears the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup.

func (*Bot) UploadSticker

func (b *Bot) UploadSticker(to Recipient, format StickerSetFormat, f File) (*File, error)

UploadSticker uploads a sticker file for later use.

func (*Bot) Use

func (b *Bot) Use(middleware ...MiddlewareFunc)

Use adds middleware to the global bot chain.

func (*Bot) UserBoosts

func (b *Bot) UserBoosts(chat, user Recipient) ([]Boost, error)

UserBoosts gets the list of boosts added to a chat by a user. Requires administrator rights in the chat.

func (*Bot) VerifyChat

func (b *Bot) VerifyChat(chat *Chat, level VerificationLevel, requirements *VerificationRequirements) error

VerifyChat verifies a chat with the specified level and requirements.

func (*Bot) VerifyUser

func (b *Bot) VerifyUser(user Recipient, level VerificationLevel, requirements *VerificationRequirements) error

VerifyUser verifies a user with the specified level and requirements.

func (*Bot) Webhook

func (b *Bot) Webhook() (*Webhook, error)

Webhook returns the current webhook status.

type BotInfo

type BotInfo struct {
	Name             string `json:"name,omitempty"`
	Description      string `json:"description,omitempty"`
	ShortDescription string `json:"short_description,omitempty"`
}

BotInfo represents a single object of BotName, BotDescription, BotShortDescription instances.

type Btn

type Btn struct {
	Unique            string          `json:"unique,omitempty"`
	Text              string          `json:"text,omitempty"`
	IconCustomEmojiID string          `json:"icon_custom_emoji_id,omitempty"`
	Style             ButtonStyle     `json:"style,omitempty"`
	URL               string          `json:"url,omitempty"`
	Data              string          `json:"callback_data,omitempty"`
	InlineQuery       string          `json:"switch_inline_query,omitempty"`
	InlineQueryChat   string          `json:"switch_inline_query_current_chat,omitempty"`
	Login             *Login          `json:"login_url,omitempty"`
	WebApp            *WebApp         `json:"web_app,omitempty"`
	Contact           bool            `json:"request_contact,omitempty"`
	Location          bool            `json:"request_location,omitempty"`
	Poll              PollType        `json:"request_poll,omitempty"`
	User              *ReplyRecipient `json:"request_user,omitempty"`
	Chat              *ReplyRecipient `json:"request_chat,omitempty"`
	CopyText          *CopyTextButton `json:"copy_text,omitempty"`
}

Btn is a constructor button, which will later become either a reply, or an inline button.

func (*Btn) CallbackUnique

func (t *Btn) CallbackUnique() string

CallbackUnique implements CallbackEndpoint.

func (Btn) Inline

func (b Btn) Inline() *InlineButton

func (Btn) Reply

func (b Btn) Reply() *ReplyButton

type BtnKey

type BtnKey string

BtnKey is the stable identifier ("unique") of an inline button. Declare one constant per button and use it both to build keyboards and to register the callback handler, so the two can never drift apart:

const Balance tbb.BtnKey = "balance"

kb.Inline(Balance.AsRow(ctx.GetL8dBtn("btn.balance")))
app.Callback(Balance, h.Balance)

The key must match [-\w]+ (letters, digits, '_' and '-') and, together with the data, fit in Telegram's 64-byte callback_data limit.

const LanguageBtn BtnKey = "tbbLang"

LanguageBtn is the built-in button of the language picker. Its data is the language code.

func (BtnKey) AsRow

func (k BtnKey) AsRow(text string, data ...string) Row

AsRow returns a single-button row.

func (BtnKey) Build

func (k BtnKey) Build(text string, data ...string) Btn

Build returns an inline button with the given text. data values are joined with "|" and can be read back in the handler with ctx.Args().

func (BtnKey) Endpoint

func (k BtnKey) Endpoint() string

Endpoint returns the "\f"-prefixed form used as a Bot.Handle endpoint.

func (BtnKey) String

func (k BtnKey) String() string

String returns the bare key.

type BusinessConnection

type BusinessConnection struct {
	// Unique identifier of the business connection
	ID string `json:"id"`

	// Business account user that created the business connection
	Sender *User `json:"user"`

	// Identifier of a private chat with the user who created the business connection. This
	// number may have more than 32 significant bits and some programming languages may
	// have difficulty/silent defects in interpreting it. But it has at most 52 significant bits,
	// so a 64-bit integer or double-precision float type are safe for storing this identifier.
	UserChatID int64 `json:"user_chat_id"`

	// Unixtime, use BusinessConnection.Time() to get time.Time.
	Unixtime int64 `json:"date"`

	// True, if the bot can act on behalf of the business account in chats that were active in the last 24 hours
	CanReply bool `json:"can_reply"`

	// True, if the connection is active
	Enabled bool `json:"is_enabled"`
}

func (*BusinessConnection) Time

func (b *BusinessConnection) Time() time.Time

Time returns the moment of business connection creation in local time.

type BusinessIntro

type BusinessIntro struct {
	// (Optional)
	// Title text of the business intro
	Title string `json:"title"`

	// Message text of the business intro
	Message string `json:"message"`

	// Sticker of the business intro
	Sticker *Sticker `json:"sticker"`
}

type BusinessLocation

type BusinessLocation struct {
	// Address of the business
	Address string `json:"address"`

	// (Optional) Location of the business
	Location *Location `json:"location"`
}

type BusinessMessagesDeleted

type BusinessMessagesDeleted struct {
	// Unique identifier of the business connection
	BusinessConnectionID string `json:"business_connection_id"`

	// Information about a chat in the business account. The bot
	// may not have access to the chat or the corresponding user.
	Chat *Chat `json:"chat"`

	// The list of identifiers of deleted messages in the chat of the business account
	MessageIDs []int `json:"message_ids"`
}

type BusinessOpeningHours

type BusinessOpeningHours struct {
	// Unique name of the time zone for which the opening hours are defined
	Timezone string `json:"time_zone_name"`

	// List of time intervals describing business opening hours
	OpeningHours []BusinessOpeningHoursInterval `json:"opening_hours"`
}

type BusinessOpeningHoursInterval

type BusinessOpeningHoursInterval struct {
	// The minute's sequence number in a week, starting on Monday,
	// marking the start of the time interval during which the business
	// is open; 0 - 7 * 24 * 60
	OpeningMinute int `json:"opening_minute"`

	// The minute's sequence number in a week, starting on Monday,
	// marking the start of the time interval during which the business
	// is open; 0 - 7 * 24 * 60
	ClosingMinute int `json:"closing_minute"`
}

type ButtonStyle

type ButtonStyle string

ButtonStyle is the visual style of a keyboard button. Bot API 9.4.

const (
	ButtonStylePrimary ButtonStyle = "primary"
	ButtonStyleSuccess ButtonStyle = "success"
	ButtonStyleDanger  ButtonStyle = "danger"
)

type Callback

type Callback struct {
	ID string `json:"id"`

	// For message sent to channels, Sender may be empty
	Sender *User `json:"from"`

	// Message will be set if the button that originated the query
	// was attached to a message sent by a bot.
	Message *Message `json:"message"`

	// MessageID will be set if the button was attached to a message
	// sent via the bot in inline mode.
	MessageID string `json:"inline_message_id"`

	// Data associated with the callback button. Be aware that
	// a bad client can send arbitrary data in this field.
	Data string `json:"data"`

	// ChatInstance is a global identifier, uniquely corresponding to
	// the chat to which the message with the callback button was sent.
	ChatInstance string `json:"chat_instance"`

	// GameShortName is a unique identifier of the game for which a URL
	// is requested from the bot when a user presses the Play button of
	// that game. GameShortName may be empty
	GameShortName string `json:"game_short_name"`

	// Unique is the unique of the button that fired the callback. When Data
	// has the "\f<unique>|<payload>" form that buttons with a Unique produce,
	// it is split before any handler runs (including OnCallback): Unique
	// gets the unique, Data keeps only the payload and RawData the original.
	// Otherwise Unique is empty and Data is left as Telegram sent it.
	Unique string `json:"-"`

	// RawData is the callback data exactly as received, before splitting.
	RawData string `json:"-"`
}

Callback object represents a query from a callback button in an inline keyboard.

func (*Callback) IsInline

func (c *Callback) IsInline() bool

IsInline says whether message is an inline message.

func (*Callback) MessageSig

func (c *Callback) MessageSig() (string, int64)

MessageSig satisfies Editable interface.

type CallbackEndpoint

type CallbackEndpoint interface {
	CallbackUnique() string
}

CallbackEndpoint is an interface any element capable of responding to a callback `\f<unique>`.

type CallbackGame

type CallbackGame struct {
}

CallbackGame is a placeholder, currently holds no information

type CallbackResponse

type CallbackResponse struct {
	// The ID of the callback to which this is a response.
	//
	// Note: Telebot sets this field automatically!
	CallbackID string `json:"callback_query_id"`

	// Text of the notification. If not specified, nothing will be
	// shown to the user.
	Text string `json:"text,omitempty"`

	// (Optional) If true, an alert will be shown by the client instead
	// of a notification at the top of the chat screen. Defaults to false.
	ShowAlert bool `json:"show_alert,omitempty"`

	// (Optional) URL that will be opened by the user's client.
	// If you have created a Game and accepted the conditions via
	// @BotFather, specify the URL that opens your game.
	//
	// Note: this will only work if the query comes from a game
	// callback button. Otherwise, you may use deep-linking:
	// https://telegram.me/your_bot?start=XXXX
	URL string `json:"url,omitempty"`
}

CallbackResponse builds a response to a Callback query.

type Chat

type Chat struct {
	ID int64 `json:"id"`

	// See ChatType and consts.
	Type ChatType `json:"type"`

	// Won't be there for ChatPrivate.
	Title string `json:"title"`

	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Username  string `json:"username"`

	// Returns only in getChat
	Bio                            string               `json:"bio,omitempty"`
	Photo                          *ChatPhoto           `json:"photo,omitempty"`
	Description                    string               `json:"description,omitempty"`
	InviteLink                     string               `json:"invite_link,omitempty"`
	PinnedMessage                  *Message             `json:"pinned_message,omitempty"`
	Permissions                    *Rights              `json:"permissions,omitempty"`
	Reactions                      []Reaction           `json:"available_reactions"`
	SlowMode                       int                  `json:"slow_mode_delay,omitempty"`
	StickerSet                     string               `json:"sticker_set_name,omitempty"`
	CanSetStickerSet               bool                 `json:"can_set_sticker_set,omitempty"`
	CanSendPaidMedia               bool                 `json:"can_send_paid_media"`
	CustomEmojiStickerSet          string               `json:"custom_emoji_sticker_set_name"`
	LinkedChatID                   int64                `json:"linked_chat_id,omitempty"`
	ChatLocation                   *ChatLocation        `json:"location,omitempty"`
	Private                        bool                 `json:"has_private_forwards,omitempty"`
	Protected                      bool                 `json:"has_protected_content,omitempty"`
	NoVoiceAndVideo                bool                 `json:"has_restricted_voice_and_video_messages"`
	HasHiddenMembers               bool                 `json:"has_hidden_members,omitempty"`
	AggressiveAntiSpam             bool                 `json:"has_aggressive_anti_spam_enabled,omitempty"`
	IsForum                        bool                 `json:"is_forum"`
	StatusCustomEmojiID            string               `json:"emoji_status_custom_emoji_id"`
	EmojiExpirationUnixtime        int64                `json:"emoji_status_expiration_date"`
	BackgroundCustomEmojiID        string               `json:"background_custom_emoji_id"`
	AccentColorID                  int                  `json:"accent_color_id"`
	ProfileAccentColorID           int                  `json:"profile_accent_color_id"`
	ProfileBackgroundCustomEmojiID string               `json:"profile_background_custom_emoji_id"`
	HasVisibleHistory              bool                 `json:"has_visible_history"`
	UnrestrictBoosts               int                  `json:"unrestrict_boost_count"`
	MaxReactions                   int                  `json:"max_reaction_count"`
	Birthdate                      Birthdate            `json:"birthdate,omitempty"`
	PersonalChat                   *Chat                `json:"personal_chat,omitempty"`
	BusinessIntro                  BusinessIntro        `json:"business_intro,omitempty"`
	BusinessLocation               BusinessLocation     `json:"business_location,omitempty"`
	BusinessOpeningHours           BusinessOpeningHours `json:"business_opening_hours,omitempty"`
}

Chat object represents a Telegram user, bot, group or a channel.

func (*Chat) Recipient

func (c *Chat) Recipient() string

Recipient returns chat ID (see Recipient interface).

func (*Chat) Time

func (c *Chat) Time() time.Time

Time returns the moment of the emoji status expiration.

type ChatAction

type ChatAction string

ChatAction is a client-side status indicating bot activity.

const (
	Typing            ChatAction = "typing"
	UploadingPhoto    ChatAction = "upload_photo"
	UploadingVideo    ChatAction = "upload_video"
	UploadingAudio    ChatAction = "upload_audio"
	UploadingDocument ChatAction = "upload_document"
	UploadingVNote    ChatAction = "upload_video_note"
	RecordingVideo    ChatAction = "record_video"
	RecordingAudio    ChatAction = "record_audio"
	RecordingVNote    ChatAction = "record_video_note"
	FindingLocation   ChatAction = "find_location"
	ChoosingSticker   ChatAction = "choose_sticker"
)

type ChatBackground

type ChatBackground struct {
	// Type of the background
	Type BackgroundType `json:"type"`
}

type ChatFullInfo

type ChatFullInfo struct {
	ID int64 `json:"id"`

	// See ChatType and consts.
	Type ChatType `json:"type"`

	// Won't be there for ChatPrivate.
	Title string `json:"title"`

	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Username  string `json:"username"`

	// (Optional) Bio of the chat
	Bio string `json:"bio,omitempty"`

	// (Optional) Chat photo
	Photo *ChatPhoto `json:"photo,omitempty"`

	// (Optional) Description of the chat
	Description string `json:"description,omitempty"`

	// (Optional) Invite link for the chat
	InviteLink string `json:"invite_link,omitempty"`

	// (Optional) Pinned message
	PinnedMessage *Message `json:"pinned_message,omitempty"`

	// (Optional) Default chat member permissions
	Permissions *Rights `json:"permissions,omitempty"`

	// (Optional) The minimum allowed delay between consecutive messages sent by each user
	SlowMode int `json:"slow_mode_delay,omitempty"`

	// (Optional) The time after which all messages sent to the chat will be automatically deleted
	MessageAutoDeleteTime int `json:"message_auto_delete_time,omitempty"`

	// (Optional) True, if new members of the chat can be anonymous
	HasAnonymousMembers bool `json:"has_anonymous_members,omitempty"`

	// (Optional) True, if reactions are available in the chat
	HasAggressiveAntiSpam bool `json:"has_aggressive_anti_spam_enabled,omitempty"`

	// (Optional) True, if anti-spam checks are enabled in the chat
	HasHiddenMembers bool `json:"has_hidden_members,omitempty"`

	// (Optional) True, if the chat has protected content
	HasProtectedContent bool `json:"has_protected_content,omitempty"`

	// (Optional) True, if non-administrators can only get the list of bots and administrators in the chat
	HasVisibleHistory bool `json:"has_visible_history,omitempty"`

	// (Optional) True, if messages from the chat can't be forwarded to other chats
	NoMessagesToOther bool `json:"has_restricted_voice_and_video_messages,omitempty"`

	// (Optional) For supergroups, name of group sticker set
	StickerSetName string `json:"sticker_set_name,omitempty"`

	// (Optional) True, if the bot can change the group sticker set
	CanSetStickerSet bool `json:"can_set_sticker_set,omitempty"`

	// (Optional) Custom emoji sticker set name
	CustomEmojiStickerSet string `json:"custom_emoji_sticker_set_name,omitempty"`

	// (Optional) Chat location
	Location *ChatLocation `json:"location,omitempty"`

	// (Optional) Identifier of the linked chat
	LinkedChatID int64 `json:"linked_chat_id,omitempty"`

	// Bot API 8.3: True, if the chat can be gifted with Telegram Stars gifts
	CanSendGift bool `json:"can_send_gift"`

	// Bot API 9.4: For private chats, the first audio added to the profile of the user.
	FirstProfileAudio *Audio `json:"first_profile_audio,omitempty"`
}

ChatFullInfo object contains full information about a chat.

type ChatID

type ChatID int64

ChatID represents a chat or an user integer ID, which can be used as recipient in bot methods. It is very useful in cases where you have special group IDs, for example in your config, and don't want to wrap it into *tele.Chat every time you send messages.

Example:

group := tele.ChatID(-100756389456)
b.Send(group, "Hello!")

type Config struct {
	AdminGroup tele.ChatID `json:"admin_group"`
}
b.Send(conf.AdminGroup, "Hello!")

func (ChatID) Recipient

func (i ChatID) Recipient() string

Recipient returns chat ID (see Recipient interface).

type ChatInviteLink struct {
	// The invite link.
	InviteLink string `json:"invite_link"`

	// Invite link name.
	Name string `json:"name"`

	// The creator of the link.
	Creator *User `json:"creator"`

	// If the link is primary.
	IsPrimary bool `json:"is_primary"`

	// If the link is revoked.
	IsRevoked bool `json:"is_revoked"`

	// (Optional) Point in time when the link will expire,
	// use ExpireDate() to get time.Time.
	ExpireUnixtime int64 `json:"expire_date,omitempty"`

	// (Optional) Maximum number of users that can be members of
	// the chat simultaneously.
	MemberLimit int `json:"member_limit,omitempty"`

	// (Optional) True, if users joining the chat via the link need to
	// be approved by chat administrators. If True, member_limit can't be specified.
	JoinRequest bool `json:"creates_join_request"`

	// (Optional) Number of pending join requests created using this link.
	PendingCount int `json:"pending_join_request_count"`
}

ChatInviteLink object represents an invite for a chat.

func (*ChatInviteLink) ExpireDate

func (c *ChatInviteLink) ExpireDate() time.Time

ExpireDate returns the moment of the link expiration in local time.

type ChatJoinRequest

type ChatJoinRequest struct {
	// Chat to which the request was sent.
	Chat *Chat `json:"chat"`

	// Sender is the user that sent the join request.
	Sender *User `json:"from"`

	// UserChatID is an ID of a private chat with the user
	// who sent the join request. The bot can use this ID
	// for 5 minutes to send messages until the join request
	// is processed, assuming no other administrator contacted the user.
	UserChatID int64 `json:"user_chat_id"`

	// Unixtime, use ChatJoinRequest.Time() to get time.Time.
	Unixtime int64 `json:"date"`

	// Bio of the user, optional.
	Bio string `json:"bio"`

	// InviteLink is the chat invite link that was used by
	//the user to send the join request, optional.
	InviteLink *ChatInviteLink `json:"invite_link"`
}

ChatJoinRequest represents a join request sent to a chat.

func (ChatJoinRequest) Time

func (r ChatJoinRequest) Time() time.Time

Time returns the moment of chat join request sending in local time.

type ChatLocation

type ChatLocation struct {
	Location Location `json:"location,omitempty"`
	Address  string   `json:"address,omitempty"`
}

ChatLocation represents a location to which a chat is connected.

type ChatMember

type ChatMember struct {
	Rights

	User      *User        `json:"user"`
	Role      MemberStatus `json:"status"`
	Title     string       `json:"custom_title"`
	Anonymous bool         `json:"is_anonymous"`
	Member    bool         `json:"is_member,omitempty"`

	// Date when restrictions will be lifted for the user, unix time.
	//
	// If user is restricted for more than 366 days or less than
	// 30 seconds from the current time, they are considered to be
	// restricted forever.
	//
	// Use tele.Forever().
	//
	RestrictedUntil int64 `json:"until_date,omitempty"`

	JoinToSend    string `json:"join_to_send_messages"`
	JoinByRequest string `json:"join_by_request"`

	// Bot API 9.5: (Optional) Tag of the member; for regular and restricted members only.
	Tag string `json:"tag,omitempty"`
}

ChatMember object represents information about a single chat member.

type ChatMemberUpdate

type ChatMemberUpdate struct {
	// Chat where the user belongs to.
	Chat *Chat `json:"chat"`

	// Sender which user the action was triggered.
	Sender *User `json:"from"`

	// Unixtime, use Date() to get time.Time.
	Unixtime int64 `json:"date"`

	// Previous information about the chat member.
	OldChatMember *ChatMember `json:"old_chat_member"`

	// New information about the chat member.
	NewChatMember *ChatMember `json:"new_chat_member"`

	// (Optional) InviteLink which was used by the user to
	// join the chat; for joining by invite link events only.
	InviteLink *ChatInviteLink `json:"invite_link"`

	// (Optional) True, if the user joined the chat after sending
	// a direct join request without using an invite link and being
	// approved by an administrator
	ViaJoinRequest bool `json:"via_join_request"`

	// (Optional) True, if the user joined the chat via a chat folder invite link.
	ViaFolderLink bool `json:"via_chat_folder_invite_link"`
}

ChatMemberUpdate object represents changes in the status of a chat member.

func (*ChatMemberUpdate) Time

func (c *ChatMemberUpdate) Time() time.Time

Time returns the moment of the change in local time.

type ChatOwnerChanged

type ChatOwnerChanged struct {
	// The new owner of the chat.
	NewOwner *User `json:"new_owner"`
}

ChatOwnerChanged describes a service message about an ownership change in the chat.

type ChatOwnerLeft

type ChatOwnerLeft struct {
	// (Optional) The user who will become the new owner of the chat
	// if the previous owner does not return to the chat.
	NewOwner *User `json:"new_owner,omitempty"`
}

ChatOwnerLeft describes a service message about the chat owner leaving the chat.

type ChatPhoto

type ChatPhoto struct {
	// File identifiers of small (160x160) chat photo
	SmallFileID   string `json:"small_file_id"`
	SmallUniqueID string `json:"small_file_unique_id"`

	// File identifiers of big (640x640) chat photo
	BigFileID   string `json:"big_file_id"`
	BigUniqueID string `json:"big_file_unique_id"`
}

ChatPhoto object represents a chat photo.

type ChatType

type ChatType string

ChatType represents one of the possible chat types.

const (
	ChatPrivate        ChatType = "private"
	ChatGroup          ChatType = "group"
	ChatSuperGroup     ChatType = "supergroup"
	ChatChannel        ChatType = "channel"
	ChatChannelPrivate ChatType = "privatechannel"
)

type Command

type Command struct {
	// Text is a text of the command, 1-32 characters.
	// Can contain only lowercase English letters, digits and underscores.
	Text string `json:"command"`

	// Description of the command, 3-256 characters.
	Description string `json:"description"`
}

Command represents a bot command.

type CommandParams

type CommandParams struct {
	Commands     []Command     `json:"commands,omitempty"`
	Scope        *CommandScope `json:"scope,omitempty"`
	LanguageCode string        `json:"language_code,omitempty"`
}

CommandParams controls parameters for commands-related methods (setMyCommands, deleteMyCommands and getMyCommands).

type CommandScope

type CommandScope struct {
	Type   CommandScopeType `json:"type"`
	ChatID int64            `json:"chat_id,omitempty"`
	UserID int64            `json:"user_id,omitempty"`
}

CommandScope object represents a scope to which bot commands are applied.

type CommandScopeType

type CommandScopeType = string
const (
	CommandScopeDefault         CommandScopeType = "default"
	CommandScopeAllPrivateChats CommandScopeType = "all_private_chats"
	CommandScopeAllGroupChats   CommandScopeType = "all_group_chats"
	CommandScopeAllChatAdmin    CommandScopeType = "all_chat_administrators"
	CommandScopeChat            CommandScopeType = "chat"
	CommandScopeChatAdmin       CommandScopeType = "chat_administrators"
	CommandScopeChatMember      CommandScopeType = "chat_member"
)

type Config

type Config struct {
	Telegram TelegramConfig `json:"telegram"`
	DB       DBConfig       `json:"db"`

	// DefaultLanguage is used for chats that haven't chosen a language and
	// for keys missing in the chosen one.
	DefaultLanguage string `json:"default_language" default:"en"`
}

Config is the framework configuration. It can be embedded in an app's own config struct and filled by LoadConfig.

type Contact

type Contact struct {
	PhoneNumber string `json:"phone_number"`
	FirstName   string `json:"first_name"`

	// (Optional)
	LastName string `json:"last_name"`
	UserID   int64  `json:"user_id,omitempty"`
	VCard    string `json:"vcard,omitempty"`
}

Contact object represents a contact to Telegram user.

type ContactResult

type ContactResult struct {
	ResultBase

	// Contact's phone number.
	PhoneNumber string `json:"phone_number"`

	// Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes.
	VCard string `json:"vcard,omitempty"`

	// Contact's first name.
	FirstName string `json:"first_name"`

	// Optional. Contact's last name.
	LastName string `json:"last_name,omitempty"`

	// Optional. URL of the thumbnail for the result.
	ThumbURL string `json:"thumbnail_url,omitempty"`

	// Optional. Width of the thumbnail for the result.
	ThumbWidth int `json:"thumbnail_width,omitempty"`

	// Optional. Height of the thumbnail for the result.
	ThumbHeight int `json:"thumbnail_height,omitempty"`
}

ContactResult represents a contact with a phone number.

type Context

type Context interface {
	// Bot returns the bot instance.
	Bot() API

	// Update returns the original update.
	Update() Update

	// Message returns stored message if such presented.
	Message() *Message

	// Callback returns stored callback if such presented.
	Callback() *Callback

	// Query returns stored query if such presented.
	Query() *Query

	// InlineResult returns stored inline result if such presented.
	InlineResult() *InlineResult

	// ShippingQuery returns stored shipping query if such presented.
	ShippingQuery() *ShippingQuery

	// PreCheckoutQuery returns stored pre checkout query if such presented.
	PreCheckoutQuery() *PreCheckoutQuery

	// Payment returns payment instance.
	Payment() *Payment

	// Poll returns stored poll if such presented.
	Poll() *Poll

	// PollAnswer returns stored poll answer if such presented.
	PollAnswer() *PollAnswer

	// ChatMember returns chat member changes.
	ChatMember() *ChatMemberUpdate

	// ChatJoinRequest returns the chat join request.
	ChatJoinRequest() *ChatJoinRequest

	// Migration returns both migration from and to chat IDs.
	Migration() (int64, int64)

	// Topic returns the topic changes.
	Topic() *Topic

	// Boost returns the boost instance.
	Boost() *BoostUpdated

	// BoostRemoved returns the boost removed from a chat instance.
	BoostRemoved() *BoostRemoved

	// PurchasedPaidMedia returns the purchased paid media instance.
	PurchasedPaidMedia() *PaidMediaPurchased

	// Sender returns the current recipient, depending on the context type.
	// Returns nil if user is not presented.
	Sender() *User

	// Chat returns the current chat, depending on the context type.
	// Returns nil if chat is not presented.
	Chat() *Chat
	// Recipient combines both Sender and Chat functions. If there is no user
	// the chat will be returned. The native context cannot be without sender,
	// but it is useful in the case when the context created intentionally
	// by the NewContext constructor and have only Chat field inside.
	Recipient() Recipient

	// Text returns the message text, depending on the context type.
	// In the case when no related data presented, returns an empty string.
	Text() string

	// ThreadID returns the current message thread ID.
	ThreadID() int

	// Entities returns the message entities, whether it's media caption's or the text's.
	// In the case when no entities presented, returns a nil.
	Entities() Entities

	// Data returns the current data, depending on the context type.
	// If the context contains command, returns its arguments string.
	// If the context contains payment, returns its payload.
	// In the case when no related data presented, returns an empty string.
	Data() string

	// Args returns a raw slice of command or callback arguments as strings.
	// The message arguments split by space, while the callback's ones by a "|" symbol.
	Args() []string

	// Send sends a message to the current recipient.
	// See Send from bot.go.
	Send(what interface{}, opts ...interface{}) error

	// SendAlbum sends an album to the current recipient.
	// See SendAlbum from bot.go.
	SendAlbum(a Album, opts ...interface{}) error

	// Reply replies to the current message.
	// See Reply from bot.go.
	Reply(what interface{}, opts ...interface{}) error

	// Forward forwards the given message to the current recipient.
	// See Forward from bot.go.
	Forward(msg Editable, opts ...interface{}) error

	// ForwardTo forwards the current message to the given recipient.
	// See Forward from bot.go
	ForwardTo(to Recipient, opts ...interface{}) error

	// Edit edits the current message.
	// See Edit from bot.go.
	Edit(what interface{}, opts ...interface{}) error

	// EditCaption edits the caption of the current message.
	// See EditCaption from bot.go.
	EditCaption(caption string, opts ...interface{}) error

	// EditOrSend edits the current message if the update is callback,
	// otherwise the content is sent to the chat as a separate message.
	EditOrSend(what interface{}, opts ...interface{}) error

	// EditOrReply edits the current message if the update is callback,
	// otherwise the content is replied as a separate message.
	EditOrReply(what interface{}, opts ...interface{}) error

	// Delete removes the current message.
	// See Delete from bot.go.
	Delete() error

	// DeleteAfter waits for the duration to elapse and then removes the
	// message. It handles an error automatically using b.OnError callback.
	// It returns a Timer that can be used to cancel the call using its Stop method.
	DeleteAfter(d time.Duration) *time.Timer

	// Notify updates the chat action for the current recipient.
	// See Notify from bot.go.
	Notify(action ChatAction) error

	// Ship replies to the current shipping query.
	// See Ship from bot.go.
	Ship(what ...interface{}) error

	// Accept finalizes the current deal.
	// See Accept from bot.go.
	Accept(errorMessage ...string) error

	// Answer sends a response to the current inline query.
	// See Answer from bot.go.
	Answer(resp *QueryResponse) error

	// AnswerGuest sends a response to the current guest message.
	// See AnswerGuest from guest.go.
	AnswerGuest(result Result) error

	// Respond sends a response for the current callback query.
	// See Respond from bot.go.
	Respond(resp ...*CallbackResponse) error

	// RespondText sends a popup response for the current callback query.
	RespondText(text string) error

	// RespondAlert sends an alert response for the current callback query.
	RespondAlert(text string) error

	// Get retrieves data from the context.
	Get(key string) interface{}

	// Set saves data in the context.
	Set(key string, val interface{})
}

Context wraps an update and represents the context of current event.

func NewContext

func NewContext(b API, u Update) Context

NewContext returns a new native context object, field by the passed update.

type CopyTextButton

type CopyTextButton struct {
	Text string `json:"text"`
}

CopyTextButton represents an inline keyboard button that copies specified text to the clipboard when pressed.

type Ctx

type Ctx[T any] interface {
	Context

	// Session returns the chat's session. Changes made during the handler
	// are persisted automatically when it returns.
	Session() *Session[T]
	// State returns the app-specific part of the session.
	State() *T

	// ID returns the chat ID.
	ID() int64
	// UserID returns the account ID (accounts.id) of the user, or 0 for
	// updates that have no linked account (e.g. group chats).
	UserID() int64

	GetScene() Scene
	SetScene(scene Scene)
	GetCurrentQuestion() Question
	SetNextQuestion(q Question)
	IncQuestion()
	Enter(scene Scene, q Question)
	ResetScene()

	// GetLanguage returns the chat's language ("" until one is chosen;
	// translations then use the fallback language).
	GetLanguage() string
	// SetLanguage changes the chat's language and stores it on the
	// account as well.
	SetLanguage(lang string) error

	// Account returns the stored account of the user who sent the update.
	Account() (*Account, error)

	// GetL8d returns the translation of key in the chat's language, with
	// {placeholders} filled from kv pairs, escaped for the bot's parse
	// mode: the template's own markup is kept and the values are escaped
	// fully, so user input can be passed safely.
	GetL8d(key string, kv ...string) string
	// GetL8dRaw is GetL8d without any escaping. Use it for button labels,
	// callback answers, or text sent without a parse mode.
	GetL8dRaw(key string, kv ...string) string
	// GetL8dBtn is an alias of GetL8dRaw, for button labels.
	GetL8dBtn(key string, kv ...string) string
	// SendL8d sends the translation of key. opts are passed to Send.
	SendL8d(key string, opts ...any) error
	// RespondL8d answers a callback query with the translation of key
	// shown as a toast.
	RespondL8d(key string, kv ...string) error

	// CleanSend strips the inline keyboard from the previous keyboard
	// message, sends a new message and remembers it as the current one.
	CleanSend(what any, opts ...any) error
	// CleanSendDelete is CleanSend, except the previous keyboard message
	// is deleted entirely (falling back to stripping its keyboard).
	CleanSendDelete(what any, opts ...any) error
	// CleanEdit edits the previous keyboard message in place, so a single
	// "control panel" message morphs as the user navigates menus. It falls
	// back to CleanSendDelete when there is nothing to edit or the edit is
	// impossible (different message type, too old, deleted).
	CleanEdit(what any, opts ...any) error

	// I18n returns the app's translation registry.
	I18n() *I18n
	// Logger returns the app's logger, annotated with the chat ID.
	Logger() *slog.Logger
}

Ctx is the context handlers receive. It is a telebot Context (so Send, Edit, Respond, Callback, Message… all work as usual) extended with the chat's session, localization and the "clean" keyboard helpers.

type Currency

type Currency struct {
	Code         string      `json:"code"`
	Title        string      `json:"title"`
	Symbol       string      `json:"symbol"`
	Native       string      `json:"native"`
	ThousandsSep string      `json:"thousands_sep"`
	DecimalSep   string      `json:"decimal_sep"`
	SymbolLeft   bool        `json:"symbol_left"`
	SpaceBetween bool        `json:"space_between"`
	Exp          int         `json:"exp"`
	MinAmount    interface{} `json:"min_amount"`
	MaxAmount    interface{} `json:"max_amount"`
}

Currency contains information about supported currency for payments.

func (Currency) FromTotal

func (c Currency) FromTotal(total int) float64

func (Currency) ToTotal

func (c Currency) ToTotal(total float64) int

type DBConfig

type DBConfig struct {
	// Driver is "sqlite" or "postgres". When empty it is inferred from the
	// DSN: postgres:// and postgresql:// URLs select Postgres, anything else
	// SQLite.
	Driver string `json:"driver"`

	// DSN is the connection string, e.g.
	//   file:data/bot.db?_pragma=busy_timeout(5000)
	//   postgres://user:pass@localhost:5432/bot?sslmode=disable
	DSN string `json:"dsn"`
}

DBConfig selects the database. Everything is optional: the zero value opens DefaultSQLiteDSN.

type Dice

type Dice struct {
	Type  DiceType `json:"emoji"`
	Value int      `json:"value"`
}

Dice object represents a dice with a random value from 1 to 6 for currently supported base emoji.

func (*Dice) Send

func (d *Dice) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers dice through bot b to recipient.

type DiceType

type DiceType string

DiceType defines dice types.

type Document

type Document struct {
	File

	// (Optional)
	Thumbnail            *Photo `json:"thumbnail,omitempty"`
	Caption              string `json:"caption,omitempty"`
	MIME                 string `json:"mime_type"`
	FileName             string `json:"file_name,omitempty"`
	DisableTypeDetection bool   `json:"disable_content_type_detection,omitempty"`
}

Document object represents a general file (as opposed to Photo or Audio). Telegram users can send files of any type of up to 1.5 GB in size.

func (*Document) InputMedia

func (d *Document) InputMedia() InputMedia

func (*Document) MediaFile

func (d *Document) MediaFile() *File

func (*Document) MediaType

func (d *Document) MediaType() string

func (*Document) Send

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

Send delivers media through bot b to recipient.

type DocumentResult

type DocumentResult struct {
	ResultBase

	// Title for the result.
	Title string `json:"title"`

	// A valid URL for the file
	URL string `json:"document_url"`

	// Mime type of the content of the file, either “application/pdf” or
	// “application/zip”.
	MIME string `json:"mime_type"`

	// Optional. Caption of the document to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. URL of the thumbnail (jpeg only) for the file.
	ThumbURL string `json:"thumbnail_url,omitempty"`

	// Optional. Width of the thumbnail for the result.
	ThumbWidth int `json:"thumbnail_width,omitempty"`

	// Optional. Height of the thumbnail for the result.
	ThumbHeight int `json:"thumbnail_height,omitempty"`

	// If Cache != "", it'll be used instead
	Cache string `json:"document_file_id,omitempty"`
}

DocumentResult represents a link to a file.

type Editable

type Editable interface {
	// MessageSig is a "message signature".
	//
	// For inline messages, return chatID = 0.
	MessageSig() (messageID string, chatID int64)
}

Editable is an interface for all objects that provide "message signature", a pair of 32-bit message ID and 64-bit chat ID, both required for edit operations.

Use case: DB model struct for messages to-be edited with, say two columns: msg_id,chat_id could easily implement MessageSig() making instances of stored messages editable.

type Entities

type Entities []MessageEntity

Entities are used to set message's text entities as a send option.

type EntityType

type EntityType string

EntityType is a MessageEntity type.

const (
	EntityMention       EntityType = "mention"
	EntityTMention      EntityType = "text_mention"
	EntityHashtag       EntityType = "hashtag"
	EntityCashtag       EntityType = "cashtag"
	EntityCommand       EntityType = "bot_command"
	EntityURL           EntityType = "url"
	EntityEmail         EntityType = "email"
	EntityPhone         EntityType = "phone_number"
	EntityBold          EntityType = "bold"
	EntityItalic        EntityType = "italic"
	EntityUnderline     EntityType = "underline"
	EntityStrikethrough EntityType = "strikethrough"
	EntityCode          EntityType = "code"
	EntityCodeBlock     EntityType = "pre"
	EntityTextLink      EntityType = "text_link"
	EntitySpoiler       EntityType = "spoiler"
	EntityCustomEmoji   EntityType = "custom_emoji"
	EntityBlockquote    EntityType = "blockquote"
	EntityEBlockquote   EntityType = "expandable_blockquote"
	EntityDateTime      EntityType = "date_time"
)

type Error

type Error struct {
	Code        int
	Description string
	Message     string
}

func NewError

func NewError(code int, msgs ...string) *Error

NewError returns new Error instance with given description. First element of msgs is Description. The second is optional Message.

func (*Error) Error

func (err *Error) Error() string

Error implements error interface.

type ExternalReply

type ExternalReply struct {
	// Origin of the message replied to by the given message.
	Origin *MessageOrigin `json:"origin"`

	// (Optional) Chat the original message belongs to.
	// Available only if the chat is a supergroup or a channel.
	Chat *Chat `json:"chat"`

	// (Optional) Unique message identifier inside the original chat.
	// Available only if the original chat is a supergroup or a channel.
	MessageID int `json:"message_id"`

	// (Optional) PreviewOptions used for link preview generation for the original message,
	// if it is a text message.
	PreviewOptions *PreviewOptions `json:"link_preview_options"`

	// (Optional) Message is an animation, information about the animation.
	Animation *Animation `json:"animation"`

	// (Optional) Message is an audio file, information about the file.
	Audio *Audio `json:"audio"`

	// (Optional) Message is a general file, information about the file.
	Document *Document `json:"document"`

	// (Optional) Message is a photo, available sizes of the photo.
	Photo []Photo `json:"photo"`

	// (Optional) Message is a sticker, information about the sticker.
	Sticker *Sticker `json:"sticker"`

	// (Optional) Message is a forwarded story.
	Story *Story `json:"story"`

	// (Optional) Message is a video, information about the video.
	Video *Video `json:"video"`

	// (Optional) Message is a video note, information about the video message.
	Note *VideoNote `json:"video_note"`

	// (Optional) Message is a voice message, information about the file.
	Voice *Voice `json:"voice"`

	// (Optional) Message is a shared contact, information about the contact.
	Contact *Contact `json:"contact"`

	// (Optional) Message is a dice with random value.
	Dice *Dice `json:"dice"`

	//( Optional) Message is a game, information about the game.
	Game *Game `json:"game"`

	// (Optional) Message is a venue, information about the venue.
	Venue *Venue `json:"venue"`

	// (Optional) Message is a native poll, information about the poll.
	Poll *Poll `json:"poll"`

	// (Optional) Message is a shared location, information about the location.
	Location *Location `json:"location"`

	// (Optional) Message is an invoice for a payment, information about the invoice.
	Invoice *Invoice `json:"invoice"`

	// (Optional) Message is a scheduled giveaway, information about the giveaway.
	Giveaway *Giveaway `json:"giveaway"`

	// (Optional) A giveaway with public winners was completed.
	GiveawayWinners *GiveawayWinners `json:"giveaway_winners"`

	// Message contains paid media; information about the paid media
	PaidMedia PaidMedias `json:"paid_media"`

	// (Optional) True, if the message media is covered by a spoiler animation.
	HasMediaSpoiler bool `json:"has_media_spoiler"`
}

ExternalReply contains information about a message that is being replied to, which may come from another chat or forum topic.

type File

type File struct {
	FileID   string `json:"file_id"`
	UniqueID string `json:"file_unique_id"`
	FileSize int64  `json:"file_size"`

	// FilePath is used for files on Telegram server.
	FilePath string `json:"file_path"`

	// FileLocal is used for files on local file system.
	FileLocal string `json:"file_local"`

	// FileURL is used for file on the internet.
	FileURL string `json:"file_url"`

	// FileReader is used for file backed with io.Reader.
	FileReader io.Reader `json:"-"`
	// contains filtered or unexported fields
}

File object represents any sort of file.

func FromDisk

func FromDisk(filename string) File

FromDisk constructs a new local (on-disk) file object.

Note, it returns File, not *File for a very good reason: in telebot, File is pretty much an embeddable struct, so upon uploading media you'll need to set embedded File with something. NewFile() returning File makes it a one-liner.

photo := &tele.Photo{File: tele.FromDisk("chicken.jpg")}

func FromReader

func FromReader(reader io.Reader) File

FromReader constructs a new file from io.Reader.

Note, it returns File, not *File for a very good reason: in telebot, File is pretty much an embeddable struct, so upon uploading media you'll need to set embedded File with something. NewFile() returning File makes it a one-liner.

photo := &tele.Photo{File: tele.FromReader(bytes.NewReader(...))}

func FromURL

func FromURL(url string) File

FromURL constructs a new file on provided HTTP URL.

Note, it returns File, not *File for a very good reason: in telebot, File is pretty much an embeddable struct, so upon uploading media you'll need to set embedded File with something. NewFile() returning File makes it a one-liner.

photo := &tele.Photo{File: tele.FromURL("https://site.com/picture.jpg")}

func (*File) InCloud

func (f *File) InCloud() bool

InCloud tells whether the file is present on Telegram servers.

func (*File) OnDisk

func (f *File) OnDisk() bool

OnDisk will return true if file is present on disk.

type FloodError

type FloodError struct {
	RetryAfter int
	// contains filtered or unexported fields
}

func (FloodError) Error

func (err FloodError) Error() string

Error implements error interface.

type Game

type Game struct {
	Name string `json:"game_short_name"`

	Title       string `json:"title"`
	Description string `json:"description"`
	Photo       *Photo `json:"photo"`

	// (Optional)
	Text      string          `json:"text"`
	Entities  []MessageEntity `json:"text_entities"`
	Animation *Animation      `json:"animation"`
}

Game object represents a game. Their short names acts as unique identifiers.

func (*Game) Send

func (g *Game) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers game through bot b to recipient.

type GameHighScore

type GameHighScore struct {
	User     *User `json:"user"`
	Position int   `json:"position"`

	Score  int  `json:"score"`
	Force  bool `json:"force"`
	NoEdit bool `json:"disable_edit_message"`
}

GameHighScore object represents one row of the high scores table for a game.

type GameResult

type GameResult struct {
	ResultBase

	// ShortName is a unique identifier of the game.
	ShortName string `json:"game_short_name"`
}

GameResult represents a game. Game is a content type supported by Telegram, which can be sent back to the user as a result for an inline query.

type GifResult

type GifResult struct {
	ResultBase

	// A valid URL for the GIF file. File size must not exceed 1MB.
	URL string `json:"gif_url"`

	// Optional. Width of the GIF.
	Width int `json:"gif_width,omitempty"`

	// Optional. Height of the GIF.
	Height int `json:"gif_height,omitempty"`

	// Optional. Duration of the GIF.
	Duration int `json:"gif_duration,omitempty"`

	// URL of the static thumbnail for the result (jpeg or gif).
	ThumbURL string `json:"thumbnail_url"`

	// Optional. MIME type of the thumbnail, must be one of
	// “image/jpeg”, “image/gif”, or “video/mp4”.
	ThumbMIME string `json:"thumbnail_mime_type,omitempty"`

	// Optional. Title for the result.
	Title string `json:"title,omitempty"`

	// Optional. Caption of the GIF file to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// If Cache != "", it'll be used instead
	Cache string `json:"gif_file_id,omitempty"`

	// (Optional) Pass True, if the caption must be shown above the message media
	CaptionAbove bool `json:"show_caption_above_media,omitempty"`
}

GifResult represents a link to an animated GIF file.

type Gift

type Gift struct {
	// Unique identifier of the gift
	ID string `json:"id"`

	// The sticker that represents the gift
	Sticker *Sticker `json:"sticker"`

	// The number of Telegram Stars that must be paid to send the sticker
	StarCount int `json:"star_count"`

	// (Optional) The number of Telegram Stars that must be paid to upgrade the gift to a unique one
	UpgradeStarCount int `json:"upgrade_star_count,omitempty"`

	// (Optional) The total number of the gifts of this type that can be sent; for limited gifts only
	TotalCount int `json:"total_count,omitempty"`

	// (Optional) The number of remaining gifts of this type that can be sent; for limited gifts only
	RemainingCount int `json:"remaining_count,omitempty"`
}

Gift represents a gift that can be sent by the bot.

type Gifts

type Gifts struct {
	// The list of gifts
	Gifts []Gift `json:"gifts"`
}

Gifts represents a list of gifts.

type Giveaway

type Giveaway struct {
	// The list of chats which the user must join to participate in the giveaway.
	Chats []Chat `json:"chats"`

	// Point in time (Unix timestamp) when winners of the giveaway will be selected.
	SelectionUnixtime int64 `json:"winners_selection_date"`

	// The number of users which are supposed to be selected as winners of the giveaway.
	WinnerCount int `json:"winner_count"`

	// (Optional) True, if only users who join the chats after the giveaway
	// started should be eligible to win.
	OnlyNewMembers bool `json:"only_new_members"`

	// (Optional) True, if the list of giveaway winners will be visible to everyone.
	HasPublicWinners bool `json:"has_public_winners"`

	// (Optional) Description of additional giveaway prize.
	PrizeDescription string `json:"prize_description"`

	// (Optional) A list of two-letter ISO 3166-1 alpha-2 country codes indicating
	// the countries from which eligible users for the giveaway must come.
	// If empty, then all users can participate in the giveaway. Users with a phone number
	// that was bought on Fragment can always participate in giveaways.
	CountryCodes []string `json:"country_codes"`

	// (Optional) The number of months the Telegram Premium subscription won from
	// the giveaway will be active for.
	PremiumMonthCount int `json:"premium_subscription_month_count"`

	// (Optional) The number of Telegram Stars to be split between giveaway winners;
	// for Telegram Star giveaways only.
	PrizeStarCount int `json:"prize_star_count,omitempty"`
}

Giveaway represents a message about a scheduled giveaway.

func (*Giveaway) SelectionDate

func (g *Giveaway) SelectionDate() time.Time

SelectionDate returns the moment of when winners of the giveaway were selected in local time.

type GiveawayCompleted

type GiveawayCompleted struct {
	// Number of winners in the giveaway.
	WinnerCount int `json:"winner_count"`

	// (Optional) Number of undistributed prizes.
	UnclaimedPrizes int `json:"unclaimed_prize_count"`

	// (Optional) Message with the giveaway that was completed, if it wasn't deleted.
	Message *Message `json:"giveaway_message"`

	// (Optional) True, if the giveaway is a Telegram Star giveaway.
	// Otherwise, currently, the giveaway is a Telegram Premium giveaway.
	IsStarGiveaway bool `json:"is_star_giveaway,omitempty"`
}

GiveawayCompleted represents a service message about the completion of a giveaway without public winners.

type GiveawayCreated

type GiveawayCreated struct {
	// (Optional) The number of Telegram Stars to be split between giveaway winners;
	// for Telegram Star giveaways only.
	PrizeStarCount int `json:"prize_star_count,omitempty"`
}

GiveawayCreated represents a service message about the creation of a scheduled giveaway.

type GiveawayWinners

type GiveawayWinners struct {
	// The chat that created the giveaway.
	Chat *Chat `json:"chat"`

	// Identifier of the message with the giveaway in the chat.
	MessageID int `json:"message_id"`

	// Point in time (Unix timestamp) when winners of the giveaway were selected.
	SelectionUnixtime int64 `json:"winners_selection_date"`

	// The number of users which are supposed to be selected as winners of the giveaway.
	WinnerCount int `json:"winner_count"`

	// List of up to 100 winners of the giveaway.
	Winners []User `json:"winners"`

	// (Optional) The number of other chats the user had to join in order
	// to be eligible for the giveaway.
	AdditionalChats int `json:"additional_chat_count"`

	// (Optional) The number of months the Telegram Premium subscription won from
	// the giveaway will be active for.
	PremiumMonthCount int `json:"premium_subscription_month_count"`

	// (Optional) Number of undistributed prizes.
	UnclaimedPrizes int `json:"unclaimed_prize_count"`

	// (Optional) True, if only users who had joined the chats after the giveaway started
	// were eligible to win.
	OnlyNewMembers bool `json:"only_new_members"`

	// (Optional) True, if the giveaway was canceled because the payment for it was refunded.
	Refunded bool `json:"was_refunded"`

	// (Optional) Description of additional giveaway prize.
	PrizeDescription string `json:"prize_description"`

	// (Optional) The number of Telegram Stars to be split between giveaway winners;
	// for Telegram Star giveaways only.
	PrizeStarCount int `json:"prize_star_count,omitempty"`
}

GiveawayWinners object represents a message about the completion of a giveaway with public winners.

func (*GiveawayWinners) SelectionDate

func (g *GiveawayWinners) SelectionDate() time.Time

SelectionDate returns the moment of when winners of the giveaway were selected in local time.

type Group

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

Group is a separated group of handlers, united by the general middleware.

func (*Group) Handle

func (g *Group) Handle(endpoint interface{}, h HandlerFunc, m ...MiddlewareFunc)

Handle adds endpoint handler to the bot, combining group's middleware with the optional given middleware.

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc)

Use adds middleware to the chain.

type GroupError

type GroupError struct {
	MigratedTo int64
	// contains filtered or unexported fields
}

func (GroupError) Error

func (err GroupError) Error() string

Error implements error interface.

type Handler

type Handler[T any] func(c Ctx[T]) error

Handler handles an update with the framework context.

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc represents a handler function, which is used to handle actual endpoints.

type I18n

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

I18n is a registry of translations keyed by language code. Lookups fall back to the default language when a key is missing in the requested one. It is safe for concurrent use.

func NewI18n

func NewI18n(fallback string) *I18n

NewI18n creates an empty registry. fallback is the language used when a key or a language is missing ("en" when empty).

func (*I18n) Fallback

func (i *I18n) Fallback() string

Fallback returns the fallback language code.

func (*I18n) Get

func (i *I18n) Get(lang, key string) string

Get returns the raw template of key in lang. When lang is empty or unknown, or the key is missing in it, the fallback language is tried. If the key cannot be found at all, "[missing: key]" is returned so the gap is visible in the chat instead of producing an empty message.

func (*I18n) Has

func (i *I18n) Has(code string) bool

Has reports whether a language is registered.

func (*I18n) Languages

func (i *I18n) Languages() []Language

Languages returns the registered languages in registration order.

func (*I18n) Register

func (i *I18n) Register(code, name string, t Translations)

Register adds (or replaces) the translations of a language. name is the display name used by the language picker; when empty, the LangNameKey entry of t is used, then the code itself. Languages keep their registration order.

func (*I18n) SetLogger

func (i *I18n) SetLogger(l *slog.Logger)

SetLogger sets the logger used to report missing keys.

func (*I18n) Texts

func (i *I18n) Texts(key string) []string

Texts returns every registered translation of key, one per language that defines it. It is used to match localized reply-keyboard buttons.

type InlineButton

type InlineButton struct {
	// Unique slagish name for this kind of button,
	// try to be as specific as possible.
	//
	// It will be used as a callback endpoint.
	Unique string `json:"unique,omitempty"`

	Text                  string             `json:"text"`
	IconCustomEmojiID     string             `json:"icon_custom_emoji_id,omitempty"`
	Style                 ButtonStyle        `json:"style,omitempty"`
	URL                   string             `json:"url,omitempty"`
	Data                  string             `json:"callback_data,omitempty"`
	InlineQuery           string             `json:"switch_inline_query,omitempty"`
	InlineQueryChat       string             `json:"switch_inline_query_current_chat"`
	InlineQueryChosenChat *SwitchInlineQuery `json:"switch_inline_query_chosen_chat,omitempty"`
	Login                 *Login             `json:"login_url,omitempty"`
	WebApp                *WebApp            `json:"web_app,omitempty"`
	CallbackGame          *CallbackGame      `json:"callback_game,omitempty"`
	Pay                   bool               `json:"pay,omitempty"`
	CopyText              *CopyTextButton    `json:"copy_text,omitempty"`
}

InlineButton represents a button displayed in the message.

func (*InlineButton) CallbackUnique

func (t *InlineButton) CallbackUnique() string

CallbackUnique returns InlineButton.Unique.

func (*InlineButton) MarshalJSON

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

MarshalJSON implements json.Marshaler interface. It needed to avoid InlineQueryChat and Login or WebApp fields conflict. If you have Login or WebApp field in your button, InlineQueryChat must be skipped.

func (*InlineButton) With

func (t *InlineButton) With(data string) *InlineButton

With returns a copy of the button with data.

type InlineResult

type InlineResult struct {
	Sender    *User     `json:"from"`
	Location  *Location `json:"location,omitempty"`
	ResultID  string    `json:"result_id"`
	Query     string    `json:"query"`
	MessageID string    `json:"inline_message_id"` // inline messages only!
}

InlineResult represents a result of an inline query that was chosen by the user and sent to their chat partner.

func (*InlineResult) MessageSig

func (ir *InlineResult) MessageSig() (string, int64)

MessageSig satisfies Editable interface.

type InputContactMessageContent

type InputContactMessageContent struct {
	// Contact's phone number.
	PhoneNumber string `json:"phone_number"`

	// Contact's first name.
	FirstName string `json:"first_name"`

	// Optional. Contact's last name.
	LastName string `json:"last_name,omitempty"`
}

InputContactMessageContent represents the content of a contact message to be sent as the result of an inline query.

func (*InputContactMessageContent) IsInputMessageContent

func (input *InputContactMessageContent) IsInputMessageContent() bool

type InputLocationMessageContent

type InputLocationMessageContent struct {
	Lat float32 `json:"latitude"`
	Lng float32 `json:"longitude"`
}

InputLocationMessageContent represents the content of a location message to be sent as the result of an inline query.

func (*InputLocationMessageContent) IsInputMessageContent

func (input *InputLocationMessageContent) IsInputMessageContent() bool

type InputMedia

type InputMedia struct {
	Type                 string   `json:"type"`
	Media                string   `json:"media"`
	Caption              string   `json:"caption"`
	Thumbnail            string   `json:"thumbnail,omitempty"`
	ParseMode            string   `json:"parse_mode,omitempty"`
	Entities             Entities `json:"caption_entities,omitempty"`
	Width                int      `json:"width,omitempty"`
	Height               int      `json:"height,omitempty"`
	Duration             int      `json:"duration,omitempty"`
	Title                string   `json:"title,omitempty"`
	Performer            string   `json:"performer,omitempty"`
	Streaming            bool     `json:"supports_streaming,omitempty"`
	DisableTypeDetection bool     `json:"disable_content_type_detection,omitempty"`
	CaptionAbove         bool     `json:"show_caption_above_media,omitempty"`
	HasSpoiler           bool     `json:"has_spoiler,omitempty"`

	// Bot API 8.3: (Optional) Cover frame of the video (for InputMediaVideo)
	Cover string `json:"cover,omitempty"`

	// Bot API 8.3: (Optional) Point in time (Unix timestamp) when the video starts (for InputMediaVideo)
	StartTimestamp int64 `json:"start_timestamp,omitempty"`
}

InputMedia represents a composite InputMedia struct that is used by Telebot in sending and editing media methods.

type InputMessageContent

type InputMessageContent interface {
	IsInputMessageContent() bool
}

InputMessageContent objects represent the content of a message to be sent as a result of an inline query.

type InputProfilePhoto

type InputProfilePhoto interface {
	// contains filtered or unexported methods
}

InputProfilePhoto describes a profile photo to set. Bot API 9.4. Implemented by *InputProfilePhotoStatic and *InputProfilePhotoAnimated.

type InputProfilePhotoAnimated

type InputProfilePhotoAnimated struct {
	File

	// (Optional) Timestamp in seconds of the frame that will be used
	// as the static profile photo. Defaults to 0.0.
	MainFrameTimestamp float64
}

InputProfilePhotoAnimated is an animated profile photo in the MPEG4 format.

type InputProfilePhotoStatic

type InputProfilePhotoStatic struct {
	File
}

InputProfilePhotoStatic is a static profile photo in the .JPG format.

type InputRichMessage

type InputRichMessage struct {
	// (Optional) Content described using Telegram's extended HTML formatting.
	HTML string `json:"html,omitempty"`

	// (Optional) Content described using Telegram's extended Markdown formatting.
	Markdown string `json:"markdown,omitempty"`

	// (Optional) Pass true to render the message right-to-left.
	IsRTL bool `json:"is_rtl,omitempty"`

	// (Optional) Pass true to skip automatic detection of URLs, email addresses,
	// mentions, hashtags, cashtags, bot commands and phone numbers in the text.
	SkipEntityDetection bool `json:"skip_entity_detection,omitempty"`
}

InputRichMessage describes a rich message to send with the Bot API 10.1 rich-message methods (sendRichMessage, sendRichMessageDraft, and the rich_message parameter of editMessageText). Exactly one of HTML or Markdown must be set; Telegram parses the source server-side into its rich block tree — headings, tables, ordered and nested lists, blockquotes, dividers, media blocks and so on — and renders it as a single message regardless of length.

InputRichMessage implements Sendable, so the idiomatic way to send one is through Send/Reply:

b.Send(to, &telebot.InputRichMessage{Markdown: "# Title\n\nBody"})

and to edit a message into rich content through Edit:

b.Edit(msg, &telebot.InputRichMessage{HTML: "<b>done</b>"})

func (*InputRichMessage) Send

func (i *InputRichMessage) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers the rich message through bot b to recipient via the sendRichMessage method, satisfying the Sendable interface.

type InputRichMessageContent

type InputRichMessageContent struct {
	// The rich message to be sent.
	RichMessage *InputRichMessage `json:"rich_message"`
}

InputRichMessageContent represents the content of a rich message to be sent as the result of an inline, guest or Web App query (Bot API 10.1).

func (*InputRichMessageContent) IsInputMessageContent

func (i *InputRichMessageContent) IsInputMessageContent() bool

IsInputMessageContent marks InputRichMessageContent as InputMessageContent.

type InputSticker

type InputSticker struct {
	File
	Sticker      string        `json:"sticker"`
	Format       string        `json:"format"`
	MaskPosition *MaskPosition `json:"mask_position"`
	Emojis       []string      `json:"emoji_list"`
	Keywords     []string      `json:"keywords"`
}

type InputTextMessageContent

type InputTextMessageContent struct {
	// Text of the message to be sent, 1-4096 characters.
	Text string `json:"message_text"`

	// (Optional) Send Markdown or HTML, if you want Telegram apps to show
	// bold, italic, fixed-width text or inline URLs in your bot's message.
	ParseMode string `json:"parse_mode,omitempty"`

	// (Optional) Link preview generation options for the message.
	PreviewOptions *PreviewOptions `json:"link_preview_options,omitempty"`
}

InputTextMessageContent represents the content of a text message to be sent as the result of an inline query.

func (*InputTextMessageContent) IsInputMessageContent

func (input *InputTextMessageContent) IsInputMessageContent() bool

type InputVenueMessageContent

type InputVenueMessageContent struct {
	Lat float32 `json:"latitude"`
	Lng float32 `json:"longitude"`

	// Name of the venue.
	Title string `json:"title"`

	// Address of the venue.
	Address string `json:"address"`

	// Optional. Foursquare identifier of the venue, if known.
	FoursquareID string `json:"foursquare_id,omitempty"`
}

InputVenueMessageContent represents the content of a venue message to be sent as the result of an inline query.

func (*InputVenueMessageContent) IsInputMessageContent

func (input *InputVenueMessageContent) IsInputMessageContent() bool

type Inputtable

type Inputtable interface {
	Media

	// InputMedia returns already marshalled InputMedia type
	// ready to be used in sending and editing media methods.
	InputMedia() InputMedia
}

Inputtable is a generic type for all kinds of media you can put into an album.

type Invoice

type Invoice struct {
	Title       string  `json:"title"`
	Description string  `json:"description"`
	Payload     string  `json:"payload"`
	Currency    string  `json:"currency"`
	Prices      []Price `json:"prices"`
	Token       string  `json:"provider_token"`
	Data        string  `json:"provider_data"`

	Photo     *Photo `json:"photo"`
	PhotoSize int    `json:"photo_size"`

	// Unique deep-linking parameter that can be used to
	// generate this invoice when used as a start parameter (0).
	Start string `json:"start_parameter"`

	// Shows the total price in the smallest units of the currency.
	// For example, for a price of US$ 1.45 pass amount = 145.
	Total int `json:"total_amount"`

	MaxTipAmount        int   `json:"max_tip_amount"`
	SuggestedTipAmounts []int `json:"suggested_tip_amounts"`

	NeedName            bool `json:"need_name"`
	NeedPhoneNumber     bool `json:"need_phone_number"`
	NeedEmail           bool `json:"need_email"`
	NeedShippingAddress bool `json:"need_shipping_address"`
	SendPhoneNumber     bool `json:"send_phone_number_to_provider"`
	SendEmail           bool `json:"send_email_to_provider"`
	Flexible            bool `json:"is_flexible"`

	// Bot API 8.0: Star subscriptions
	SubscriptionPeriod int `json:"subscription_period,omitempty"`

	// Bot API 8.0: Business connection support
	BusinessConnectionID string `json:"business_connection_id,omitempty"`
}

Invoice contains basic information about an invoice.

func (*Invoice) Send

func (i *Invoice) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers invoice through bot b to recipient.

type Language

type Language struct {
	Code string // e.g. "en", "fa"
	Name string // display name shown in the language picker
}

Language describes a registered language.

type Location

type Location struct {
	Lat                float32  `json:"latitude"`
	Lng                float32  `json:"longitude"`
	HorizontalAccuracy *float32 `json:"horizontal_accuracy,omitempty"`
	Heading            int      `json:"heading,omitempty"`
	AlertRadius        int      `json:"proximity_alert_radius,omitempty"`

	// Period in seconds for which the location will be updated
	// (see Live Locations, should be between 60 and 86400.)
	LivePeriod int `json:"live_period,omitempty"`

	// (Optional) Unique identifier of the business connection
	// on behalf of which the message to be edited was sent
	BusinessConnectionID string `json:"business_connection_id,omitempty"`
}

Location object represents geographic position.

func (*Location) Send

func (x *Location) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers media through bot b to recipient.

type LocationResult

type LocationResult struct {
	ResultBase

	Location

	// Location title.
	Title string `json:"title"`

	// Optional. Url of the thumbnail for the result.
	ThumbURL string `json:"thumbnail_url,omitempty"`
}

LocationResult represents a location on a map.

type Login

type Login struct {
	URL         string `json:"url"`
	Text        string `json:"forward_text,omitempty"`
	Username    string `json:"bot_username,omitempty"`
	WriteAccess bool   `json:"request_write_access,omitempty"`
}

Login represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram.

type LongPoller

type LongPoller struct {
	Limit        int
	Timeout      time.Duration
	LastUpdateID int

	// AllowedUpdates contains the update types
	// you want your bot to receive.
	//
	// Possible values:
	//		message
	// 		edited_message
	// 		channel_post
	// 		edited_channel_post
	// 		inline_query
	// 		chosen_inline_result
	// 		callback_query
	// 		shipping_query
	// 		pre_checkout_query
	// 		poll
	// 		poll_answer
	// 		guest_message
	//
	AllowedUpdates []string `yaml:"allowed_updates"`
}

LongPoller is a classic LongPoller with timeout.

func (*LongPoller) Poll

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

Poll does long polling.

type M

type M = map[string]interface{}

M is a shortcut for map[string]interface{}. Useful for passing arguments to the layout functions.

type MaskFeature

type MaskFeature = string
const (
	MaskForehead MaskFeature = "forehead"
	MaskEyes     MaskFeature = "eyes"
	MaskMouth    MaskFeature = "mouth"
	MaskChin     MaskFeature = "chin"
)

type MaskPosition

type MaskPosition struct {
	Feature MaskFeature `json:"point"`
	XShift  float32     `json:"x_shift"`
	YShift  float32     `json:"y_shift"`
	Scale   float32     `json:"scale"`
}

MaskPosition describes the position on faces where a mask should be placed by default.

type Media

type Media interface {
	// MediaType returns string-represented media type.
	MediaType() string

	// MediaFile returns a pointer to the media file.
	MediaFile() *File
}

Media is a generic type for all kinds of media that includes File.

type MemberStatus

type MemberStatus string

MemberStatus is one's chat status.

const (
	Creator       MemberStatus = "creator"
	Administrator MemberStatus = "administrator"
	Member        MemberStatus = "member"
	Restricted    MemberStatus = "restricted"
	Left          MemberStatus = "left"
	Kicked        MemberStatus = "kicked"
)

type MemoryStore

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

MemoryStore is a Store that keeps everything in memory. Nothing survives a restart, so it is meant for tests and throwaway bots.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty MemoryStore.

func (*MemoryStore) AccountByID

func (m *MemoryStore) AccountByID(_ context.Context, id int64) (*Account, error)

func (*MemoryStore) AccountByTelegramID

func (m *MemoryStore) AccountByTelegramID(_ context.Context, telegramID int64) (*Account, error)

func (*MemoryStore) LoadSession

func (m *MemoryStore) LoadSession(_ context.Context, chatID int64) ([]byte, error)

func (*MemoryStore) SaveSession

func (m *MemoryStore) SaveSession(_ context.Context, chatID int64, payload []byte) error

func (*MemoryStore) SetAccountLanguage

func (m *MemoryStore) SetAccountLanguage(_ context.Context, accountID int64, lang string) error

func (*MemoryStore) UpsertAccount

func (m *MemoryStore) UpsertAccount(_ context.Context, a *Account) error
type MenuButton struct {
	Type   MenuButtonType `json:"type"`
	Text   string         `json:"text,omitempty"`
	WebApp *WebApp        `json:"web_app,omitempty"`
}

MenuButton describes the bot's menu button in a private chat.

type MenuButtonType = string
const (
	MenuButtonDefault  MenuButtonType = "default"
	MenuButtonCommands MenuButtonType = "commands"
	MenuButtonWebApp   MenuButtonType = "web_app"
)

type Message

type Message struct {
	ID int `json:"message_id"`

	// (Optional) Unique identifier of a message thread to which the message belongs; for supergroups only
	ThreadID int `json:"message_thread_id"`

	// For message sent to channels, Sender will be nil
	Sender *User `json:"from"`

	// Unixtime, use Message.Time() to get time.Time
	Unixtime int64 `json:"date"`

	// Conversation the message belongs to.
	Chat *Chat `json:"chat"`

	// Sender of the message, sent on behalf of a chat.
	SenderChat *Chat `json:"sender_chat"`

	// The user that called the bot in guest mode.
	GuestUser *User `json:"guest_bot_caller_user"`

	// The chat that called the bot in guest mode.
	GuestChat *Chat `json:"guest_bot_caller_chat"`

	// For forwarded messages, sender of the original message.
	OriginalSender *User `json:"forward_from"`

	// For forwarded messages, chat of the original message when
	// forwarded from a channel.
	OriginalChat *Chat `json:"forward_from_chat"`

	// For forwarded messages, identifier of the original message
	// when forwarded from a channel.
	OriginalMessageID int `json:"forward_from_message_id"`

	// For forwarded messages, signature of the post author.
	OriginalSignature string `json:"forward_signature"`

	// For forwarded messages, sender's name from users who
	// disallow adding a link to their account.
	OriginalSenderName string `json:"forward_sender_name"`

	// For forwarded messages, unixtime of the original message.
	OriginalUnixtime int `json:"forward_date"`

	// For information about the original message for forwarded messages.
	Origin *MessageOrigin `json:"forward_origin"`

	// Message is a channel post that was automatically forwarded to the connected discussion group.
	AutomaticForward bool `json:"is_automatic_forward"`

	// For replies, ReplyTo represents the original message.
	//
	// Note that the Message object in this field will not
	// contain further ReplyTo fields even if it
	// itself is a reply.
	ReplyTo *Message `json:"reply_to_message"`

	// (Optional) For replies to a story, the original story
	Story *Story `json:"story"`

	// (Optional) Information about the message that is being replied to,
	// which may come from another chat or forum topic.
	ExternalReply *ExternalReply `json:"external_reply"`

	// (Optional) For replies that quote part of the original message,
	// the quoted part of the message.
	Quote *TextQuote `json:"quote"`

	// Shows through which bot the message was sent.
	Via *User `json:"via_bot"`

	// For replies to a story, the original story.
	ReplyToStory *Story `json:"reply_to_story"`

	// (Optional) Time of last edit in Unix.
	LastEdit int64 `json:"edit_date"`

	// (Optional) True, if the message is sent to a forum topic.
	TopicMessage bool `json:"is_topic_message"`

	// (Optional) Message can't be forwarded.
	Protected bool `json:"has_protected_content,omitempty"`

	// (Optional) True, if the message was sent by an implicit action,
	// for example, as an away or a greeting business message, or as a scheduled message
	FromOffline bool `json:"is_from_offline,omitempty"`

	// AlbumID is the unique identifier of a media message group
	// this message belongs to.
	AlbumID string `json:"media_group_id"`

	// Author signature (in channels).
	Signature string `json:"author_signature"`

	// For a text message, the actual UTF-8 text of the message.
	Text string `json:"text"`

	// For registered commands, will contain the string payload:
	//
	// Ex: `/command <payload>` or `/command@botname <payload>`
	Payload string `json:"-"`

	// For text messages, special entities like usernames, URLs, bot commands,
	// etc. that appear in the text.
	Entities Entities `json:"entities,omitempty"`

	// (Optional) PreviewOptions used for link preview generation for the message,
	// if it is a text message and link preview options were changed.
	PreviewOptions *PreviewOptions `json:"link_preview_options,omitempty"`

	// (Optional) Unique identifier of the message effect added to the message
	EffectID string `json:"effect_id"`

	// Some messages containing media, may as well have a caption.
	Caption string `json:"caption,omitempty"`

	// For messages with a caption, special entities like usernames, URLs,
	// bot commands, etc. that appear in the caption.
	CaptionEntities Entities `json:"caption_entities,omitempty"`

	// For an audio recording, information about it.
	Audio *Audio `json:"audio"`

	// For a general file, information about it.
	Document *Document `json:"document"`

	// Message contains paid media; information about the paid media
	PaidMedia PaidMedias `json:"paid_media"`

	// For a photo, all available sizes (thumbnails).
	Photo *Photo `json:"photo"`

	// For a sticker, information about it.
	Sticker *Sticker `json:"sticker"`

	// For a voice message, information about it.
	Voice *Voice `json:"voice"`

	// For a video note, information about it.
	VideoNote *VideoNote `json:"video_note"`

	// For a video, information about it.
	Video *Video `json:"video"`

	// For an animation, information about it.
	Animation *Animation `json:"animation"`

	// For a contact, contact information itself.
	Contact *Contact `json:"contact"`

	// For a location, its longitude and latitude.
	Location *Location `json:"location"`

	// For a venue, information about it.
	Venue *Venue `json:"venue"`

	// For a poll, information the native poll.
	Poll *Poll `json:"poll"`

	// For a game, information about it.
	Game *Game `json:"game"`

	// For a dice, information about it.
	Dice *Dice `json:"dice"`

	// (Optional) The message is a scheduled giveaway message.
	Giveaway *Giveaway `json:"giveaway"`

	// (Optional) A giveaway with public winners was completed.
	GiveawayWinners *GiveawayWinners `json:"giveaway_winners"`

	// (Optional) Service message: a scheduled giveaway was created.
	GiveawayCreated *GiveawayCreated `json:"giveaway_created"`

	// (Optional) Service message: a giveaway without public winners was completed.
	GiveawayCompleted *GiveawayCompleted `json:"giveaway_completed"`

	// (Optional) Unique identifier of the business connection from which the message
	// was received. If non-empty, the message belongs to a chat of the corresponding
	// business account that is independent from any potential bot chat which might
	// share the same identifier.
	BusinessConnectionID string `json:"business_connection_id"`

	// Unique identifier for answering the guest query.
	GuestQueryID string `json:"guest_query_id"`

	// (Optional) For a rich message, the rich formatted content (Bot API 10.1).
	RichMessage *RichMessage `json:"rich_message,omitempty"`

	// (Optional) The bot that actually sent the message on behalf of the business account.
	// Available only for outgoing messages sent on behalf of the connected business account.
	BusinessBot *User `json:"sender_business_bot"`

	// For a service message, represents a user,
	// that just got added to chat, this message came from.
	//
	// Sender leads to User, capable of invite.
	//
	// UserJoined might be the Bot itself.
	UserJoined *User `json:"new_chat_member"`

	// For a service message, represents a user,
	// that just left chat, this message came from.
	//
	// If user was kicked, Sender leads to a User,
	// capable of this kick.
	//
	// UserLeft might be the Bot itself.
	UserLeft *User `json:"left_chat_member"`

	// For a service message, represents a new title
	// for chat this message came from.
	//
	// Sender would lead to a User, capable of change.
	NewGroupTitle string `json:"new_chat_title"`

	// For a service message, represents all available
	// thumbnails of the new chat photo.
	//
	// Sender would lead to a User, capable of change.
	NewGroupPhoto *Photo `json:"new_chat_photo"`

	// For a service message, new members that were added to
	// the group or supergroup and information about them
	// (the bot itself may be one of these members).
	UsersJoined []User `json:"new_chat_members"`

	// For a service message, true if chat photo just
	// got removed.
	//
	// Sender would lead to a User, capable of change.
	GroupPhotoDeleted bool `json:"delete_chat_photo"`

	// For a service message, true if group has been created.
	//
	// You would receive such a message if you are one of
	// initial group chat members.
	//
	// Sender would lead to creator of the chat.
	GroupCreated bool `json:"group_chat_created"`

	// For a service message, true if supergroup has been created.
	//
	// You would receive such a message if you are one of
	// initial group chat members.
	//
	// Sender would lead to creator of the chat.
	SuperGroupCreated bool `json:"supergroup_chat_created"`

	// For a service message, true if channel has been created.
	//
	// You would receive such a message if you are one of
	// initial channel administrators.
	//
	// Sender would lead to creator of the chat.
	ChannelCreated bool `json:"channel_chat_created"`

	// For a service message, the destination (supergroup) you
	// migrated to.
	//
	// You would receive such a message when your chat has migrated
	// to a supergroup.
	//
	// Sender would lead to creator of the migration.
	MigrateTo int64 `json:"migrate_to_chat_id"`

	// For a service message, the Origin (normal group) you migrated
	// from.
	//
	// You would receive such a message when your chat has migrated
	// to a supergroup.
	//
	// Sender would lead to creator of the migration.
	MigrateFrom int64 `json:"migrate_from_chat_id"`

	// Specified message was pinned. Note that the Message object
	// in this field will not contain further ReplyTo fields even
	// if it is itself a reply.
	PinnedMessage *Message `json:"pinned_message"`

	// Message is an invoice for a payment.
	Invoice *Invoice `json:"invoice"`

	// Message is a service message about a successful payment.
	Payment *Payment `json:"successful_payment"`

	// Message is a service message about a refunded payment, information about the payment.
	RefundedPayment *RefundedPayment `json:"refunded_payment"`

	// For a service message, a user was shared with the bot.
	UserShared *RecipientShared `json:"users_shared,omitempty"`

	// For a service message, a chat was shared with the bot.
	ChatShared *RecipientShared `json:"chat_shared,omitempty"`

	// The domain name of the website on which the user has logged in.
	ConnectedWebsite string `json:"connected_website,omitempty"`

	// For a service message, a video chat started in the chat.
	VideoChatStarted *VideoChatStarted `json:"video_chat_started,omitempty"`

	// For a service message, a video chat ended in the chat.
	VideoChatEnded *VideoChatEnded `json:"video_chat_ended,omitempty"`

	// For a service message, some users were invited in the video chat.
	VideoChatParticipants *VideoChatParticipants `json:"video_chat_participants_invited,omitempty"`

	// For a service message, a video chat schedule in the chat.
	VideoChatScheduled *VideoChatScheduled `json:"video_chat_scheduled,omitempty"`

	// For a data sent by a Web App.
	WebAppData *WebAppData `json:"web_app_data,omitempty"`

	// For a service message, represents the content of a service message,
	// sent whenever a user in the chat triggers a proximity alert set by another user.
	ProximityAlert *ProximityAlert `json:"proximity_alert_triggered,omitempty"`

	// For a service message, represents about a change in auto-delete timer settings.
	AutoDeleteTimer *AutoDeleteTimer `json:"message_auto_delete_timer_changed,omitempty"`

	// Inline keyboard attached to the message.
	ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`

	// Service message: user boosted the chat.
	BoostAdded *BoostAdded `json:"boost_added"`

	// Service message: chat background set
	ChatBackground ChatBackground `json:"chat_background_set"`

	// If the sender of the message boosted the chat, the number of boosts
	// added by the user.
	SenderBoosts int `json:"sender_boost_count"`

	// Bot API 9.5: (Optional) Tag or custom title of the sender of the message;
	// for supergroups only.
	SenderTag string `json:"sender_tag,omitempty"`

	// Service message: forum topic created
	TopicCreated *Topic `json:"forum_topic_created,omitempty"`

	// Service message: forum topic closed
	TopicClosed *struct{} `json:"forum_topic_closed,omitempty"`

	// Service message: forum topic reopened
	TopicReopened *Topic `json:"forum_topic_reopened,omitempty"`

	// Service message: forum topic deleted
	TopicEdited *Topic `json:"forum_topic_edited,omitempty"`

	// Service message: general forum topic hidden
	GeneralTopicHidden *struct{} `json:"general_topic_hidden,omitempty"`

	// Service message: general forum topic unhidden
	GeneralTopicUnhidden *struct{} `json:"general_topic_unhidden,omitempty"`

	// Service message: represents spoiler information about the message.
	HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"`

	// (Optional) Pass True, if the caption must be shown above the message media
	CaptionAbove bool `json:"show_caption_above_media"`

	// Service message: the user allowed the bot added to the attachment menu to write messages
	WriteAccessAllowed *WriteAccessAllowed `json:"write_access_allowed,omitempty"`

	// Bot API 9.4: Service message: chat owner has left.
	ChatOwnerLeft *ChatOwnerLeft `json:"chat_owner_left,omitempty"`

	// Bot API 9.4: Service message: chat owner has changed.
	ChatOwnerChanged *ChatOwnerChanged `json:"chat_owner_changed,omitempty"`
}

Message object represents a message.

func (*Message) EntityText

func (m *Message) EntityText(e MessageEntity) string

EntityText returns the substring of the message identified by the given MessageEntity.

It's safer than manually slicing Text because Telegram uses UTF-16 indices whereas Go string are []byte.

func (*Message) FromChannel

func (m *Message) FromChannel() bool

FromChannel returns true, if message came from a channel.

func (*Message) FromGroup

func (m *Message) FromGroup() bool

FromGroup returns true, if message came from a group OR a supergroup.

func (*Message) Inaccessible

func (m *Message) Inaccessible() bool

Inaccessible shows whether the message is InaccessibleMessage object.

func (*Message) IsForwarded

func (m *Message) IsForwarded() bool

IsForwarded says whether message is forwarded copy of another message or not.

func (*Message) IsReply

func (m *Message) IsReply() bool

IsReply says whether message is a reply to another message.

func (*Message) IsService

func (m *Message) IsService() bool

IsService returns true, if message is a service message, returns false otherwise.

Service messages are automatically sent messages, which typically occur on some global action. For instance, when anyone leaves the chat or chat title changes.

func (*Message) LastEdited

func (m *Message) LastEdited() time.Time

LastEdited returns time.Time of last edit.

func (*Message) Media

func (m *Message) Media() Media

Media returns the message's media if it contains either photo, voice, audio, animation, sticker, document, video or video note.

func (*Message) MessageSig

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

MessageSig satisfies Editable interface (see Editable.)

func (*Message) Private

func (m *Message) Private() bool

Private returns true, if it's a personal message.

func (*Message) Time

func (m *Message) Time() time.Time

Time returns the moment of message creation in local time.

type MessageEntity

type MessageEntity struct {
	// Specifies entity type.
	Type EntityType `json:"type"`

	// Offset in UTF-16 code units to the start of the entity.
	Offset int `json:"offset"`

	// Length of the entity in UTF-16 code units.
	Length int `json:"length"`

	// (Optional) For EntityTextLink entity type only.
	//
	// URL will be opened after user taps on the text.
	URL string `json:"url,omitempty"`

	// (Optional) For EntityTMention entity type only.
	User *User `json:"user,omitempty"`

	// (Optional) For EntityCodeBlock entity type only.
	Language string `json:"language,omitempty"`

	// (Optional) For EntityCustomEmoji entity type only.
	CustomEmojiID string `json:"custom_emoji_id,omitempty"`

	// (Optional) For EntityHashtag and EntityCashtag entity types only.
	// Username of the chat where the hashtag or cashtag search should be performed.
	ChatUsername string `json:"chat_username,omitempty"`

	// Bot API 9.5: (Optional) For EntityDateTime only,
	// the Unix time associated with the entity.
	UnixTime int64 `json:"unix_time,omitempty"`

	// Bot API 9.5: (Optional) For EntityDateTime only,
	// the string that defines the formatting of the date and time.
	DateTimeFormat string `json:"date_time_format,omitempty"`
}

MessageEntity object represents "special" parts of text messages, including hashtags, usernames, URLs, etc.

type MessageOrigin

type MessageOrigin struct {
	// Type of the message origin, always “channel”.
	Type string `json:"type"`

	// Date the message was sent originally in Unix time.
	DateUnixtime int64 `json:"date"`

	// User that sent the message originally.
	Sender *User `json:"sender_user,omitempty"`

	// Name of the user that sent the message originally.
	SenderUsername string `json:"sender_user_name,omitempty"`

	// Chat that sent the message originally.
	SenderChat *Chat `json:"sender_chat,omitempty"`

	// Channel chat to which the message was originally sent.
	Chat *Chat `json:"chat,omitempty"`

	// Unique message identifier inside the chat.
	MessageID int `json:"message_id,omitempty"`

	// (Optional) For messages originally sent by an anonymous chat administrator,
	// original message author signature.
	Signature string `json:"author_signature,omitempty"`
}

MessageOrigin a message reference that has been sent originally by a known user.

func (*MessageOrigin) Time

func (mo *MessageOrigin) Time() time.Time

Time returns the moment of message that was sent originally in local time.

type MessageReaction

type MessageReaction struct {
	// The chat containing the message the user reacted to.
	Chat *Chat `json:"chat"`

	// Unique identifier of the message inside the chat.
	MessageID int `json:"message_id"`

	// (Optional) The user that changed the reaction,
	// if the user isn't anonymous
	User *User `json:"user"`

	// (Optional) The chat on behalf of which the reaction was changed,
	// if the user is anonymous.
	ActorChat *Chat `json:"actor_chat"`

	// Date of the change in Unix time.
	DateUnixtime int64 `json:"date"`

	// Previous list of reaction types that were set by the user.
	OldReaction []Reaction `json:"old_reaction"`

	// New list of reaction types that have been set by the user.
	NewReaction []Reaction `json:"new_reaction"`
}

MessageReaction object represents a change of a reaction on a message performed by a user.

func (*MessageReaction) Time

func (mu *MessageReaction) Time() time.Time

type MessageReactionCount

type MessageReactionCount struct {
	// The chat containing the message.
	Chat *Chat `json:"chat"`

	// Unique message identifier inside the chat.
	MessageID int `json:"message_id"`

	// Date of the change in Unix time.
	DateUnixtime int64 `json:"date"`

	// List of reactions that are present on the message.
	Reactions []*ReactionCount `json:"reactions"`
}

MessageReactionCount represents reaction changes on a message with anonymous reactions.

func (*MessageReactionCount) Time

func (mc *MessageReactionCount) Time() time.Time

Time returns the moment of change in local time.

type Middleware

type Middleware[T any] func(next Handler[T]) Handler[T]

Middleware wraps a Handler, e.g. to restrict access or add logging.

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc represents a middleware processing function, which get called before the endpoint group or specific handler.

type MiddlewarePoller

type MiddlewarePoller struct {
	Capacity int // Default: 1
	Poller   Poller
	Filter   func(*Update) bool
}

MiddlewarePoller is a special kind of poller that acts like a filter for updates. It could be used for spam handling, banning or whatever.

For heavy middleware, use increased capacity.

func NewMiddlewarePoller

func NewMiddlewarePoller(original Poller, filter func(*Update) bool) *MiddlewarePoller

NewMiddlewarePoller wait for it... constructs a new middleware poller.

func (*MiddlewarePoller) Poll

func (p *MiddlewarePoller) Poll(b *Bot, dest chan Update, stop chan struct{})

Poll sieves updates through middleware filter.

type Migration

type Migration struct {
	Version int
	Name    string
	Up      func(ctx context.Context, tx bun.Tx) error
}

Migration is one versioned, forward-only schema change. Up runs inside a transaction together with the bookkeeping row, so a failed migration leaves no trace.

type Mpeg4GifResult

type Mpeg4GifResult struct {
	ResultBase

	// A valid URL for the MP4 file.
	URL string `json:"mpeg4_url"`

	// Optional. Video width.
	Width int `json:"mpeg4_width,omitempty"`

	// Optional. Video height.
	Height int `json:"mpeg4_height,omitempty"`

	// Optional. Video duration.
	Duration int `json:"mpeg4_duration,omitempty"`

	// URL of the static thumbnail (jpeg or gif) for the result.
	ThumbURL string `json:"thumbnail_url,omitempty"`

	// Optional. MIME type of the thumbnail, must be one of
	// “image/jpeg”, “image/gif”, or “video/mp4”.
	ThumbMIME string `json:"thumbnail_mime_type,omitempty"`

	// Optional. Title for the result.
	Title string `json:"title,omitempty"`

	// Optional. Caption of the MPEG-4 file to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// If Cache != "", it'll be used instead
	Cache string `json:"mpeg4_file_id,omitempty"`

	// (Optional) Pass True, if the caption must be shown above the message media
	CaptionAbove bool `json:"show_caption_above_media,omitempty"`
}

Mpeg4GifResult represents a link to a video animation (H.264/MPEG-4 AVC video without sound).

type Option

type Option int

Option is a shortcut flag type for certain message features (so-called options). It means that instead of passing fully-fledged SendOptions* to Send(), you can use these flags instead.

Supported options are defined as iota-constants.

const (
	// NoPreview = SendOptions.DisableWebPagePreview
	NoPreview Option = iota

	// Silent = SendOptions.DisableNotification
	Silent

	// AllowWithoutReply = SendOptions.AllowWithoutReply
	AllowWithoutReply

	// Protected = SendOptions.Protected
	Protected

	// ForceReply = ReplyMarkup.ForceReply
	ForceReply

	// OneTimeKeyboard = ReplyMarkup.OneTimeKeyboard
	OneTimeKeyboard

	// RemoveKeyboard = ReplyMarkup.RemoveKeyboard
	RemoveKeyboard

	// IgnoreThread is used to ignore the thread when responding to a message via context.
	IgnoreThread
)

type Order

type Order struct {
	Name        string          `json:"name"`
	PhoneNumber string          `json:"phone_number"`
	Email       string          `json:"email"`
	Address     ShippingAddress `json:"shipping_address"`
}

Order represents information about an order.

type PaidAlbum

type PaidAlbum []PaidInputtable

PaidAlbum lets you group multiple paid media into a single message.

type PaidInputtable

type PaidInputtable interface {
	Inputtable

	// Paid shows if the media is paid.
	Paid() bool
}

PaidInputtable is a generic type for all kinds of media you can put into an album that are paid.

type PaidMedia

type PaidMedia struct {
	Type     string `json:"type"`
	Photo    *Photo `json:"photo"`    // photo
	Video    *Video `json:"video"`    // video
	Width    int    `json:"width"`    // preview only
	Height   int    `json:"height"`   // preview only
	Duration int    `json:"duration"` // preview only
	Payload  string `json:"payload,omitempty"`

	// Bot API 8.3: (Optional) Cover frame of the video (for paid video media)
	Cover *Photo `json:"cover,omitempty"`

	// Bot API 8.3: (Optional) Point in time (Unix timestamp) when the video starts (for paid video media)
	StartTimestamp int64 `json:"start_timestamp,omitempty"`
}

type PaidMediaPurchased

type PaidMediaPurchased struct {
	// User who purchased the media.
	From *User `json:"from"`

	// Bot-specified paid media payload.
	Payload string `json:"paid_media_payload"`
}

PaidMediaPurchased contains information about paid media purchased by a user.

type PaidMedias

type PaidMedias struct {
	Stars     int         `json:"star_count"`
	PaidMedia []PaidMedia `json:"paid_media"`
}

type ParseEntitiesError

type ParseEntitiesError struct {
	// Description is Telegram's description, e.g. "Bad Request: can't parse
	// entities: Character '.' is reserved and must be escaped with the
	// preceding '\'".
	Description string
	// Offset is the reported byte offset into Text, or -1 if none was given.
	Offset int
	// Text is the text or caption that was sent, when it is known.
	Text string
}

ParseEntitiesError is returned when Telegram rejects a message's markup, typically an unescaped MarkdownV2 character. Telegram only reports a byte offset, so the error also carries the text around it: in

can't parse entities: Can't find end of the entity starting at byte offset 9
near "Hi john▶_doe!"

the '▶' marks the offending byte. Escape user-supplied values with Escape, EscapeMarkdownV2 or EscapeHTML to avoid it.

func (*ParseEntitiesError) Error

func (e *ParseEntitiesError) Error() string

Error implements error.

func (*ParseEntitiesError) Excerpt

func (e *ParseEntitiesError) Excerpt() string

Excerpt returns up to 20 bytes of Text on each side of Offset, with '▶' inserted before the offending byte. It is empty when Text or Offset is unknown.

func (*ParseEntitiesError) Is

func (e *ParseEntitiesError) Is(target error) bool

Is makes errors.Is(err, ErrCantParseEntities) true.

type ParseMode

type ParseMode = string

ParseMode determines the way client applications treat the text of the message

const (
	ModeDefault    ParseMode = ""
	ModeMarkdown   ParseMode = "Markdown"
	ModeMarkdownV2 ParseMode = "MarkdownV2"
	ModeHTML       ParseMode = "HTML"
)

type Payment

type Payment struct {
	Currency         string `json:"currency"`
	Total            int    `json:"total_amount"`
	Payload          string `json:"invoice_payload"`
	OptionID         string `json:"shipping_option_id"`
	Order            Order  `json:"order_info"`
	TelegramChargeID string `json:"telegram_payment_charge_id"`
	ProviderChargeID string `json:"provider_payment_charge_id"`

	// Bot API 8.0: Star subscriptions
	SubscriptionExpirationDate int64 `json:"subscription_expiration_date,omitempty"`
	IsRecurring                bool  `json:"is_recurring,omitempty"`
	IsFirstRecurring           bool  `json:"is_first_recurring,omitempty"`
}

Payment contains basic information about a successful payment.

type Photo

type Photo struct {
	File

	// (Optional)
	Width        int    `json:"width"`
	Height       int    `json:"height"`
	Caption      string `json:"caption,omitempty"`
	HasSpoiler   bool   `json:"has_spoiler,omitempty"`
	CaptionAbove bool   `json:"show_caption_above_media,omitempty"`
}

Photo object represents a single photo file.

func (*Photo) InputMedia

func (p *Photo) InputMedia() InputMedia

func (*Photo) MediaFile

func (p *Photo) MediaFile() *File

func (*Photo) MediaType

func (p *Photo) MediaType() string

func (*Photo) Paid

func (p *Photo) Paid() bool

func (*Photo) Send

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

Send delivers media through bot b to recipient.

func (*Photo) UnmarshalJSON

func (p *Photo) UnmarshalJSON(data []byte) error

UnmarshalJSON is custom unmarshaller required to abstract away the hassle of treating different thumbnail sizes. Instead, Telebot chooses the hi-res one and just sticks to it.

I really do find it a beautiful solution.

type PhotoResult

type PhotoResult struct {
	ResultBase

	// A valid URL of the photo. Photo must be in jpeg format.
	// Photo size must not exceed 5MB.
	URL string `json:"photo_url"`

	// Optional. Width of the photo.
	Width int `json:"photo_width,omitempty"`

	// Optional. Height of the photo.
	Height int `json:"photo_height,omitempty"`

	// Optional. Title for the result.
	Title string `json:"title,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. Caption of the photo to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// URL of the thumbnail for the photo.
	ThumbURL string `json:"thumbnail_url"`

	// If Cache != "", it'll be used instead
	Cache string `json:"photo_file_id,omitempty"`

	// (Optional) Pass True, if the caption must be shown above the message media
	CaptionAbove bool `json:"show_caption_above_media,omitempty"`
}

PhotoResult represents a link to a photo.

type Poll

type Poll struct {
	ID         string       `json:"id"`
	Type       PollType     `json:"type"`
	Question   string       `json:"question"`
	Options    []PollOption `json:"options"`
	VoterCount int          `json:"total_voter_count"`

	// (Optional)
	Closed            bool            `json:"is_closed,omitempty"`
	CorrectOption     int             `json:"correct_option_id,omitempty"`
	MultipleAnswers   bool            `json:"allows_multiple_answers,omitempty"`
	Explanation       string          `json:"explanation,omitempty"`
	ParseMode         ParseMode       `json:"explanation_parse_mode,omitempty"`
	Entities          []MessageEntity `json:"explanation_entities,omitempty"`
	QuestionParseMode string          `json:"question_parse_mode,omitempty"`
	QuestionEntities  []MessageEntity `json:"question_entities,omitempty"`

	// True by default, shouldn't be omitted.
	Anonymous bool `json:"is_anonymous"`

	// (Mutually exclusive)
	OpenPeriod    int   `json:"open_period,omitempty"`
	CloseUnixdate int64 `json:"close_date,omitempty"`
}

Poll contains information about a poll.

func (*Poll) AddOptions

func (p *Poll) AddOptions(opts ...string)

AddOptions adds text options to the poll.

func (*Poll) CloseDate

func (p *Poll) CloseDate() time.Time

CloseDate returns the close date of poll in local time.

func (*Poll) IsQuiz

func (p *Poll) IsQuiz() bool

IsQuiz says whether poll is a quiz.

func (*Poll) IsRegular

func (p *Poll) IsRegular() bool

IsRegular says whether poll is a regular.

func (*Poll) Send

func (p *Poll) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers poll through bot b to recipient.

type PollAnswer

type PollAnswer struct {
	PollID  string `json:"poll_id"`
	Sender  *User  `json:"user"`
	Chat    *Chat  `json:"voter_chat"`
	Options []int  `json:"option_ids"`
}

PollAnswer represents an answer of a user in a non-anonymous poll.

type PollOption

type PollOption struct {
	Text       string          `json:"text"`
	VoterCount int             `json:"voter_count"`
	ParseMode  ParseMode       `json:"text_parse_mode,omitempty"`
	Entities   []MessageEntity `json:"text_entities,omitempty"`
}

PollOption contains information about one answer option in a poll.

type PollType

type PollType string

PollType defines poll types.

const (
	// NOTE:
	// Despite "any" type isn't described in documentation,
	// it needed for proper KeyboardButtonPollType marshaling.
	PollAny PollType = "any"

	PollQuiz    PollType = "quiz"
	PollRegular PollType = "regular"
)

func (PollType) MarshalJSON

func (pt PollType) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It allows passing PollType as a keyboard's poll type instead of KeyboardButtonPollType object.

type Poller

type Poller interface {
	// Poll is supposed to take the bot object
	// subscription channel and start polling
	// for Updates immediately.
	//
	// Poller must listen for stop constantly and close
	// it as soon as it's done polling.
	Poll(b *Bot, updates chan Update, stop chan struct{})
}

Poller is a provider of Updates.

All pollers must implement Poll(), which accepts bot pointer and subscription channel and start polling synchronously straight away.

type PreCheckoutQuery

type PreCheckoutQuery struct {
	Sender   *User  `json:"from"`
	ID       string `json:"id"`
	Currency string `json:"currency"`
	Payload  string `json:"invoice_payload"`
	Total    int    `json:"total_amount"`
	OptionID string `json:"shipping_option_id"`
	Order    Order  `json:"order_info"`
}

PreCheckoutQuery contains information about an incoming pre-checkout query.

type PreparedInlineMessage

type PreparedInlineMessage struct {
	// Unique identifier of the prepared message
	ID string `json:"id"`

	// Expiration date of the prepared message, in Unix time.
	// Expired prepared messages can no longer be used.
	ExpirationDate int64 `json:"expiration_date"`
}

PreparedInlineMessage describes an inline message to be sent by a user of a Mini App.

type PreviewOptions

type PreviewOptions struct {
	// (Optional) True, if the link preview is disabled.
	Disabled bool `json:"is_disabled"`

	// (Optional) URL to use for the link preview. If empty, then the first URL
	// found in the message text will be used.
	URL string `json:"url"`

	// (Optional) True, if the media in the link preview is supposed to be shrunk;
	// ignored if the URL isn't explicitly specified or media size change.
	// isn't supported for the preview.
	SmallMedia bool `json:"prefer_small_media"`

	// (Optional) True, if the media in the link preview is supposed to be enlarged;
	// ignored if the URL isn't explicitly specified or media size change.
	// isn't supported for the preview.
	LargeMedia bool `json:"prefer_large_media"`

	// (Optional) True, if the link preview must be shown above the message text;
	// otherwise, the link preview will be shown below the message text.
	AboveText bool `json:"show_above_text"`
}

PreviewOptions describes the options used for link preview generation.

type Price

type Price struct {
	Label  string `json:"label"`
	Amount int    `json:"amount"`
}

Price represents a portion of the price for goods or services.

type ProximityAlert

type ProximityAlert struct {
	Traveler *User `json:"traveler,omitempty"`
	Watcher  *User `json:"watcher,omitempty"`
	Distance int   `json:"distance"`
}

ProximityAlert sent whenever a user in the chat triggers a proximity alert set by another user.

type Query

type Query struct {
	// Unique identifier for this query. 1-64 bytes.
	ID string `json:"id"`

	// Sender.
	Sender *User `json:"from"`

	// Sender location, only for bots that request user location.
	Location *Location `json:"location"`

	// Text of the query (up to 512 characters).
	Text string `json:"query"`

	// Offset of the results to be returned, can be controlled by the bot.
	Offset string `json:"offset"`

	// ChatType of the type of the chat, from which the inline query was sent.
	ChatType string `json:"chat_type"`
}

Query is an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

type QueryResponse

type QueryResponse struct {
	// The ID of the query to which this is a response.
	//
	// Note: Telebot sets this field automatically!
	QueryID string `json:"inline_query_id"`

	// The results for the inline query.
	Results Results `json:"results"`

	// (Optional) The maximum amount of time in seconds that the result
	// of the inline query may be cached on the server.
	CacheTime int `json:"cache_time,omitempty"`

	// (Optional) Pass True, if results may be cached on the server side
	// only for the user that sent the query. By default, results may
	// be returned to any user who sends the same query.
	IsPersonal bool `json:"is_personal"`

	// (Optional) Pass the offset that a client should send in the next
	// query with the same text to receive more results. Pass an empty
	// string if there are no more results or if you don‘t support
	// pagination. Offset length can’t exceed 64 bytes.
	NextOffset string `json:"next_offset"`

	// (Optional) If passed, clients will display a button with specified
	// text that switches the user to a private chat with the bot and sends
	// the bot a start message with the parameter switch_pm_parameter.
	SwitchPMText string `json:"switch_pm_text,omitempty"`

	// (Optional) Parameter for the start message sent to the bot when user
	// presses the switch button.
	SwitchPMParameter string `json:"switch_pm_parameter,omitempty"`

	// (Optional) A JSON-serialized object describing a button to be shown
	// above inline query results.
	Button *QueryResponseButton `json:"button,omitempty"`
}

QueryResponse builds a response to an inline Query.

type QueryResponseButton

type QueryResponseButton struct {
	// Label text on the button
	Text string `json:"text"`

	// (Optional) Description of the Web App that will be launched when the
	// user presses the button. The Web App will be able to switch back to the
	// inline mode using the method switchInlineQuery inside the Web App.
	WebApp *WebApp `json:"web_app"`

	// (Optional) Deep-linking parameter for the /start message sent to the bot
	// when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.
	Start string `json:"start_parameter,omitempty"`
}

QueryResponseButton represents a button to be shown above inline query results. You must use exactly one of the optional fields.

type Question

type Question int

Question is a step inside a Scene. Zero is the scene's entry point.

func (Question) Next

func (q Question) Next() Question

Next returns the following question.

type Reaction

type Reaction struct {
	// Type of the reaction, always “emoji”
	Type string `json:"type"`

	// Reaction emoji.
	Emoji string `json:"emoji,omitempty"`

	// Custom emoji identifier.
	CustomEmojiID string `json:"custom_emoji_id,omitempty"`
}

Reaction describes the type of reaction. Describes an instance of ReactionTypeCustomEmoji and ReactionTypeEmoji.

type ReactionCount

type ReactionCount struct {
	// Type of the reaction.
	Type Reaction `json:"type"`

	// Number of times the reaction was added.
	Count int `json:"total_count"`
}

ReactionCount represents a reaction added to a message along with the number of times it was added.

type Reactions

type Reactions struct {
	// List of reaction types to set on the message.
	Reactions []Reaction `json:"reaction"`

	// Pass True to set the reaction with a big animation.
	Big bool `json:"is_big"`
}

Reactions represents an object of reaction options.

type Recipient

type Recipient interface {
	Recipient() string // must return legit Telegram chat_id or username
}

Recipient is any possible endpoint you can send messages to: either user, group or a channel.

type RecipientShared

type RecipientShared struct {
	ID       int32  `json:"request_id"` // chat, users
	ChatID   int64  `json:"chat_id"`    // chat only
	Title    string `json:"title"`      // chat only
	Username string `json:"username"`   // chat only
	Photo    *Photo `json:"photo"`      // chat only

	Users []struct {
		UserID    int64  `json:"user_id"`
		FirstName string `json:"first_name"`
		LastName  string `json:"last_name"`
		Username  string `json:"username"`
		Photo     *Photo `json:"photo"`
	} `json:"users"` // users only

}

RecipientShared combines both UserShared and ChatShared objects.

type RefundedPayment

type RefundedPayment struct {
	Currency         string `json:"currency"`
	Total            int    `json:"total_amount"`
	Payload          string `json:"invoice_payload"`
	TelegramChargeID string `json:"telegram_payment_charge_id"`
	ProviderChargeID string `json:"provider_payment_charge_id"`
}

type ReplyButton

type ReplyButton struct {
	Text              string      `json:"text"`
	IconCustomEmojiID string      `json:"icon_custom_emoji_id,omitempty"`
	Style             ButtonStyle `json:"style,omitempty"`

	Contact  bool            `json:"request_contact,omitempty"`
	Location bool            `json:"request_location,omitempty"`
	Poll     PollType        `json:"request_poll,omitempty"`
	User     *ReplyRecipient `json:"request_users,omitempty"`
	Chat     *ReplyRecipient `json:"request_chat,omitempty"`
	WebApp   *WebApp         `json:"web_app,omitempty"`
}

ReplyButton represents a button displayed in reply-keyboard.

Set either Contact or Location to true in order to request sensitive info, such as user's phone number or current location.

func (*ReplyButton) CallbackUnique

func (t *ReplyButton) CallbackUnique() string

CallbackUnique returns ReplyButton.Text.

type ReplyMarkup

type ReplyMarkup struct {
	// InlineKeyboard is a grid of InlineButtons displayed in the message.
	//
	// Note: DO NOT confuse with ReplyKeyboard and other keyboard properties!
	InlineKeyboard [][]InlineButton `json:"inline_keyboard,omitempty"`

	// ReplyKeyboard is a grid, consisting of keyboard buttons.
	//
	// Note: you don't need to set HideCustomKeyboard field to show custom keyboard.
	ReplyKeyboard [][]ReplyButton `json:"keyboard,omitempty"`

	// ForceReply forces Telegram clients to display
	// a reply interface to the user (act as if the user
	// has selected the bot‘s message and tapped "Reply").
	ForceReply bool `json:"force_reply,omitempty"`

	// Requests clients to resize the keyboard vertically for optimal fit
	// (e.g. make the keyboard smaller if there are just two rows of buttons).
	//
	// Defaults to false, in which case the custom keyboard is always of the
	// same height as the app's standard keyboard.
	ResizeKeyboard bool `json:"resize_keyboard,omitempty"`

	// Requests clients to hide the reply keyboard as soon as it's been used.
	//
	// Defaults to false.
	OneTimeKeyboard bool `json:"one_time_keyboard,omitempty"`

	// Requests clients to remove the reply keyboard.
	//
	// Defaults to false.
	RemoveKeyboard bool `json:"remove_keyboard,omitempty"`

	// Use this param if you want to force reply from
	// specific users only.
	//
	// Targets:
	// 1) Users that are @mentioned in the text of the Message object;
	// 2) If the bot's message is a reply (has SendOptions.ReplyTo),
	//       sender of the original message.
	Selective bool `json:"selective,omitempty"`

	// Placeholder will be shown in the input field when the reply is active.
	Placeholder string `json:"input_field_placeholder,omitempty"`

	// IsPersistent allows to control when the keyboard is shown.
	IsPersistent bool `json:"is_persistent,omitempty"`
}

ReplyMarkup controls two convenient options for bot-user communications such as reply keyboard and inline "keyboard" (a grid of buttons as a part of the message).

func (*ReplyMarkup) Chat

func (r *ReplyMarkup) Chat(text string, chat *ReplyRecipient) Btn

func (*ReplyMarkup) Contact

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

func (*ReplyMarkup) CopyText

func (r *ReplyMarkup) CopyText(text, copyText string) Btn

func (*ReplyMarkup) Data

func (r *ReplyMarkup) Data(text, unique string, data ...string) Btn

func (*ReplyMarkup) Inline

func (r *ReplyMarkup) Inline(rows ...Row)

func (*ReplyMarkup) Location

func (r *ReplyMarkup) Location(text string) Btn

func (*ReplyMarkup) Login

func (r *ReplyMarkup) Login(text string, login *Login) Btn

func (*ReplyMarkup) Poll

func (r *ReplyMarkup) Poll(text string, poll PollType) Btn

func (*ReplyMarkup) Query

func (r *ReplyMarkup) Query(text, query string) Btn

func (*ReplyMarkup) QueryChat

func (r *ReplyMarkup) QueryChat(text, query string) Btn

func (*ReplyMarkup) Reply

func (r *ReplyMarkup) Reply(rows ...Row)

func (*ReplyMarkup) Row

func (r *ReplyMarkup) Row(many ...Btn) Row

Row creates a row of buttons.

func (*ReplyMarkup) Split

func (r *ReplyMarkup) Split(max int, btns []Btn) []Row

Split splits the keyboard into the rows with N maximum number of buttons. For example, if you pass six buttons and 3 as the max, you get two rows with three buttons in each.

`Split(3, []Btn{six buttons...}) -> [[1, 2, 3], [4, 5, 6]]` `Split(2, []Btn{six buttons...}) -> [[1, 2],[3, 4],[5, 6]]`

func (*ReplyMarkup) Text

func (r *ReplyMarkup) Text(text string) Btn

func (*ReplyMarkup) URL

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

func (*ReplyMarkup) User

func (r *ReplyMarkup) User(text string, user *ReplyRecipient) Btn

func (*ReplyMarkup) WebApp

func (r *ReplyMarkup) WebApp(text string, app *WebApp) Btn

type ReplyParams

type ReplyParams struct {
	// Identifier of the message that will be replied to in the current chat,
	// or in the chat chat_id if it is specified.
	MessageID int `json:"message_id"`

	// (Optional) If the message to be replied to is from a different chat,
	// unique identifier for the chat or username of the channel.
	ChatID int64 `json:"chat_id"`

	// Optional. Pass True if the message should be sent even if the specified message
	// to be replied to is not found; can be used only for replies in the
	// same chat and forum topic.
	AllowWithoutReply bool `json:"allow_sending_without_reply"`

	// (Optional) Quoted part of the message to be replied to; 0-1024 characters after
	// entities parsing. The quote must be an exact substring of the message to be replied to,
	// including bold, italic, underline, strikethrough, spoiler, and custom_emoji entities.
	// The message will fail to send if the quote isn't found in the original message.
	Quote string `json:"quote"`

	// (Optional) Mode for parsing entities in the quote.
	QuoteParseMode ParseMode `json:"quote_parse_mode"`

	// (Optional) A JSON-serialized list of special entities that appear in the quote.
	// It can be specified instead of quote_parse_mode.
	QuoteEntities []MessageEntity `json:"quote_entities"`

	// (Optional) Position of the quote in the original message in UTF-16 code units.
	QuotePosition int `json:"quote_position"`
}

ReplyParams describes reply parameters for the message that is being sent.

type ReplyRecipient

type ReplyRecipient struct {
	ID int32 `json:"request_id"`

	Bot      *bool `json:"user_is_bot,omitempty"`     // user only, optional
	Premium  *bool `json:"user_is_premium,omitempty"` // user only, optional
	Quantity int   `json:"max_quantity,omitempty"`    // user only, optional

	Channel         bool    `json:"chat_is_channel,omitempty"`           // chat only, required
	Forum           *bool   `json:"chat_is_forum,omitempty"`             // chat only, optional
	WithUsername    *bool   `json:"chat_has_username,omitempty"`         // chat only, optional
	Created         *bool   `json:"chat_is_created,omitempty"`           // chat only, optional
	UserRights      *Rights `json:"user_administrator_rights,omitempty"` // chat only, optional
	BotRights       *Rights `json:"bot_administrator_rights,omitempty"`  // chat only, optional
	BotMember       *bool   `json:"bot_is_member,omitempty"`             // chat only, optional
	RequestTitle    *bool   `json:"request_title,omitempty"`             // chat only, optional
	RequestName     *bool   `json:"request_name,omitempty"`              // user only, optional
	RequestUsername *bool   `json:"request_username,omitempty"`          // user only, optional
	RequestPhoto    *bool   `json:"request_photo,omitempty"`             // user only, optional
}

ReplyRecipient combines both KeyboardButtonRequestUser and KeyboardButtonRequestChat objects. Use inside ReplyButton to request the user or chat sharing with respective settings.

To pass the pointers to bool use a special tele.Flag function, that way you will be able to reflect the three-state bool (nil, false, true).

type Result

type Result interface {
	ResultID() string
	SetResultID(string)
	SetParseMode(ParseMode)
	SetContent(InputMessageContent)
	SetReplyMarkup(*ReplyMarkup)
	Process(*Bot)
}

Result represents one result of an inline query.

type ResultBase

type ResultBase struct {
	// Unique identifier for this result, 1-64 Bytes.
	// If left unspecified, a 64-bit FNV-1 hash will be calculated
	ID string `json:"id"`

	// Ignore. This field gets set automatically.
	Type string `json:"type"`

	// Optional. Send Markdown or HTML, if you want Telegram apps to show
	// bold, italic, fixed-width text or inline URLs in the media caption.
	ParseMode ParseMode `json:"parse_mode,omitempty"`

	// Optional. Content of the message to be sent.
	Content InputMessageContent `json:"input_message_content,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup *ReplyMarkup `json:"reply_markup,omitempty"`
}

ResultBase must be embedded into all IQRs.

func (*ResultBase) Process

func (r *ResultBase) Process(b *Bot)

func (*ResultBase) ResultID

func (r *ResultBase) ResultID() string

ResultID returns ResultBase.ID.

func (*ResultBase) SetContent

func (r *ResultBase) SetContent(content InputMessageContent)

SetContent sets ResultBase.Content.

func (*ResultBase) SetParseMode

func (r *ResultBase) SetParseMode(mode ParseMode)

SetParseMode sets ResultBase.ParseMode.

func (*ResultBase) SetReplyMarkup

func (r *ResultBase) SetReplyMarkup(markup *ReplyMarkup)

SetReplyMarkup sets ResultBase.ReplyMarkup.

func (*ResultBase) SetResultID

func (r *ResultBase) SetResultID(id string)

SetResultID sets ResultBase.ID.

type Results

type Results []Result

Results is a slice wrapper for convenient marshalling.

func (Results) MarshalJSON

func (results Results) MarshalJSON() ([]byte, error)

MarshalJSON makes sure IQRs have proper IDs and Type variables set.

type RevenueState

type RevenueState = string
const (
	RevenueStatePending   RevenueState = "pending"
	RevenueStateSucceeded RevenueState = "succeeded"
	RevenueStateFailed    RevenueState = "failed"
)

type RevenueWithdrawal

type RevenueWithdrawal struct {
	// Type of the state
	Type RevenueState `json:"type"`

	// Date the withdrawal was completed in Unix time
	Unixtime int `json:"date,omitempty"`

	// An HTTPS URL that can be used to see transaction details
	URL string `json:"url,omitempty"`
}

func (*RevenueWithdrawal) Time

func (s *RevenueWithdrawal) Time() time.Time

Time returns the date of the withdrawal.

type RichBlock

type RichBlock struct {
	// Type is the block discriminator (see the RichBlock* constants).
	Type string `json:"type"`

	// Text is the block's formatted text (paragraph, heading, pre, footer,
	// pullquote, thinking).
	Text *RichText `json:"text,omitempty"`

	// Size is the heading level, 1 (largest) to 6 (smallest).
	Size int `json:"size,omitempty"`

	// Language is the optional source language of a "pre" block.
	Language string `json:"language,omitempty"`

	// Expression is the LaTeX of a "mathematical_expression" block.
	Expression string `json:"expression,omitempty"`

	// Name is the identifier of an "anchor" block.
	Name string `json:"name,omitempty"`

	// Items are the entries of a "list" block.
	Items []RichBlockListItem `json:"items,omitempty"`

	// Blocks are the nested blocks of a blockquote, collage, slideshow or
	// details block.
	Blocks []RichBlock `json:"blocks,omitempty"`

	// Summary is the disclosure summary of a "details" block.
	Summary *RichText `json:"summary,omitempty"`

	// IsOpen reports whether a "details" block is expanded by default.
	IsOpen bool `json:"is_open,omitempty"`

	// Credit is the attribution of a blockquote or pullquote block.
	Credit *RichText `json:"credit,omitempty"`

	// Cells are the rows-by-columns of a "table" block.
	Cells [][]RichBlockTableCell `json:"cells,omitempty"`

	// IsBordered and IsStriped style a "table" block.
	IsBordered bool `json:"is_bordered,omitempty"`
	IsStriped  bool `json:"is_striped,omitempty"`

	// Location, Zoom, Width and Height describe a "map" block.
	Location *Location `json:"location,omitempty"`
	Zoom     int       `json:"zoom,omitempty"`
	Width    int       `json:"width,omitempty"`
	Height   int       `json:"height,omitempty"`

	// Media of the corresponding block type.
	Animation *Animation `json:"animation,omitempty"`
	Audio     *Audio     `json:"audio,omitempty"`
	Photo     []Photo    `json:"photo,omitempty"`
	Video     *Video     `json:"video,omitempty"`
	VoiceNote *Voice     `json:"voice_note,omitempty"`

	// HasSpoiler marks an animation, photo or video block as a spoiler.
	HasSpoiler bool `json:"has_spoiler,omitempty"`

	// Caption is the caption of a collage, slideshow, map, animation, audio,
	// photo, video or voice-note block.
	Caption *RichBlockCaption `json:"-"`

	// TableCaption is the caption of a "table" block (a bare RichText rather
	// than a RichBlockCaption).
	TableCaption *RichText `json:"-"`
}

RichBlock is a single block of a received RichMessage (Bot API 10.1). It is a polymorphic type discriminated by Type; only the fields relevant to a given Type are populated. RichBlock is a received-only type.

func (*RichBlock) UnmarshalJSON

func (rb *RichBlock) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a RichBlock, resolving the polymorphic "caption" field: a table carries a bare RichText caption, every other block a RichBlockCaption.

type RichBlockCaption

type RichBlockCaption struct {
	// Text of the caption.
	Text RichText `json:"text"`

	// (Optional) Attribution shown alongside the caption.
	Credit *RichText `json:"credit,omitempty"`
}

RichBlockCaption is the caption of a media or container rich block.

type RichBlockListItem

type RichBlockListItem struct {
	// Label is the rendered bullet or number of the item.
	Label string `json:"label,omitempty"`

	// Blocks is the content of the item.
	Blocks []RichBlock `json:"blocks,omitempty"`

	// HasCheckbox and IsChecked render a task-list item.
	HasCheckbox bool `json:"has_checkbox,omitempty"`
	IsChecked   bool `json:"is_checked,omitempty"`

	// Value is the ordinal of an ordered-list item.
	Value int `json:"value,omitempty"`

	// Type is the label style of an ordered item ("a", "A", "i", "I", "1").
	Type string `json:"type,omitempty"`
}

RichBlockListItem is a single entry of a "list" rich block.

type RichBlockTableCell

type RichBlockTableCell struct {
	Text     *RichText `json:"text,omitempty"`
	IsHeader bool      `json:"is_header,omitempty"`
	Colspan  int       `json:"colspan,omitempty"`
	Rowspan  int       `json:"rowspan,omitempty"`
	Align    string    `json:"align,omitempty"`  // "left", "center", "right"
	VAlign   string    `json:"valign,omitempty"` // "top", "middle", "bottom"
}

RichBlockTableCell is a single cell of a "table" rich block. An omitted Text denotes an invisible cell spanned into by a neighbour.

type RichMessage

type RichMessage struct {
	// Content of the message, as an ordered list of blocks.
	Blocks []RichBlock `json:"blocks"`

	// (Optional) True if the message must be shown right-to-left.
	IsRTL bool `json:"is_rtl,omitempty"`
}

RichMessage represents a received rich formatted message (Bot API 10.1), available on Message.RichMessage. Its content is a tree of RichBlock values.

type RichText

type RichText struct {
	// Kind is the wire form this value was decoded from.
	Kind RichTextKind `json:"-"`

	// Plain holds the text when Kind is RichTextPlain.
	Plain string `json:"-"`

	// Parts holds the run when Kind is RichTextArray.
	Parts []RichText `json:"-"`

	// Type is the entity discriminator when Kind is RichTextEntity.
	Type string `json:"type,omitempty"`

	// Text is the nested, formatted text of the entity (most entity types).
	Text *RichText `json:"text,omitempty"`

	// URL is the target of a "url" entity.
	URL string `json:"url,omitempty"`

	// EmailAddress is the address of an "email_address" entity.
	EmailAddress string `json:"email_address,omitempty"`

	// PhoneNumber is the number of a "phone_number" entity.
	PhoneNumber string `json:"phone_number,omitempty"`

	// BankCardNumber is the number of a "bank_card_number" entity.
	BankCardNumber string `json:"bank_card_number,omitempty"`

	// Username is the @username of a "mention" entity.
	Username string `json:"username,omitempty"`

	// Hashtag is the tag of a "hashtag" entity.
	Hashtag string `json:"hashtag,omitempty"`

	// Cashtag is the tag of a "cashtag" entity.
	Cashtag string `json:"cashtag,omitempty"`

	// BotCommand is the command of a "bot_command" entity.
	BotCommand string `json:"bot_command,omitempty"`

	// User is the mentioned user of a "text_mention" entity.
	User *User `json:"user,omitempty"`

	// UnixTime is the moment of a "date_time" entity, in Unix time.
	UnixTime int64 `json:"unix_time,omitempty"`

	// DateTimeFormat is the rendering format of a "date_time" entity.
	DateTimeFormat string `json:"date_time_format,omitempty"`

	// CustomEmojiID is the identifier of a "custom_emoji" entity.
	CustomEmojiID string `json:"custom_emoji_id,omitempty"`

	// AlternativeText is the fallback text of a "custom_emoji" entity.
	AlternativeText string `json:"alternative_text,omitempty"`

	// Expression is the LaTeX of a "mathematical_expression" entity.
	Expression string `json:"expression,omitempty"`

	// Name is the identifier of an "anchor" or "reference" entity.
	Name string `json:"name,omitempty"`

	// AnchorName is the target of an "anchor_link" entity (empty = top).
	AnchorName string `json:"anchor_name,omitempty"`

	// ReferenceName is the target of a "reference_link" entity.
	ReferenceName string `json:"reference_name,omitempty"`
}

RichText is a polymorphic piece of rich-formatted text (Bot API 10.1). On the wire it is one of: a plain string, an array of RichText, or a tagged object carrying a "type" discriminator and a (usually nested) text. Kind reports which form was decoded; the relevant fields are populated accordingly.

RichText is a received-only type — rich content is sent as HTML or Markdown via InputRichMessage, never as a block tree.

func (RichText) String

func (r RichText) String() string

String renders the RichText as plain text, recursively flattening arrays and entities. Entities without textual content (anchors, dividers) contribute nothing; custom emoji contribute their alternative text.

func (*RichText) UnmarshalJSON

func (r *RichText) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the string, array and tagged-object forms of RichText.

type RichTextKind

type RichTextKind int

RichTextKind tells which of the three wire forms a RichText holds.

const (
	// RichTextPlain is a bare string of plain text.
	RichTextPlain RichTextKind = iota

	// RichTextArray is an ordered run of RichText values (mixed formatting).
	RichTextArray

	// RichTextEntity is a single tagged formatting entity (see RichText.Type).
	RichTextEntity
)

type Rights

type Rights struct {
	// Anonymous is true, if the user's presence in the chat is hidden.
	Anonymous bool `json:"is_anonymous"`

	CanBeEdited         bool `json:"can_be_edited"`
	CanChangeInfo       bool `json:"can_change_info"`
	CanPostMessages     bool `json:"can_post_messages"`
	CanEditMessages     bool `json:"can_edit_messages"`
	CanDeleteMessages   bool `json:"can_delete_messages"`
	CanPinMessages      bool `json:"can_pin_messages"`
	CanInviteUsers      bool `json:"can_invite_users"`
	CanRestrictMembers  bool `json:"can_restrict_members"`
	CanPromoteMembers   bool `json:"can_promote_members"`
	CanSendMessages     bool `json:"can_send_messages"`
	CanSendPolls        bool `json:"can_send_polls"`
	CanSendOther        bool `json:"can_send_other_messages"`
	CanAddPreviews      bool `json:"can_add_web_page_previews"`
	CanManageVideoChats bool `json:"can_manage_video_chats"`
	CanManageChat       bool `json:"can_manage_chat"`
	CanManageTopics     bool `json:"can_manage_topics"`

	CanSendMedia      bool `json:"can_send_media_messages,omitempty"` // deprecated
	CanSendAudios     bool `json:"can_send_audios"`
	CanSendDocuments  bool `json:"can_send_documents"`
	CanSendPhotos     bool `json:"can_send_photos"`
	CanSendVideos     bool `json:"can_send_videos"`
	CanSendVideoNotes bool `json:"can_send_video_notes"`
	CanSendVoiceNotes bool `json:"can_send_voice_notes"`

	CanPostStories   bool `json:"can_post_stories"`
	CanEditStories   bool `json:"can_edit_stories"`
	CanDeleteStories bool `json:"can_delete_stories"`

	// Bot API 9.5: administrator right (ChatAdministratorRights / promoteChatMember).
	CanManageTags bool `json:"can_manage_tags"`

	// Bot API 9.5: restricted member permission (ChatPermissions).
	CanEditTag bool `json:"can_edit_tag"`

	// Independent defines whether the chat permissions are set independently.
	// If not, the can_send_other_messages and can_add_web_page_previews permissions
	// will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos,
	// can_send_videos, can_send_video_notes, and can_send_voice_notes permissions;
	// the can_send_polls permission will imply the can_send_messages permission.
	//
	// Works for Restrict and SetGroupPermissions methods only.
	Independent bool `json:"-"`
}

Rights is a list of privileges available to chat members.

func AdminRights

func AdminRights() Rights

AdminRights could be used to promote user to admin.

func NoRestrictions

func NoRestrictions() Rights

NoRestrictions should be used when un-restricting or un-promoting user.

member.Rights = tele.NoRestrictions()
b.Restrict(chat, member)

func NoRights

func NoRights() Rights

NoRights is the default Rights{}.

type Row

type Row []Btn

Row represents an array of buttons, a row.

type SQLStore

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

SQLStore is the default Store, backed by bun on SQLite or Postgres.

func NewSQLStore

func NewSQLStore(db *bun.DB) *SQLStore

NewSQLStore wraps an open database. Call Migrate once before using it.

func (*SQLStore) AccountByID

func (s *SQLStore) AccountByID(ctx context.Context, id int64) (*Account, error)

func (*SQLStore) AccountByTelegramID

func (s *SQLStore) AccountByTelegramID(ctx context.Context, telegramID int64) (*Account, error)

func (*SQLStore) DB

func (s *SQLStore) DB() *bun.DB

DB returns the underlying database handle.

func (*SQLStore) LoadSession

func (s *SQLStore) LoadSession(ctx context.Context, chatID int64) ([]byte, error)

func (*SQLStore) Migrate

func (s *SQLStore) Migrate(ctx context.Context) error

Migrate creates or upgrades the framework's tables.

func (*SQLStore) SaveSession

func (s *SQLStore) SaveSession(ctx context.Context, chatID int64, payload []byte) error

func (*SQLStore) SetAccountLanguage

func (s *SQLStore) SetAccountLanguage(ctx context.Context, accountID int64, lang string) error

func (*SQLStore) UpsertAccount

func (s *SQLStore) UpsertAccount(ctx context.Context, a *Account) error

type Scene

type Scene int

Scene groups the steps of a multi-message conversation flow (a "wizard"), such as "top up" or "deploy". Zero means "no scene": the user is at the main menu and free text goes to the default text handler.

type SceneRouter

type SceneRouter[T any] struct {
	// contains filtered or unexported fields
}

SceneRouter dispatches the text messages of one scene by question.

func (*SceneRouter[T]) Default

func (r *SceneRouter[T]) Default(h Handler[T]) *SceneRouter[T]

Default handles the scene's questions that have no handler of their own.

func (*SceneRouter[T]) On

func (r *SceneRouter[T]) On(q Question, h Handler[T]) *SceneRouter[T]

On registers the handler answering question q.

type SendOptions

type SendOptions struct {
	// If the message is a reply, original message.
	ReplyTo *Message

	// See ReplyMarkup struct definition.
	ReplyMarkup *ReplyMarkup

	// For text messages, disables previews for links in this message.
	DisableWebPagePreview bool

	// Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.
	DisableNotification bool

	// ParseMode controls how client apps render your message. When left as
	// ModeDefault, the bot's Settings.ParseMode applies. To send one message
	// without any parse mode on a bot that has one, pass ModeDefault as a
	// separate option after the SendOptions: b.Send(to, text, opts, ModeDefault).
	ParseMode ParseMode

	// Entities is a list of special entities that appear in message text, which can be specified instead of parse_mode.
	Entities Entities

	// AllowWithoutReply allows sending messages not a as reply if the replied-to message has already been deleted.
	AllowWithoutReply bool

	// Protected protects the contents of sent message from forwarding and saving.
	Protected bool

	// ThreadID supports sending messages to a thread.
	ThreadID int

	// HasSpoiler marks the message as containing a spoiler.
	HasSpoiler bool

	// ReplyParams Describes the message to reply to
	ReplyParams *ReplyParams

	// Unique identifier of the business connection
	BusinessConnectionID string

	// Unique identifier of the message effect to be added to the message; for private chats only
	EffectID string

	// Payload is a bot-defined paid media payload, returned in the PaidMediaPurchased update.
	// 0-128 characters. Used only for sendPaidMedia.
	Payload string

	// AllowPaidBroadcast allows the message to be sent to users who have not yet
	// unlocked access to paid channels. Only for messages sent to channels.
	AllowPaidBroadcast bool
}

SendOptions has most complete control over in what way the message must be sent, providing an API-complete set of custom properties and options.

Despite its power, SendOptions is rather inconvenient to use all the way through bot logic, so you might want to consider storing and re-using it somewhere or be using Option flags instead.

func Placeholder

func Placeholder(text string) *SendOptions

Placeholder is used to set input field placeholder as a send option.

type Sendable

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

Sendable is any object that can send itself.

This is pretty cool, since it lets bots implement custom Sendables for complex kind of media or chat objects spanning across multiple messages.

type SentGuestMessage

type SentGuestMessage struct {
	InlineMessageID string `json:"inline_message_id"`
}

SentGuestMessage describes an inline message sent by a guest bot.

type Session

type Session[T any] struct {
	ChatID int64 `json:"chat_id"`

	// UID is the database ID of the account (accounts.id) behind this chat.
	// It is filled automatically the first time the chat talks to the bot.
	UID int64 `json:"uid,omitempty"`

	Scene    Scene    `json:"scene,omitempty"`
	Question Question `json:"question,omitempty"`
	Language string   `json:"language,omitempty"`

	// KeyboardMsgID is the last message sent with an inline keyboard; the
	// Clean* helpers use it to strip, edit or delete that message.
	KeyboardMsgID int `json:"keyboard_msg_id,omitempty"`

	// State holds the app-specific session data.
	State T `json:"state"`
}

Session is the per-chat conversation state. The framework owns the core fields; the app adds its own state through the type parameter T (any JSON-serializable struct), reachable as State.

Sessions are cached in memory and written through to the database whenever a handler changes them, so they survive restarts.

func (*Session[T]) Enter

func (s *Session[T]) Enter(scene Scene, q Question)

Enter is a shortcut for SetScene followed by SetNextQuestion.

func (*Session[T]) GetCurrentQuestion

func (s *Session[T]) GetCurrentQuestion() Question

GetCurrentQuestion returns the current question of the scene.

func (*Session[T]) GetLanguage

func (s *Session[T]) GetLanguage() string

GetLanguage returns the chat's language code ("" when not chosen yet).

func (*Session[T]) GetPreviousMessageWithKeyboard

func (s *Session[T]) GetPreviousMessageWithKeyboard() int

GetPreviousMessageWithKeyboard returns the ID of the last message sent with an inline keyboard through the Clean* helpers.

func (*Session[T]) GetScene

func (s *Session[T]) GetScene() Scene

GetScene returns the current scene.

func (*Session[T]) ID

func (s *Session[T]) ID() int64

ID returns the Telegram chat ID the session belongs to.

func (*Session[T]) IncQuestion

func (s *Session[T]) IncQuestion()

IncQuestion advances to the next question.

func (*Session[T]) ResetScene

func (s *Session[T]) ResetScene()

ResetScene leaves any scene, returning the chat to the main menu.

func (*Session[T]) SetNextQuestion

func (s *Session[T]) SetNextQuestion(q Question)

SetNextQuestion sets the question the next text message answers.

func (*Session[T]) SetPreviousMessageWithKeyboard

func (s *Session[T]) SetPreviousMessageWithKeyboard(id int)

SetPreviousMessageWithKeyboard records the last message that carries an inline keyboard.

func (*Session[T]) SetScene

func (s *Session[T]) SetScene(scene Scene)

SetScene moves the chat into a scene and resets the question to the scene's entry point.

func (*Session[T]) SetUserID

func (s *Session[T]) SetUserID(id int64)

SetUserID sets the database ID (accounts.id) of the user behind the chat.

func (*Session[T]) UserID

func (s *Session[T]) UserID() int64

UserID returns the database ID (accounts.id) of the user behind the chat.

type SessionStore

type SessionStore[T any] struct {
	// contains filtered or unexported fields
}

SessionStore is a write-through cache of sessions: reads are served from memory, every change is persisted to the Store, and a chat missing from the cache (e.g. after a restart) is loaded from the Store on first access.

It also hands out a per-chat lock so updates from the same chat are handled one at a time, which keeps scene transitions consistent even though the bot processes updates concurrently.

func NewSessionStore

func NewSessionStore[T any](store Store) *SessionStore[T]

NewSessionStore creates a SessionStore backed by store.

func (*SessionStore[T]) Forget

func (ss *SessionStore[T]) Forget(chatID int64)

Forget drops a chat from the in-memory cache; the next Get reloads it from the Store.

func (*SessionStore[T]) Get

func (ss *SessionStore[T]) Get(ctx context.Context, chatID int64) (*Session[T], error)

Get returns the session of a chat, loading it from the Store or creating a fresh one when needed. The returned pointer is shared: hold the chat's Lock while mutating it.

func (*SessionStore[T]) Len

func (ss *SessionStore[T]) Len() int

Len returns the number of cached sessions.

func (*SessionStore[T]) Lock

func (ss *SessionStore[T]) Lock(chatID int64) (unlock func())

Lock serializes work for one chat. Call the returned function to release.

func (*SessionStore[T]) Save

func (ss *SessionStore[T]) Save(ctx context.Context, s *Session[T]) error

Save persists a session unconditionally.

func (*SessionStore[T]) Snapshot

func (ss *SessionStore[T]) Snapshot(s *Session[T]) []byte

Snapshot returns the JSON encoding of a session, used to detect changes.

type Settings

type Settings struct {
	URL   string
	Token string

	// Updates channel capacity, defaulted to 100.
	Updates int

	// Poller is the provider of Updates.
	Poller Poller

	// Synchronous prevents handlers from running in parallel.
	// It makes ProcessUpdate return after the handler is finished.
	Synchronous bool

	// Verbose forces bot to log all upcoming requests.
	// Use for debugging purposes only.
	Verbose bool

	// ParseMode used to set default parse mode of all sent messages.
	// It attaches to every send, edit or whatever method. You also
	// will be able to override the default mode by passing a new one.
	ParseMode ParseMode

	// OnError is a callback function that will get called on errors
	// resulted from the handler. It is used as post-middleware function.
	// Notice that context can be nil.
	OnError func(error, Context)

	// HTTP Client used to make requests to telegram api
	Client *http.Client

	// Offline allows to create a bot without network for testing purposes.
	Offline bool
}

Settings represents a utility struct for passing certain properties of a bot around and is required to make bots.

type ShippingAddress

type ShippingAddress struct {
	CountryCode string `json:"country_code"`
	State       string `json:"state"`
	City        string `json:"city"`
	StreetLine1 string `json:"street_line1"`
	StreetLine2 string `json:"street_line2"`
	PostCode    string `json:"post_code"`
}

ShippingAddress represents a shipping address.

type ShippingOption

type ShippingOption struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Prices []Price `json:"prices"`
}

ShippingOption represents one shipping option.

type ShippingQuery

type ShippingQuery struct {
	Sender  *User           `json:"from"`
	ID      string          `json:"id"`
	Payload string          `json:"invoice_payload"`
	Address ShippingAddress `json:"shipping_address"`
}

ShippingQuery contains information about an incoming shipping query.

type StarTransaction

type StarTransaction struct {
	// Unique identifier of the transaction. Coincides with the identifier of the
	// original transaction for refund transactions. Coincides with
	// SuccessfulPayment.telegram_payment_charge_id for successful incoming
	// payments from users.
	ID string `json:"id"`

	// Number of Telegram Stars transferred by the transaction
	Amount int `json:"amount"`

	// (Optional) The number of 0.00000001 TON that were transferred by the transaction
	NanostarAmount int `json:"nanostar_amount,omitempty"`

	// Date the transaction was created in Unix time
	Unixtime int64 `json:"date"`

	// (Optional) Source of an incoming transaction (e.g., a user purchasing goods
	// or services, Fragment refunding a failed withdrawal). Only for incoming transactions
	Source TransactionPartner `json:"source"`

	// (Optional) Receiver of an outgoing transaction (e.g., a user for a purchase
	// refund, Fragment for a withdrawal). Only for outgoing transactions
	Receiver TransactionPartner `json:"receiver"`
}

func (*StarTransaction) HasNanostarAmount

func (c *StarTransaction) HasNanostarAmount() bool

HasNanostarAmount returns whether the transaction has a nanostar amount.

func (*StarTransaction) NanostarAmountAsTON

func (c *StarTransaction) NanostarAmountAsTON() float64

NanostarAmountAsTON returns the nanostar amount as TON value.

func (*StarTransaction) Time

func (c *StarTransaction) Time() time.Time

Time returns the date of the transaction.

type Sticker

type Sticker struct {
	File
	Type             StickerSetType `json:"type"`
	Width            int            `json:"width"`
	Height           int            `json:"height"`
	Animated         bool           `json:"is_animated"`
	Video            bool           `json:"is_video"`
	Thumbnail        *Photo         `json:"thumbnail"`
	Emoji            string         `json:"emoji"`
	SetName          string         `json:"set_name"`
	PremiumAnimation *File          `json:"premium_animation"`
	MaskPosition     *MaskPosition  `json:"mask_position"`
	CustomEmojiID    string         `json:"custom_emoji_id"`
	Repaint          bool           `json:"needs_repainting"`
}

Sticker object represents a WebP image, so-called sticker.

func (*Sticker) MediaFile

func (s *Sticker) MediaFile() *File

func (*Sticker) MediaType

func (s *Sticker) MediaType() string

func (*Sticker) Send

func (s *Sticker) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers media through bot b to recipient.

type StickerResult

type StickerResult struct {
	ResultBase

	// If Cache != "", it'll be used instead
	Cache string `json:"sticker_file_id,omitempty"`
}

StickerResult represents an inline cached sticker response.

type StickerSet

type StickerSet struct {
	Type          StickerSetType   `json:"sticker_type"`
	Format        StickerSetFormat `json:"sticker_format"`
	Name          string           `json:"name"`
	Title         string           `json:"title"`
	Stickers      []Sticker        `json:"stickers"`
	Thumbnail     *Photo           `json:"thumbnail"`
	Emojis        string           `json:"emojis"`
	ContainsMasks bool             `json:"contains_masks"` // FIXME: can be removed
	MaskPosition  *MaskPosition    `json:"mask_position"`
	Repaint       bool             `json:"needs_repainting"`

	// Input is a field used in createNewStickerSet method to specify a list
	// of pre-defined stickers of type InputSticker to add to the set.
	Input []InputSticker
}

StickerSet represents a sticker set.

type StickerSetFormat

type StickerSetFormat = string
const (
	StickerStatic   StickerSetFormat = "static"
	StickerAnimated StickerSetFormat = "animated"
	StickerVideo    StickerSetFormat = "video"
)

type StickerSetType

type StickerSetType = string
const (
	StickerRegular     StickerSetType = "regular"
	StickerMask        StickerSetType = "mask"
	StickerCustomEmoji StickerSetType = "custom_emoji"
)

type Store

type Store interface {
	// LoadSession returns the JSON payload saved for a chat, or ErrRecordNotFound.
	LoadSession(ctx context.Context, chatID int64) ([]byte, error)
	// SaveSession upserts the JSON payload of a chat's session.
	SaveSession(ctx context.Context, chatID int64, payload []byte) error

	// UpsertAccount inserts the account or, when one with the same
	// TelegramID exists, refreshes its profile fields. a.ID is set on return.
	UpsertAccount(ctx context.Context, a *Account) error
	AccountByID(ctx context.Context, id int64) (*Account, error)
	AccountByTelegramID(ctx context.Context, telegramID int64) (*Account, error)
	SetAccountLanguage(ctx context.Context, accountID int64, lang string) error
}

Store persists the framework's own data: accounts and chat sessions. The default implementation (NewSQLStore) works on SQLite and Postgres; a custom one can be passed with WithStore.

type StoredMessage

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

StoredMessage is an example struct suitable for being stored in the database as-is or being embedded into a larger struct, which is often the case (you might want to store some metadata alongside, or might not.)

func (StoredMessage) MessageSig

func (x StoredMessage) MessageSig() (string, int64)

type Story

type Story struct {
	// Unique identifier for the story in the chat
	ID int `json:"id"`

	// Chat that posted the story
	Poster *Chat `json:"chat"`
}

type SwitchInlineQuery

type SwitchInlineQuery struct {
	// (Optional) The default inline query to be inserted in the input field.
	// If left empty, only the bot's username will be inserted.
	Query string `json:"query"`

	// (Optional) True, if private chats with users can be chosen.
	AllowUserChats bool `json:"allow_user_chats"`

	// (Optional) True, if private chats with bots can be chosen.
	AllowBotChats bool `json:"allow_bot_chats"`

	// (Optional) True, if group and supergroup chats can be chosen.
	AllowGroupChats bool `json:"allow_group_chats"`

	// (Optional) True, if channel chats can be chosen.
	AllowChannelChats bool `json:"allow_channel_chats"`
}

SwitchInlineQuery represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query.

type TelegramConfig

type TelegramConfig struct {
	Token string `json:"token" validate:"required"`
	// URL overrides the Bot API server, e.g. a local telegram-bot-api.
	URL string `json:"url"`
	// PollerTimeout is the long-polling timeout.
	PollerTimeout time.Duration `json:"poller_timeout" default:"10s"`
}

TelegramConfig configures the Bot API connection.

type TextQuote

type TextQuote struct {
	// Text of the quoted part of a message that is replied to by the given message.
	Text string `json:"text"`

	// (Optional) Special entities that appear in the quote.
	// Currently, only bold, italic, underline, strikethrough, spoiler,
	// and custom_emoji entities are kept in quotes.
	Entities []MessageEntity `json:"entities"`

	// Approximate quote position in the original message in UTF-16 code units
	// as specified by the sender.
	Position int `json:"position"`

	// (Optional) True, if the quote was chosen manually by the message sender.
	// Otherwise, the quote was added automatically by the server.
	Manual bool `json:"is_manual"`
}

TextQuote contains information about the quoted part of a message that is replied to by the given message.

type Topic

type Topic struct {
	Name              string `json:"name"`
	IconColor         int    `json:"icon_color"`
	IconCustomEmojiID string `json:"icon_custom_emoji_id"`
	ThreadID          int    `json:"message_thread_id"`
}

type TransactionPartner

type TransactionPartner struct {
	// Type of the state
	Type    TransactionType `json:"type"`
	User    *User           `json:"user,omitempty"`
	Payload string          `json:"invoice_payload"`

	// (Optional) State of the transaction if the transaction is outgoing$$
	Withdrawal RevenueWithdrawal `json:"withdrawal_state,omitempty"`

	// Bot API 8.0: Star subscriptions
	SubscriptionPeriod int `json:"subscription_period,omitempty"`

	// Bot API 8.0: Gifts
	Gift *Gift `json:"gift,omitempty"`

	// Bot API 8.1: Information about the affiliate program from which the transaction was made
	Affiliate *AffiliateInfo `json:"affiliate,omitempty"`

	// Bot API 8.3: Information about the chat transaction partner
	Chat *TransactionPartnerChat `json:"chat,omitempty"`
}

type TransactionPartnerAffiliateProgram

type TransactionPartnerAffiliateProgram struct {
	// Type of the transaction partner, always "affiliate_program"
	Type TransactionType `json:"type"`

	// Sponsor of the affiliate program
	SponsorUser *User `json:"sponsor_user,omitempty"`

	// The number of Telegram Stars received by the bot for each 1000 Telegram Stars received by the affiliate program
	CommissionPerMille int `json:"commission_per_mille"`
}

TransactionPartnerAffiliateProgram describes the affiliate program that paid the transaction.

type TransactionPartnerChat

type TransactionPartnerChat struct {
	// Type of the transaction partner, always "chat"
	Type TransactionType `json:"type"`

	// Information about the chat
	Chat *Chat `json:"chat"`
}

TransactionPartnerChat describes a transaction partner that is a chat.

type TransactionType

type TransactionType = string
const (
	TransactionTypeUser             TransactionType = "user"
	TransactionTypeFragment         TransactionType = "fragment"
	TransactionPartnerTelegramAds   TransactionType = "telegram_ads"
	TransactionPartnerTelegramApi   TransactionType = "telegram_api"
	TransactionTypeAffiliateProgram TransactionType = "affiliate_program"
	TransactionTypeOther            TransactionType = "other"
	// Bot API 8.3: Transaction partner is a chat
	TransactionTypeChat TransactionType = "chat"
)

type Translations

type Translations map[string]string

Translations maps translation keys to localized templates for one language. Templates may contain {placeholders} that are filled by Replace / GetL8d.

type Update

type Update struct {
	ID int `json:"update_id"`

	Message                 *Message                 `json:"message,omitempty"`
	EditedMessage           *Message                 `json:"edited_message,omitempty"`
	ChannelPost             *Message                 `json:"channel_post,omitempty"`
	EditedChannelPost       *Message                 `json:"edited_channel_post,omitempty"`
	MessageReaction         *MessageReaction         `json:"message_reaction"`
	MessageReactionCount    *MessageReactionCount    `json:"message_reaction_count"`
	Callback                *Callback                `json:"callback_query,omitempty"`
	Query                   *Query                   `json:"inline_query,omitempty"`
	InlineResult            *InlineResult            `json:"chosen_inline_result,omitempty"`
	ShippingQuery           *ShippingQuery           `json:"shipping_query,omitempty"`
	PreCheckoutQuery        *PreCheckoutQuery        `json:"pre_checkout_query,omitempty"`
	Poll                    *Poll                    `json:"poll,omitempty"`
	PollAnswer              *PollAnswer              `json:"poll_answer,omitempty"`
	MyChatMember            *ChatMemberUpdate        `json:"my_chat_member,omitempty"`
	ChatMember              *ChatMemberUpdate        `json:"chat_member,omitempty"`
	ChatJoinRequest         *ChatJoinRequest         `json:"chat_join_request,omitempty"`
	Boost                   *BoostUpdated            `json:"chat_boost"`
	BoostRemoved            *BoostRemoved            `json:"removed_chat_boost"`
	BusinessConnection      *BusinessConnection      `json:"business_connection"`
	BusinessMessage         *Message                 `json:"business_message"`
	EditedBusinessMessage   *Message                 `json:"edited_business_message"`
	DeletedBusinessMessages *BusinessMessagesDeleted `json:"deleted_business_messages"`
	GuestMessage            *Message                 `json:"guest_message"`
	PurchasedPaidMedia      *PaidMediaPurchased      `json:"purchased_paid_media"`
}

Update object represents an incoming update.

type User

type User struct {
	ID int64 `json:"id"`

	FirstName           string   `json:"first_name"`
	LastName            string   `json:"last_name"`
	Username            string   `json:"username"`
	LanguageCode        string   `json:"language_code"`
	IsBot               bool     `json:"is_bot"`
	IsPremium           bool     `json:"is_premium"`
	AddedToMenu         bool     `json:"added_to_attachment_menu"`
	Usernames           []string `json:"active_usernames"`
	StatusCustomEmojiID string   `json:"emoji_status_custom_emoji_id"`

	// Returns only in getMe
	CanJoinGroups        bool `json:"can_join_groups"`
	CanReadMessages      bool `json:"can_read_all_group_messages"`
	SupportsInline       bool `json:"supports_inline_queries"`
	SupportsGuest        bool `json:"supports_guest_queries"`
	CanConnectToBusiness bool `json:"can_connect_to_business"`
	HasMainWebApp        bool `json:"has_main_web_app"`

	// Bot API 9.4: (Optional) True, if the bot allows users to create
	// and delete topics in private chats.
	AllowsUsersToCreateTopics bool `json:"allows_users_to_create_topics,omitempty"`
}

User object represents a Telegram user, bot.

func (*User) Recipient

func (u *User) Recipient() string

Recipient returns user ID (see Recipient interface).

type UserProfileAudios

type UserProfileAudios struct {
	TotalCount int     `json:"total_count"`
	Audios     []Audio `json:"audios"`
}

UserProfileAudios represents the audios displayed on a user's profile.

type Venue

type Venue struct {
	Location Location `json:"location"`
	Title    string   `json:"title"`
	Address  string   `json:"address"`

	// (Optional)
	FoursquareID    string `json:"foursquare_id,omitempty"`
	FoursquareType  string `json:"foursquare_type,omitempty"`
	GooglePlaceID   string `json:"google_place_id,omitempty"`
	GooglePlaceType string `json:"google_place_type,omitempty"`
}

Venue object represents a venue location with name, address and optional foursquare ID.

func (*Venue) Send

func (v *Venue) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers media through bot b to recipient.

type VenueResult

type VenueResult struct {
	ResultBase

	Location

	// Title of the venue.
	Title string `json:"title"`

	// Address of the venue.
	Address string `json:"address"`

	// Optional. Foursquare identifier of the venue if known.
	FoursquareID string `json:"foursquare_id,omitempty"`

	// Optional. URL of the thumbnail for the result.
	ThumbURL string `json:"thumbnail_url,omitempty"`

	// Optional. Width of the thumbnail for the result.
	ThumbWidth int `json:"thumbnail_width,omitempty"`

	// Optional. Height of the thumbnail for the result.
	ThumbHeight int `json:"thumbnail_height,omitempty"`
}

VenueResult represents a venue.

type VerificationInfo

type VerificationInfo struct {
	// Verification level of the user or chat
	Level VerificationLevel `json:"level"`

	// (Optional) Date when verification was granted in Unix time
	VerificationDate int64 `json:"verification_date,omitempty"`

	// (Optional) Expiration date of verification in Unix time
	ExpirationDate int64 `json:"expiration_date,omitempty"`

	// (Optional) Information about the entity that verified this user or chat
	VerifiedBy string `json:"verified_by,omitempty"`

	// (Optional) Additional verification details
	Details string `json:"details,omitempty"`

	// (Optional) Whether the verification is currently active
	IsActive bool `json:"is_active"`
}

VerificationInfo contains information about the verification status.

func (*VerificationInfo) ExpirationTime

func (v *VerificationInfo) ExpirationTime() time.Time

ExpirationTime returns the expiration date of the verification.

func (*VerificationInfo) IsExpired

func (v *VerificationInfo) IsExpired() bool

IsExpired returns whether the verification has expired.

func (*VerificationInfo) IsValid

func (v *VerificationInfo) IsValid() bool

IsValid returns whether the verification is currently valid (active and not expired).

func (*VerificationInfo) VerificationTime

func (v *VerificationInfo) VerificationTime() time.Time

VerificationTime returns the date when verification was granted.

type VerificationLevel

type VerificationLevel string

VerificationLevel describes the verification level of a user or chat.

const (
	VerificationLevelNone     VerificationLevel = "none"
	VerificationLevelBasic    VerificationLevel = "basic"
	VerificationLevelDetailed VerificationLevel = "detailed"
	VerificationLevelFull     VerificationLevel = "full"
)

type VerificationRequirements

type VerificationRequirements struct {
	// (Optional) Whether the user needs to provide a phone number
	RequirePhoneNumber bool `json:"require_phone_number,omitempty"`

	// (Optional) Whether the user needs to provide their real name
	RequireRealName bool `json:"require_real_name,omitempty"`

	// (Optional) Whether the user needs to provide their date of birth
	RequireBirthDate bool `json:"require_birth_date,omitempty"`

	// (Optional) Whether the user needs to provide their address
	RequireAddress bool `json:"require_address,omitempty"`

	// (Optional) Whether the user needs to provide identification documents
	RequireDocuments bool `json:"require_documents,omitempty"`

	// (Optional) Custom verification requirements
	CustomRequirements []string `json:"custom_requirements,omitempty"`
}

VerificationRequirements describes the requirements for verification.

type Video

type Video struct {
	File

	Width    int `json:"width"`
	Height   int `json:"height"`
	Duration int `json:"duration,omitempty"`

	// (Optional)
	Caption      string `json:"caption,omitempty"`
	Thumbnail    *Photo `json:"thumbnail,omitempty"`
	Streaming    bool   `json:"supports_streaming,omitempty"`
	MIME         string `json:"mime_type,omitempty"`
	FileName     string `json:"file_name,omitempty"`
	HasSpoiler   bool   `json:"has_spoiler,omitempty"`
	CaptionAbove bool   `json:"show_caption_above_media,omitempty"`

	// Bot API 8.3: (Optional) Cover frame of the video
	Cover *Photo `json:"cover,omitempty"`

	// Bot API 8.3: (Optional) Point in time (Unix timestamp) when the video starts
	StartTimestamp int64 `json:"start_timestamp,omitempty"`

	// Bot API 9.4: (Optional) List of available qualities of the video.
	Qualities []VideoQuality `json:"qualities,omitempty"`
}

Video object represents a video file.

func (*Video) InputMedia

func (v *Video) InputMedia() InputMedia

func (*Video) MediaFile

func (v *Video) MediaFile() *File

func (*Video) MediaType

func (v *Video) MediaType() string

func (*Video) Paid

func (v *Video) Paid() bool

func (*Video) Send

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

Send delivers media through bot b to recipient.

type VideoChatEnded

type VideoChatEnded struct {
	Duration int `json:"duration"` // in seconds
}

VideoChatEnded represents a service message about a video chat ended in the chat.

type VideoChatParticipants

type VideoChatParticipants struct {
	Users []User `json:"users"`
}

VideoChatParticipants represents a service message about new members invited to a video chat

type VideoChatScheduled

type VideoChatScheduled struct {
	Unixtime int64 `json:"start_date"`
}

VideoChatScheduled represents a service message about a video chat scheduled in the chat.

func (*VideoChatScheduled) StartsAt

func (v *VideoChatScheduled) StartsAt() time.Time

StartsAt returns the point when the video chat is supposed to be started by a chat administrator.

type VideoChatStarted

type VideoChatStarted struct{}

VideoChatStarted represents a service message about a video chat started in the chat.

type VideoNote

type VideoNote struct {
	File

	Duration int `json:"duration"`

	// (Optional)
	Thumbnail *Photo `json:"thumbnail,omitempty"`
	Length    int    `json:"length,omitempty"`
}

VideoNote represents a video message.

func (*VideoNote) MediaFile

func (v *VideoNote) MediaFile() *File

func (*VideoNote) MediaType

func (v *VideoNote) MediaType() string

func (*VideoNote) Send

func (v *VideoNote) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers media through bot b to recipient.

type VideoQuality

type VideoQuality struct {
	FileID       string `json:"file_id"`
	FileUniqueID string `json:"file_unique_id"`
	Width        int    `json:"width"`
	Height       int    `json:"height"`

	// Codec used to encode the video, for example, "h264", "h265", or "av01".
	Codec string `json:"codec"`

	// (Optional) File size in bytes.
	FileSize int64 `json:"file_size,omitempty"`
}

VideoQuality represents a video file of a specific quality.

type VideoResult

type VideoResult struct {
	ResultBase

	// A valid URL for the embedded video player or video file.
	URL string `json:"video_url"`

	// Mime type of the content of video url, “text/html” or “video/mp4”.
	MIME string `json:"mime_type"`

	// URL of the thumbnail (jpeg only) for the video.
	ThumbURL string `json:"thumbnail_url"`

	// Title for the result.
	Title string `json:"title"`

	// Optional. Caption of the video to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Video width.
	Width int `json:"video_width,omitempty"`

	// Optional. Video height.
	Height int `json:"video_height,omitempty"`

	// Optional. Video duration in seconds.
	Duration int `json:"video_duration,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// If Cache != "", it'll be used instead
	Cache string `json:"video_file_id,omitempty"`

	// (Optional) Pass True, if the caption must be shown above the message media
	CaptionAbove bool `json:"show_caption_above_media,omitempty"`
}

VideoResult represents a link to a page containing an embedded video player or a video file.

type Voice

type Voice struct {
	File

	Duration int `json:"duration"`

	// (Optional)
	Caption string `json:"caption,omitempty"`
	MIME    string `json:"mime_type,omitempty"`
}

Voice object represents a voice note.

func (*Voice) MediaFile

func (v *Voice) MediaFile() *File

func (*Voice) MediaType

func (v *Voice) MediaType() string

func (*Voice) Send

func (v *Voice) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error)

Send delivers media through bot b to recipient.

type VoiceResult

type VoiceResult struct {
	ResultBase

	// A valid URL for the voice recording.
	URL string `json:"voice_url"`

	// Recording title.
	Title string `json:"title"`

	// Optional. Recording duration in seconds.
	Duration int `json:"voice_duration"`

	// Optional. Caption, 0-1024 characters.
	Caption string `json:"caption,omitempty"`

	// If Cache != "", it'll be used instead
	Cache string `json:"voice_file_id,omitempty"`
}

VoiceResult represents a link to a voice recording in an .ogg container encoded with OPUS.

type WebApp

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

WebApp represents a parameter of the inline keyboard button or the keyboard button used to launch Web App.

type WebAppData

type WebAppData struct {
	Data string `json:"data"`
	Text string `json:"button_text"`
}

WebAppData object represents a data sent from a Web App to the bot

type WebAppMessage

type WebAppMessage struct {
	InlineMessageID string `json:"inline_message_id"`
}

WebAppMessage describes an inline message sent by a Web App on behalf of a user.

type Webhook

type Webhook struct {
	Listen           string   `json:"url"`
	MaxConnections   int      `json:"max_connections"`
	AllowedUpdates   []string `json:"allowed_updates"`
	IP               string   `json:"ip_address"`
	DropUpdates      bool     `json:"drop_pending_updates"`
	SecretToken      string   `json:"secret_token"`
	IgnoreSetWebhook bool     `json:"ignore_set_web_hook"`

	// (WebhookInfo)
	HasCustomCert     bool   `json:"has_custom_certificate"`
	PendingUpdates    int    `json:"pending_update_count"`
	ErrorUnixtime     int64  `json:"last_error_date"`
	ErrorMessage      string `json:"last_error_message"`
	SyncErrorUnixtime int64  `json:"last_synchronization_error_date"`

	TLS      *WebhookTLS
	Endpoint *WebhookEndpoint
	// contains filtered or unexported fields
}

A Webhook configures the poller for webhooks. It opens a port on the given listen address. If TLS is filled, the listener will use the key and cert to open a secure port. Otherwise it will use plain HTTP.

If you have a loadbalancer ore other infrastructure in front of your service, you must fill the Endpoint structure so this poller will send this data to telegram. If you leave these values empty, your local address will be sent to telegram which is mostly not what you want (at least while developing). If you have a single instance of your bot you should consider to use the LongPoller instead of a WebHook.

You can also leave the Listen field empty. In this case it is up to the caller to add the Webhook to a http-mux.

If you want to ignore the automatic setWebhook call, you can set IgnoreSetWebhook to true.

func (*Webhook) Poll

func (h *Webhook) Poll(b *Bot, dest chan Update, stop chan struct{})

func (*Webhook) ServeHTTP

func (h *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request)

The handler simply reads the update from the body of the requests and writes them to the update channel.

type WebhookEndpoint

type WebhookEndpoint struct {
	PublicURL string `json:"public_url"`
	Cert      string `json:"cert"`
}

A WebhookEndpoint describes the endpoint to which telegram will send its requests. This must be a public URL and can be a loadbalancer or something similar. If the endpoint uses TLS and the certificate is self-signed you have to add the certificate path of this certificate so telegram will trust it. This field can be ignored if you have a trusted certificate (letsencrypt, ...).

type WebhookTLS

type WebhookTLS struct {
	Key  string `json:"key"`
	Cert string `json:"cert"`
}

A WebhookTLS specifies the path to a key and a cert so the poller can open a TLS listener.

type WriteAccessAllowed

type WriteAccessAllowed struct {
	WebAppName         string `json:"web_app_name,omitempty"`
	FromRequest        bool   `json:"from_request,omitempty"`
	FromAttachmentMenu bool   `json:"from_attachment_menu,omitempty"`
}

WebAppAccessAllowed represents a service message about a user allowing a bot to write messages after adding the bot to the attachment menu or launching a Web App from a link.

Directories

Path Synopsis
examples
basic command
Command basic is a small tbb bot showing the main pieces: config, translations, the language picker, inline-button callbacks, a multi-step scene with app-specific session state, and a localized reply-keyboard cancel button.
Command basic is a small tbb bot showing the main pieces: config, translations, the language picker, inline-button callbacks, a multi-step scene with app-specific session state, and a localized reply-keyboard cancel button.

Jump to

Keyboard shortcuts

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