### Initialize WebhookPoller Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Example setup for a bot using the WebhookPoller implementation. ```go poller := &tele.WebhookPoller{ Listen: ":8080", Secret: "/webhook", } b, err := tele.NewBot(tele.Settings{ Token: "TOKEN", Poller: poller, }) ``` -------------------------------- ### Initialize LongPoller Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Example setup for a bot using the LongPoller implementation. ```go poller := &tele.LongPoller{ Timeout: 10 * time.Second, Limit: 100, } b, err := tele.NewBot(tele.Settings{ Token: "TOKEN", Poller: poller, }) ``` -------------------------------- ### Basic Telebot Setup Source: https://github.com/tucnak/telebot/blob/v4/README.md Minimal setup for a Telebot application, including token retrieval, poller configuration, and a simple /hello command handler. ```go package main import ( "log" "os" "time" tele "gopkg.in/telebot.v4" ) func main() { pref := tele.Settings{ Token: os.Getenv("TOKEN"), Poller: &tele.LongPoller{Timeout: 10 * time.Second}, } b, err := tele.NewBot(pref) if err != nil { log.Fatal(err) return } b.Handle("/hello", func(c tele.Context) error { return c.Send("Hello!") }) b.Start() } ``` -------------------------------- ### Send a Document Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Example of initializing and sending a document file. ```go doc := &tele.Document{ File: tele.FromDisk("report.pdf"), FileName: "Report.pdf", MIME: "application/pdf", Caption: "Monthly Report", } msg, err := b.Send(user, doc) ``` -------------------------------- ### Implement a basic handler Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/handlers.md Example of a simple handler function and its registration to a command. ```go func myHandler(c tele.Context) error { msg := c.Message() return c.Send("You said: " + msg.Text) } b.Handle("/start", myHandler) ``` -------------------------------- ### Send a VideoNote Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Example of initializing and sending a video note. ```go note := &tele.VideoNote{ File: tele.FromDisk("note.mp4"), Duration: 30, Width: 512, } msg, err := b.Send(user, note) ``` -------------------------------- ### Handle Inline Query Example Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/callbacks.md Implementation example for handling an inline query and returning multiple result types. ```go b.Handle(tele.OnQuery, func(c tele.Context) error { query := c.Query() results := []tele.Result{ &tele.ArticleResult{ ID: "1", Title: "Search Result", Text: "Result content", }, &tele.PhotoResult{ ID: "2", URL: "https://example.com/photo.jpg", }, } return c.Bot().Answer(query, &tele.QueryResponse{ Results: results, }) }) ``` -------------------------------- ### Install Telebot Source: https://github.com/tucnak/telebot/blob/v4/README.md Install the Telebot v4 package using go get. ```bash go get -u gopkg.in/telebot.v4 ``` -------------------------------- ### Initialize Bot with Settings Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Example of creating a new bot instance using the Settings struct. ```go settings := tele.Settings{ Token: "TOKEN", Poller: &tele.LongPoller{Timeout: 10 * time.Second}, Synchronous: false, ParseMode: tele.ModeHTML, Verbose: false, OnError: func(err error, c tele.Context) { log.Println(err) }, } b, err := tele.NewBot(settings) ``` -------------------------------- ### Implement keyboard types Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Examples for creating inline keyboards, reply keyboards, and force reply interfaces. ```go // Inline keyboard (buttons in message) markup := &tele.ReplyMarkup{ InlineKeyboard: [][]tele.InlineButton{ {tele.InlineButton{Text: "Visit Google", URL: "https://google.com"}}, { tele.InlineButton{Text: "Option A", Data: "a"}, tele.InlineButton{Text: "Option B", Data: "b"}, }, }, } b.Send(user, "Choose an option:", markup) // Reply keyboard (on-screen keyboard) markup := &tele.ReplyMarkup{ ReplyKeyboard: [][]tele.ReplyButton{ {tele.ReplyButton{Text: "Yes"}, tele.ReplyButton{Text: "No"}}, {tele.ReplyButton{Text: "Maybe"}}, }, OneTimeKeyboard: true, } b.Send(user, "What do you think?", markup) // Force reply markup := &tele.ReplyMarkup{ ForceReply: true, } b.Send(user, "Please reply:", markup) ``` -------------------------------- ### Start() Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Starts the bot's polling loop. This method blocks the current goroutine until Stop is called, continuously fetching and processing updates. ```APIDOC ## func (b *Bot) Start() ### Description Starts the bot's polling loop. Blocks until Stop is called. The poller continuously fetches or receives updates and processes them through registered handlers. ``` -------------------------------- ### Send a Voice message Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Example of initializing and sending a voice file. ```go voice := &tele.Voice{ File: tele.FromDisk("audio.ogg"), Duration: 45, } msg, err := b.Send(user, voice) ``` -------------------------------- ### Send Album Example Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Shows how to group multiple media items into an album and send them together. ```go album := tele.Album{ &tele.Photo{File: tele.FromDisk("photo1.jpg")}, &tele.Photo{File: tele.FromDisk("photo2.jpg")}, &tele.Video{File: tele.FromDisk("video.mp4")}, } msgs, err := b.SendAlbum(user, album) ``` -------------------------------- ### Respond to Callback Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/callbacks.md Example of sending a response to a button click event. ```go b.Handle(&button, func(c tele.Context) error { return c.Respond(&tele.CallbackResponse{ Text: "You clicked the button!", ShowAlert: false, }) }) ``` -------------------------------- ### Initialize and start a Telegram bot Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/README.md Configures a new bot instance with a token and long poller, defines a start handler, and begins polling for updates. ```go package main import ( "log" "time" tele "gopkg.in/telebot.v4" ) func main() { b, err := tele.NewBot(tele.Settings{ Token: "YOUR_BOT_TOKEN", Poller: &tele.LongPoller{Timeout: 10 * time.Second}, }) if err != nil { log.Fatal(err) } b.Handle("/start", func(c tele.Context) error { return c.Send("Hello!") }) b.Start() } ``` -------------------------------- ### Manage Forum Topics Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Example of handling topic creation and sending messages to specific threads. ```go b.Handle(tele.OnTopicCreated, func(c tele.Context) error { topic := c.Topic() return c.Send("New topic: " + topic.Name) }) // Send to specific topic msg, err := b.Send(chat, "In topic", &tele.SendOptions{ ThreadID: topic.ThreadID, }) ``` -------------------------------- ### Send Messages and Media Examples Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/messages.md Demonstrates sending plain text, text with options, keyboards, and media files. ```go // Send text msg, err := b.Send(user, "Hello!") // Send with options msg, err := b.Send(user, "Hello!", tele.NoPreview, tele.Silent) // Send text with keyboard keyboard := &tele.ReplyMarkup{ ReplyKeyboard: [][]tele.ReplyButton{ {tele.ReplyButton{Text: "Yes"}, tele.ReplyButton{Text: "No"}}, }, } msg, err := b.Send(user, "Choose:", keyboard) // Send photo photo := &tele.Photo{ File: tele.FromDisk("/path/to/photo.jpg"), } msg, err := b.Send(user, photo) ``` -------------------------------- ### func (b *Bot) Start() Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Starts the bot by beginning to poll for updates and process them. This method blocks the current goroutine until Stop is called. ```APIDOC ## func (b *Bot) Start() ### Description Starts the bot by beginning to poll for updates and process them. Blocks until Stop is called. ### Example ```go b.Handle("/start", func(c tele.Context) error { return c.Send("Hello!") }) b.Start() // Blocks here until Stop() is called ``` ``` -------------------------------- ### Example Usage of Global Middleware Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Demonstrates applying multiple global middleware functions to the bot instance. ```go b.Use(myLogMiddleware) b.Use(myAuthMiddleware) ``` -------------------------------- ### Send PaidAlbum Example Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Demonstrates sending a paid media album with a specified cost in Stars. ```go album := tele.PaidAlbum{ &tele.Photo{File: tele.FromDisk("exclusive.jpg")}, } msg, err := b.SendPaidMedia(user, 100, album) ``` -------------------------------- ### Handle Callback Query Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/callbacks.md Example of registering a handler for an inline button and responding to the callback. ```go btn := &tele.InlineButton{ Unique: "btn_id", Text: "Click me!", Data: "button_data", } b.Handle(&btn, func(c tele.Context) error { callback := c.Callback() fmt.Println("Data:", callback.Data) return c.Respond(&tele.CallbackResponse{Text: "Got it!"}) }) ``` -------------------------------- ### Send a photo message Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Example of initializing a Photo struct and sending it to a user. ```go photo := &tele.Photo{ File: tele.FromDisk("photo.jpg"), Caption: "My photo", } msg, err := b.Send(user, photo) ``` -------------------------------- ### Send Animation Example Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Demonstrates sending an animation file from disk using the tele.Animation struct. ```go anim := &tele.Animation{ File: tele.FromDisk("animation.gif"), Duration: 60, } msg, err := b.Send(user, anim) ``` -------------------------------- ### Create a ReplyMarkup keyboard Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Example of initializing a ReplyMarkup with multiple rows of ReplyButtons and setting the OneTimeKeyboard property. ```go markup := &tele.ReplyMarkup{ ReplyKeyboard: [][]tele.ReplyButton{ { tele.ReplyButton{Text: "My Contact", Contact: true}, tele.ReplyButton{Text: "My Location", Location: true}, }, {tele.ReplyButton{Text: "Cancel"}}, }, OneTimeKeyboard: true, } b.Send(user, "Share your info:", markup) ``` -------------------------------- ### Sending Video Message Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Example of initializing a Video struct and sending it via the bot. ```go video := &tele.Video{ File: tele.FromDisk("video.mp4"), Duration: 120, Width: 1280, Height: 720, Caption: "Check this out!", } msg, err := b.Send(user, video) ``` -------------------------------- ### Initialize WebhookPoller Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Example usage of WebhookPoller to receive updates via HTTPS. ```go poller := &tele.WebhookPoller{ Listen: ":443", Secret: "/webhook/secret", } b, err := tele.NewBot(tele.Settings{ Token: "TOKEN", Poller: poller, }) b.Start() // Listens for webhook updates ``` -------------------------------- ### Using Telebot Middleware Source: https://github.com/tucnak/telebot/blob/v4/README.md Demonstrates how to apply global, group-scoped, and handler-scoped middleware. Includes importing the middleware package and custom middleware example. ```go import "gopkg.in/telebot.v4/middleware" // Global-scoped middleware: b.Use(middleware.Logger()) b.Use(middleware.AutoRespond()) // Group-scoped middleware: adminOnly := b.Group() adminOnly.Use(middleware.Whitelist(adminIDs...)) adminOnly.Handle("/ban", onBan) adminOnly.Handle("/kick", onKick) // Handler-scoped middleware: b.Handle(tele.OnText, onText, middleware.IgnoreVia()) ``` ```go // AutoResponder automatically responds to every callback update. func AutoResponder(next tele.HandlerFunc) tele.HandlerFunc { return func(c tele.Context) error { if c.Callback() != nil { defer c.Respond() } return next(c) // continue execution chain } } ``` -------------------------------- ### Sending Audio Message Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Example of initializing an Audio struct and sending it via the bot. ```go audio := &tele.Audio{ File: tele.FromDisk("song.mp3"), Title: "My Song", Performer: "Artist", Duration: 180, } msg, err := b.Send(user, audio) ``` -------------------------------- ### Example Usage of Bot Groups Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Demonstrates creating a group with specific middleware and registering handlers within that group. ```go admin := b.Group() admin.Use(adminOnly) admin.Handle("/ban", onBan) admin.Handle("/kick", onKick) ``` -------------------------------- ### Send message with options Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Example usage of SendOptions when sending a message via the bot instance. ```go opts := &tele.SendOptions{ ParseMode: tele.ModeHTML, DisableWebPagePreview: true, Protected: true, ReplyMarkup: &tele.ReplyMarkup{...}, } msg, err := b.Send(user, "Message", opts) ``` -------------------------------- ### Handler Registration Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Example of how to register a handler for an InlineButton click event. ```APIDOC ## Handler Registration ### Description Register a callback handler for a specific InlineButton instance. ### Example ```go btn := &tele.InlineButton{ Unique: "btn_yes", Text: "Yes", Data: "confirmed", } b.Handle(&btn, func(c tele.Context) error { return c.Respond(&tele.CallbackResponse{ Text: "You pressed Yes!", }) }) ``` ``` -------------------------------- ### Start Bot Lifecycle Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Initiates update polling and blocks execution until Stop is invoked. ```go func (b *Bot) Start() ``` ```go b.Handle("/start", func(c tele.Context) error { return c.Send("Hello!") }) b.Start() // Blocks here until Stop() is called ``` -------------------------------- ### Initialize LongPoller Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Example usage of LongPoller to fetch updates via the getUpdates method. ```go poller := &tele.LongPoller{ Timeout: 10 * time.Second, Limit: 100, AllowedUpdates: []string{"message", "callback_query"}, } b, err := tele.NewBot(tele.Settings{ Token: "TOKEN", Poller: poller, }) b.Start() // Polls for updates ``` -------------------------------- ### Function Signature and Usage Example Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/SUMMARY.txt Standard template for defining a function signature and its corresponding usage in Go. ```go func (b *Bot) FunctionName(param Type) (*ReturnType, error) ``` ```go result, err := b.FunctionName(param) ``` -------------------------------- ### Get Message Content Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/INDEX.md Retrieves text, arguments, and sender information from the current context. ```go text := c.Text() args := c.Args() sender := c.Sender() ``` -------------------------------- ### Handle Video Chat Events Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Event handlers for monitoring the start and end of video chats. ```go b.Handle(tele.OnVideoChatStarted, func(c tele.Context) error { return c.Send("Video chat started!") }) b.Handle(tele.OnVideoChatEnded, func(c tele.Context) error { ended := c.Update().VideoChatEnded return c.Send(fmt.Sprintf("Video chat ended, duration: %ds", ended.Duration)) }) ``` -------------------------------- ### Handle updates outside Start() Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Use the Updates channel to process messages concurrently while the bot is running. ```go go func() { for update := range b.Updates { ctx := b.NewContext(update) if update.Message != nil { // Handle message } } }() b.Start() ``` -------------------------------- ### Initialize and Use Bot Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/api-interface.md Demonstrates creating a new bot instance and sending a message using the Send method. ```go b, _ := tele.NewBot(tele.Settings{Token: "..."}) msg, _ := b.Send(user, "Hello") ``` -------------------------------- ### Using Option Flags for Message Configuration Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Demonstrates the shorthand syntax for setting keyboard options and combining multiple message flags. ```go // These are equivalent: b.Send(user, "Hello", tele.OneTimeKeyboard) b.Send(user, "Hello", &tele.SendOptions{ ReplyMarkup: &tele.ReplyMarkup{OneTimeKeyboard: true}, }) // Multiple options b.Send(user, "Hello", tele.Silent, tele.NoPreview) ``` -------------------------------- ### Start the Bot Polling Loop Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Initiates the polling loop which blocks execution until Stop is called. Registered handlers process incoming updates. ```go func (b *Bot) Start() ``` ```go b.Handle("/start", func(c tele.Context) error { return c.Send("Hello!") }) b.Start() // Blocks here, polling for updates ``` -------------------------------- ### Len Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/admin.md Gets the total number of members in a chat. ```APIDOC ## func (b *Bot) Len(chat *Chat) (int, error) ### Description Gets the total number of members in a chat. ### Parameters - **chat** (*Chat) - Required - Chat ### Returns - **(int, error)** - Member count or error ``` -------------------------------- ### Implement Editable Interface for StoredMessage Source: https://github.com/tucnak/telebot/blob/v4/README.md Provides an example implementation of the Editable interface for a StoredMessage struct, suitable for database storage. ```go // 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.) type StoredMessage struct { MessageID int `sql:"message_id" json:"message_id"` ChatID int64 `sql:"chat_id" json:"chat_id"` } func (x StoredMessage) MessageSig() (int, int64) { return x.MessageID, x.ChatID } ``` -------------------------------- ### Get Chat Info Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/INDEX.md Retrieves full information about a chat. ```go info, err := b.ChatFullInfo(chat) ``` -------------------------------- ### Initialize a new Bot instance Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Creates a new Bot instance using the provided settings. Validates the token via getMe unless Offline mode is enabled. ```go func NewBot(pref Settings) (*Bot, error) ``` ```go b, err := tele.NewBot(tele.Settings{ Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", Poller: &tele.LongPoller{Timeout: 10 * time.Second}, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create and send files Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Demonstrates creating file references from disk, URL, or reader and sending them via the bot. ```go // From local file file := tele.FromDisk("/path/to/photo.jpg") // From URL file := tele.FromURL("https://example.com/photo.jpg") // From reader file := tele.FromReader(bytes.NewReader(data)) // Use in Send msg, err := b.Send(user, &tele.Photo{File: file}) ``` -------------------------------- ### Use Option shortcuts Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Demonstrates using Option constants as shorthand for SendOptions configuration. ```go // These are equivalent: b.Send(user, "Hello", tele.NoPreview, tele.Silent) b.Send(user, "Hello", &tele.SendOptions{ DisableWebPagePreview: true, DisableNotification: true, }) ``` -------------------------------- ### Initialize Bot and Middleware Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/api-interface.md Standard import pattern for core functionality and optional middleware usage. ```go import tele "gopkg.in/telebot.v4" // All types and functions are in the tele package b, _ := tele.NewBot(tele.Settings{...}) msg, _ := b.Send(user, "Text") ``` ```go import "gopkg.in/telebot.v4/middleware" b.Use(middleware.Whitelist(adminIDs...)) ``` -------------------------------- ### Handle FloodError Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/errors.md Example of handling rate-limit errors by checking the RetryAfter field. ```go if err != nil { if floodErr, ok := err.(tele.FloodError); ok { fmt.Printf("Rate limited, retry after %d seconds\n", floodErr.RetryAfter) time.Sleep(time.Duration(floodErr.RetryAfter) * time.Second) } } ``` -------------------------------- ### Handle Command with Payload Source: https://github.com/tucnak/telebot/blob/v4/README.md Handles a /start command and prints the message payload. Ensure the command format includes a payload for this to work. ```go b.Handle("/start", func(c tele.Context) error { fmt.Println(c.Message().Payload) // }) ``` -------------------------------- ### Get Thread ID Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/context.md Retrieve the message thread ID for forum topics in supergroups. ```go threadID := c.ThreadID() if threadID > 0 { fmt.Println("In topic:", threadID) } ``` -------------------------------- ### File constructor signatures Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Available functions for creating File references from different sources. ```go func FromDisk(path string) File func FromURL(url string) File func FromReader(r io.Reader) File func FromReader(name string, r io.Reader) File ``` -------------------------------- ### Handle various endpoint types Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/handlers.md Demonstrates registering handlers for commands, events, buttons, and applying middleware. ```go // Command handler b.Handle("/start", func(c tele.Context) error { return c.Send("Welcome!") }) // Event handler b.Handle(tele.OnText, func(c tele.Context) error { return c.Send("You sent: " + c.Text()) }) // Button handler btn := &tele.InlineButton{ Unique: "btn_yes", Text: "Yes", } b.Handle(&btn, func(c tele.Context) error { return c.Respond(&tele.CallbackResponse{Text: "You clicked yes!"}) }) // With middleware b.Handle("/admin", onAdmin, requireAdmin, requireMod) ``` -------------------------------- ### Configure Reply and Inline Keyboards Source: https://github.com/tucnak/telebot/blob/v4/README.md Sets up universal markup builders for reply and inline keyboards, including defining buttons for help, settings, previous, and next actions. ```go var ( // Universal markup builders. menu = &tele.ReplyMarkup{ResizeKeyboard: true} selector = &tele.ReplyMarkup{} // Reply buttons. btnHelp = menu.Text("ℹ Help") btnSettings = menu.Text("⚙ Settings") // Inline buttons. // // Pressing it will cause the client to // send the bot a callback. // // Make sure Unique stays unique as per button kind // since it's required for callback routing to work. // btnPrev = selector.Data("⬅", "prev", ...) btnNext = selector.Data("➡", "next", ...) ) menu.Reply( menu.Row(btnHelp), menu.Row(btnSettings), ) selector.Inline( selector.Row(btnPrev, btnNext), ) ``` -------------------------------- ### Handle GroupError Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/errors.md Example of handling group migration errors to retrieve the new chat ID. ```go if err != nil { if groupErr, ok := err.(tele.GroupError); ok { newChatID := groupErr.MigratedTo fmt.Printf("Group migrated to supergroup: %d\n", newChatID) } } ``` -------------------------------- ### Registering an InlineButton Handler Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Demonstrates how to initialize an InlineButton and register a handler to respond to user interactions. ```go btn := &tele.InlineButton{ Unique: "btn_yes", Text: "Yes", Data: "confirmed", } b.Handle(&btn, func(c tele.Context) error { return c.Respond(&tele.CallbackResponse{ Text: "You pressed Yes!", }) }) ``` -------------------------------- ### Utilize Middleware Package Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Import the middleware package to access pre-built utilities for filtering, restricting, and logging bot interactions. ```go import "gopkg.in/telebot.v4/middleware" middleware.Whitelist(ids...) middleware.Blacklist(ids...) middleware.IgnoreUsername(names...) middleware.RestrictEdits() middleware.Recover() middleware.Logger() ``` -------------------------------- ### Handle Inline Queries and Respond with Results Source: https://github.com/tucnak/telebot/blob/v4/README.md Sets up a handler for incoming inline queries using tele.OnQuery and demonstrates how to use the Answer method to send a list of tele.PhotoResult objects. ```go b.Handle(tele.OnQuery, func(c tele.Context) error { urls := []string{ "http://photo.jpg", "http://photo2.jpg", } results := make(tele.Results, len(urls)) // []tele.Result for i, url := range urls { result := &tele.PhotoResult{ URL: url, ThumbURL: url, // required for photos } results[i] = result // needed to set a unique string ID for each result results[i].SetResultID(strconv.Itoa(i)) } return c.Answer(&tele.QueryResponse{ Results: results, CacheTime: 60, // a minute }) }) ``` -------------------------------- ### Get total chat member count Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/admin.md Retrieves the total number of members present in a chat. ```go func (b *Bot) Len(chat *Chat) (int, error) ``` ```go count, err := b.Len(chat) if err == nil { fmt.Printf("Chat has %d members\n", count) } ``` -------------------------------- ### Retrieve Message Text Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/context.md Get the text content of an update. Returns an empty string for callbacks. ```go if text := c.Text(); text != "" { fmt.Println("User said:", text) } ``` -------------------------------- ### Get Message Recipient Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/context.md Retrieve the recipient for sending messages, combining sender and chat information. ```go recipient := c.Recipient() b.Send(recipient, "Hello!") // Equivalent to c.Send("Hello!") ``` -------------------------------- ### Menu Button Methods Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Methods for retrieving and setting the bot's menu button configuration. ```go func (b *Bot) MenuButton(chat *User) (*MenuButton, error) func (b *Bot) SetMenuButton(chat *User, mb interface{}) error ``` -------------------------------- ### Register and handle button callbacks Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/callbacks.md Demonstrates defining a button with a unique ID, registering a handler, and sending the button in a markup. ```go // Define button with unique callback ID btn := &tele.InlineButton{ Unique: "my_button", Text: "Click me", } // Register callback handler b.Handle(&btn, myCallbackHandler) // Button is sent in a message markup := &tele.ReplyMarkup{ InlineKeyboard: [][]tele.InlineButton{{*btn}}, } b.Send(user, "Choose:", markup) // When user clicks, myCallbackHandler is invoked ``` -------------------------------- ### Initialize Rights with Constructor Functions Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/admin.md Use these functions to initialize default permission sets for chat members. ```go func NoRights() Rights func NoRestrictions() Rights func AdminRights() Rights ``` -------------------------------- ### Handle API Errors Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/errors.md Example of type asserting an error to *tele.Error to access API error details. ```go if err != nil { if apiErr, ok := err.(*tele.Error); ok { fmt.Println("Code:", apiErr.Code) fmt.Println("Description:", apiErr.Description) fmt.Println("Message:", apiErr.Message) } } ``` -------------------------------- ### Create a new Context Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/context.md Initializes a new context instance using the provided Bot API and Update. ```go ctx := tele.NewContext(b, update) ``` -------------------------------- ### func (b *Bot) ChatFullInfo(chat Recipient) (*ChatFullInfo, error) Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/admin.md Gets detailed information about a chat. ```APIDOC ## func (b *Bot) ChatFullInfo(chat Recipient) (*ChatFullInfo, error) ### Description Retrieves detailed information about a specific chat. ### Parameters - **chat** (Recipient) - Required - The chat to retrieve information for. ### Returns - **(*ChatFullInfo, error)** - Returns a pointer to ChatFullInfo or an error if the request fails. ``` -------------------------------- ### Stop() Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Stops the bot's polling loop, allowing the program to continue execution after a blocking Start() call. ```APIDOC ## func (b *Bot) Stop() ### Description Stops the bot's polling loop. ``` -------------------------------- ### Handle Bot Commands and Button Presses Source: https://github.com/tucnak/telebot/blob/v4/README.md Defines handlers for the /start command to send a message with a reply keyboard, and for reply/inline buttons to edit messages or respond to callbacks. ```go b.Handle("/start", func(c tele.Context) error { return c.Send("Hello!", menu) }) // On reply button pressed (message) b.Handle(&btnHelp, func(c tele.Context) error { return c.Edit("Here is some help: ...") }) // On inline button pressed (callback) b.Handle(&btnPrev, func(c tele.Context) error { return c.Respond() }) ``` -------------------------------- ### Retrieve Update Data Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/context.md Get command arguments, callback data, or payment payloads depending on the update type. ```go // If user sends "/start myarg", Data returns "myarg" arg := c.Data() ``` -------------------------------- ### Create Various Button Types with Markup Constructor Source: https://github.com/tucnak/telebot/blob/v4/README.md Illustrates how to use the markup constructor to create different types of reply and inline buttons, including text, contact, location, poll, data, URL, query, and login buttons. ```go r := b.NewMarkup() // Reply buttons: r.Text("Hello!") r.Contact("Send phone number") r.Location("Send location") r.Poll(tele.PollQuiz) // Inline buttons: r.Data("Show help", "help") // data is optional r.Data("Delete item", "delete", item.ID) r.URL("Visit", "https://google.com") r.Query("Search", query) r.QueryChat("Share", query) r.Login("Login", &tele.Login{...}) ``` -------------------------------- ### Download File Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Saves a file to the local filesystem. ```go func (b *Bot) Download(file *File, localFilename string) error ``` ```go msg := c.Message() if msg.Photo != nil { err := b.Download(msg.Photo, "./photo.jpg") } ``` -------------------------------- ### Handle and Query Boosts Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Methods for handling boost events and retrieving user boost information. ```go b.Handle(tele.OnBoost, func(c tele.Context) error { boost := c.Boost() return c.Send(fmt.Sprintf("Chat boosted %d times!", boost.Boost.Count)) }) boosts, err := b.UserBoosts(chat, user) ``` -------------------------------- ### Pass options to Send method Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Demonstrates passing multiple variadic options to the Send method. Later arguments override earlier ones. ```go // Multiple option types can be mixed msg, err := b.Send(user, "Text", tele.NoPreview, // Option flag tele.Silent, // Option flag tele.ModeHTML, // ParseMode &tele.ReplyMarkup{...}, // ReplyMarkup &tele.SendOptions{...}, // Full options ) ``` -------------------------------- ### Clone Telebot v3 Repository Source: https://github.com/tucnak/telebot/blob/v4/README.md Clone the v3 branch of the Telebot repository to start contributing. Ensure you are on the correct branch for v3 development. ```bash git clone -b v3 https://github.com/tucnak/telebot ``` -------------------------------- ### Handle Business connections Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Event handler for tracking business account connections. ```go b.Handle(tele.OnBusinessConnection, func(c tele.Context) error { conn := c.Update().ConnectedWebsite return nil }) ``` -------------------------------- ### Define Poller Interface Source: https://github.com/tucnak/telebot/blob/v4/README.md Defines the Poller interface which providers of Updates must implement. Poll() starts polling synchronously and must listen for a stop signal. ```go type Poller interface { Poll(b *Bot, updates chan Update, stop chan struct{}) } ``` -------------------------------- ### Create input field placeholder Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Generates SendOptions with a placeholder for force-reply mode. ```go func Placeholder(text string) *SendOptions ``` ```go msg, err := b.Send(user, "What's your name?", tele.Placeholder("Your name...")) ``` -------------------------------- ### Add Middleware Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/INDEX.md Applies middleware to the bot instance. ```go b.Use(myMiddleware) ``` -------------------------------- ### Rights Constructor Functions Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/types.md Helper functions for initializing Rights structures and time constants. ```go func NoRights() Rights func NoRestrictions() Rights func AdminRights() Rights func Forever() int64 ``` -------------------------------- ### Use() Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Registers global middleware that applies to all handlers. ```APIDOC ## func (b *Bot) Use(middleware ...MiddlewareFunc) ### Description Adds global middleware that applies to all handlers. Middleware runs in the order added. ### Parameters - **middleware** (...MiddlewareFunc) - Required - Middleware functions to be executed. ### Example ```go b.Use(myLogMiddleware) b.Use(myAuthMiddleware) ``` ``` -------------------------------- ### Settings Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Settings configures a Bot instance, including the API token, polling mechanism, error handling, and HTTP client configuration. ```APIDOC ## Settings ### Description Configures a Bot instance. ### Fields - **URL** (string) - Telegram API base URL (Default: "https://api.telegram.org") - **Token** (string) - Bot API token (Required) - **Updates** (int) - Update channel buffer (Default: 100) - **Poller** (Poller) - Update provider (Default: &LongPoller{}) - **Synchronous** (bool) - Run handlers sequentially (Default: false) - **Verbose** (bool) - Log all API requests (Default: false) - **ParseMode** (ParseMode) - Default text parsing mode (Default: "") - **OnError** (func) - Error handler callback (Default: defaultOnError) - **Client** (*http.Client) - HTTP client (Default: 1min timeout) - **Offline** (bool) - Skip token validation (Default: false) ``` -------------------------------- ### Create new ReplyMarkup Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Initializes an empty ReplyMarkup for use in messages. ```go func (b *Bot) NewMarkup() *ReplyMarkup ``` ```go markup := b.NewMarkup() markup.InlineKeyboard = [][]tele.InlineButton{...} ``` -------------------------------- ### Register Button Callback Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/INDEX.md Sets up a handler for inline button interactions. ```go btn := &tele.InlineButton{Unique: "id", Text: "Click"} b.Handle(&btn, func(c tele.Context) error { return c.Respond(&tele.CallbackResponse{Text: "Clicked!"}) }) ``` -------------------------------- ### Define Boost System Structures Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Data structures for tracking premium chat boosts and updates. ```go type Boost struct { ID int AddDate int64 ExpirationDate int64 Count int Source *BoostSource } type BoostUpdated struct { Chat *Chat Boost *Boost } type BoostRemoved struct { Chat *Chat BoostID string RemoveDate int64 Source *BoostSource } ``` -------------------------------- ### NewBot Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Creates a new Bot instance with the provided settings and validates the token. ```APIDOC ## NewBot ### Description Creates a new Bot instance with the given settings. Validates the token by calling getMe unless Offline mode is enabled. ### Signature `func NewBot(pref Settings) (*Bot, error)` ### Parameters - **pref** (Settings) - Required - Bot configuration ### Returns - **(*Bot, error)** - Bot instance and error if token is invalid or offline ### Example ```go b, err := tele.NewBot(tele.Settings{ Token: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11", Poller: &tele.LongPoller{Timeout: 10 * time.Second}, }) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Custom Poller Implementation Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/polling.md Demonstrates implementing the Poller interface to fetch updates from custom sources. ```go type MyPoller struct { // custom fields } func (p *MyPoller) Poll(b *tele.Bot, dest chan<- tele.Update, stop <-chan struct{}) error { for { select { case <-stop: return nil default: // Fetch update from custom source update := getUpdateFromSource() select { case dest <- update: case <-stop: return nil } } } } // Use custom poller b, _ := tele.NewBot(tele.Settings{ Token: "TOKEN", Poller: &MyPoller{}, }) ``` -------------------------------- ### Define WebApp structure Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md Represents a Web App button configuration containing the target URL. ```go type WebApp struct { URL string } ``` -------------------------------- ### Context Methods Reference Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/handlers.md Provides access to update data, recipient information, message content, and shortcut methods for interaction. ```go // Update accessors c.Update() Update // Original update c.Message() *Message // Current message (if any) c.Callback() *Callback // Callback (if OnCallback) c.Query() *Query // Inline query (if OnQuery) // Recipients c.Sender() *User // User who triggered update c.Chat() *Chat // Chat where update occurred c.Recipient() Recipient // Chat or user // Message content c.Text() string // Message text c.Data() string // Command args or callback data c.Args() []string // Parsed arguments c.Entities() Entities // Text entities (bold, links, etc.) // Send/edit shortcuts c.Send(what, opts...) error c.Reply(what, opts...) error c.Edit(what, opts...) error c.Delete() error // Callbacks c.Respond(resp) error ``` -------------------------------- ### Register Command Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/INDEX.md Defines a handler for a specific command string. ```go b.Handle("/start", func(c tele.Context) error { return c.Send("Welcome!") }) ``` -------------------------------- ### Register endpoints with Handle Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/handlers.md Method signature for registering handlers to commands, events, or buttons. ```go func (b *Bot) Handle(endpoint interface{}, h HandlerFunc, m ...MiddlewareFunc) ``` -------------------------------- ### Configure ReplyParams Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Demonstrates using ReplyParams to specify a message to reply to within SendOptions. ```go params := &tele.ReplyParams{ MessageID: 123, ChatID: chat.ID, } msg, err := b.Send(user, "Reply text", &tele.SendOptions{ ReplyParams: params, }) ``` -------------------------------- ### Send Media Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/INDEX.md Sends a photo file from the local disk. ```go photo := &tele.Photo{File: tele.FromDisk("photo.jpg")} msg, err := b.Send(user, photo) ``` -------------------------------- ### Send File from Disk Source: https://github.com/tucnak/telebot/blob/v4/README.md Creates an Audio object from a local file and sends it. Telebot automatically uploads the file and uses its FileID for subsequent sends. ```go a := &tele.Audio{File: tele.FromDisk("file.ogg")} fmt.Println(a.OnDisk()) // true fmt.Println(a.InCloud()) // false // Will upload the file from disk and send it to the recipient b.Send(recipient, a) // Next time you'll be sending this very *Audio, Telebot won't // re-upload the same file but rather utilize its Telegram FileID b.Send(otherRecipient, a) fmt.Println(a.OnDisk()) // true fmt.Println(a.InCloud()) // true fmt.Println(a.FileID) // ``` -------------------------------- ### Define PreviewOptions struct Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/options.md Structure used to control link preview generation in messages. ```go type PreviewOptions struct { Disabled bool URL string SmallMedia bool LargeMedia bool AboveText bool } ``` -------------------------------- ### Define Business account structures Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Data structures for managing business connections, intros, locations, and opening hours. ```go type BusinessConnection struct { ID string UserID int64 IsEnabled bool ConnectDate int64 } type BusinessIntro struct { Title string Message string Sticker *Sticker } type BusinessLocation struct { Address string Location *Location } type BusinessOpeningHours struct { TimeZoneID string OpeningHours []BusinessOpeningHoursInterval } ``` -------------------------------- ### Manage Bot Profile Information Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Methods and structures for managing bot names, descriptions, and short descriptions. ```go type BotInfo struct { ShortDescription string Description string } func (b *Bot) SetMyName(name, language string) error func (b *Bot) MyName(language string) (*BotInfo, error) func (b *Bot) SetMyDescription(desc, language string) error func (b *Bot) MyDescription(language string) (*BotInfo, error) func (b *Bot) SetMyShortDescription(desc, language string) error func (b *Bot) MyShortDescription(language string) (*BotInfo, error) ``` ```go err := b.SetMyName("My Bot", "en") err := b.SetMyDescription("This is my bot", "en") info, _ := b.MyDescription("en") ``` -------------------------------- ### Define Menu Button Types Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Defines the interface and structs for configuring the bot's menu button. ```go type MenuButton interface { menuButton() map[string]interface{} } type MenuButtonDefault struct{} type MenuButtonCommands struct{} type MenuButtonWebApp struct { Text string WebApp *WebApp } ``` -------------------------------- ### func (b *Bot) Download(file *File, localFilename string) error Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/media.md Downloads a file to the local filesystem. ```APIDOC ## func (b *Bot) Download(file *File, localFilename string) error ### Description Downloads a file to the local filesystem. ### Parameters - **file** (*File) - Required - File to download - **localFilename** (string) - Required - Local path to save to ### Returns - **error** - Error if download fails ### Example ```go msg := c.Message() if msg.Photo != nil { err := b.Download(msg.Photo, "./photo.jpg") } ``` ``` -------------------------------- ### Import the Telebot module Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/README.md Standard import statement for the Telebot v4 package. ```go import tele "gopkg.in/telebot.v4" ``` -------------------------------- ### Send Sticker Message Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Sends a sticker file from disk to a user. ```go sticker := &tele.Sticker{ File: tele.FromDisk("sticker.webp"), } msg, err := b.Send(user, sticker) ``` -------------------------------- ### func (b *Bot) Use(middleware ...MiddlewareFunc) Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/handlers.md Registers global middleware that applies to all handlers. Middleware functions are executed in the order they are registered. ```APIDOC ## func (b *Bot) Use(middleware ...MiddlewareFunc) ### Description Adds global middleware that applies to all handlers. Middleware runs in the order registered. ### Parameters - **middleware** (...MiddlewareFunc) - Required - Middleware functions to apply globally ### Example ```go b.Use(logMiddleware) b.Use(authMiddleware) // All subsequent handlers will have these middleware applied b.Handle("/cmd", handler) ``` ``` -------------------------------- ### Apply Global Middleware Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/core.md Defines the Use method for adding global middleware that applies to all handlers in the order they are added. ```go func (b *Bot) Use(middleware ...MiddlewareFunc) ``` -------------------------------- ### Handle Command with Arguments Source: https://github.com/tucnak/telebot/blob/v4/README.md Handles a /tags command and retrieves a list of space-separated arguments. Iterate through the arguments for processing. ```go b.Handle("/tags", func(c tele.Context) error { tags := c.Args() // list of arguments splitted by a space for _, tag := range tags { // iterate through passed arguments } }) ``` -------------------------------- ### Implement Middleware Functions Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/handlers.md Defines the structure for middleware that wraps handlers to perform pre- or post-processing. ```go type MiddlewareFunc func(HandlerFunc) HandlerFunc ``` ```go func MyMiddleware(next tele.HandlerFunc) tele.HandlerFunc { return func(c tele.Context) error { // Pre-processing err := next(c) // Call next handler // Post-processing return err } } ``` ```go // Logging middleware func logMiddleware(next tele.HandlerFunc) tele.HandlerFunc { return func(c tele.Context) error { log.Printf("User %d: %s", c.Sender().ID, c.Text()) return next(c) } } // Auth middleware func authMiddleware(next tele.HandlerFunc) tele.HandlerFunc { return func(c tele.Context) error { if !isAdmin(c.Sender().ID) { return c.Send("Not authorized") } return next(c) } } b.Use(logMiddleware) b.Handle("/admin", onAdmin, authMiddleware) ``` -------------------------------- ### Organize Handlers with Groups Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/api-interface.md Use Bot.Group() to apply middleware selectively to specific sets of command handlers. ```go // Public group public := b.Group() public.Handle("/help", helpHandler) public.Handle("/about", aboutHandler) // Admin group with auth middleware admin := b.Group() admin.Use(authMiddleware) admin.Handle("/ban", banHandler) admin.Handle("/kick", kickHandler) // Premium group with multiple middleware premium := b.Group() premium.Use(authMiddleware, premiumCheckMiddleware) premium.Handle("/premium_feature", premiumHandler) ``` -------------------------------- ### Define ReplyMarkup structure Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/keyboards.md The core structure used to define keyboard layouts and behavior settings. ```go type ReplyMarkup struct { InlineKeyboard [][]InlineButton ReplyKeyboard [][]ReplyButton ForceReply bool ResizeKeyboard bool OneTimeKeyboard bool RemoveKeyboard bool Selective bool Placeholder string IsPersistent bool } ``` -------------------------------- ### Define Callback Structure Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/callbacks.md Represents a user's response to an inline button click. ```go type Callback struct { ID string From *User Message *Message InlineMessageID string ChatInstance string MessageID int Data string GameShortName string } ``` -------------------------------- ### Manage Bot Lifecycle with Logout and Close Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Use these methods to terminate the bot session or close the connection. Both methods return a boolean success status and an error. ```go func (b *Bot) Logout() (bool, error) func (b *Bot) Close() (bool, error) ``` ```go // Logout success, err := b.Logout() // Close connection success, err := b.Close() ``` -------------------------------- ### Respond to a Callback Query Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/callbacks.md Responds to a callback query using the Respond method. Can be invoked from outside a handler. ```go func (b *Bot) Respond(c *Callback, resp ...*CallbackResponse) error ``` ```go if err := b.Respond(callback, &tele.CallbackResponse{ Text: "Done!", }); err != nil { log.Println(err) } ``` -------------------------------- ### NewContext Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/context.md Creates a new Context instance for a given Bot API and Update. ```APIDOC ## func NewContext(b API, u Update) Context ### Description Creates a new Context for the given Bot instance and Update. ### Parameters - **b** (API) - Required - Bot API interface - **u** (Update) - Required - Update to wrap ### Returns - **Context** - New context instance ### Example ```go ctx := tele.NewContext(b, update) ``` ``` -------------------------------- ### Define StarTransaction struct Source: https://github.com/tucnak/telebot/blob/v4/_autodocs/advanced.md Represents a Telegram Stars transaction structure. ```go type StarTransaction struct { ID string Amount int Date int64 Source *TransactionPartner Receiver *TransactionPartner } ```