### Quick Start Bot Example Source: https://github.com/amarnathcjd/gogram/blob/master/README.md A basic example demonstrating how to initialize a Gogram client, log in as a bot, and set up a message handler for private messages. The client will block the main goroutine until it's closed. ```golang package main import "github.com/amarnathcjd/gogram/telegram" func main() { client, err := telegram.NewClient(telegram.ClientConfig{ AppID: 6, AppHash: "", }) if err != nil { log.Fatal(err) } client.Conn() client.LoginBot("") // or client.Login("") for user account, or client.AuthPrompt() for interactive login client.On(telegram.OnMessage, func(message *telegram.NewMessage) error { // client.AddMessageHandler message.Reply("Hello from Gogram!") return nil }, telegram.IsPrivate) // waits for private messages only client.Idle() // block main goroutine until client is closed } ``` -------------------------------- ### Install Gogram Library Source: https://github.com/amarnathcjd/gogram/blob/master/README.md Install the Gogram library using go get. Requires Go 1.18 or later. ```bash go get -u github.com/amarnathcjd/gogram/telegram ``` -------------------------------- ### Handle Telegram Inline Queries Source: https://github.com/amarnathcjd/gogram/blob/master/README.md Set up a handler for inline queries using a pattern. This example shows how to build and return articles as results for the inline query. ```golang // inline queries client.On("inline:", func(iq *telegram.InlineQuery) error { // client.AddInlineHandler builder := iq.Builder() builder.Article("", "<description>", "<text>", &telegram.ArticleOptions{ LinkPreview: true, }) return nil }) ``` -------------------------------- ### Handle Telegram Callback Queries Source: https://github.com/amarnathcjd/gogram/blob/master/README.md Register a handler for callback queries matching a specific pattern. This example demonstrates how to answer a callback query, optionally with an alert. ```golang // callback queries client.On("callback:<pattern>", func(cb *telegram.CallbackQuery) error { // client.AddCallbackHandler cb.Answer("This is a callback response", &CallbackOptions{ Alert: true, }) return nil }) ``` -------------------------------- ### HandlerGroup Source: https://context7.com/amarnathcjd/gogram/llms.txt Allows grouping handlers that share common configurations such as filters, middleware, and priority. This simplifies the setup for related handlers. ```APIDOC ## HandlerGroup — Grouped handlers with shared config `NewGroup` creates a handler group where all registered handlers share the same filters, middleware, and priority. ```go adminGroup := client.NewGroup(). Filter(telegram.FromUsers(123456789)). Use(func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { log.Println("Admin action from", m.SenderID()) return next(m) } }) adminGroup.OnCommand("ban", func(m *telegram.NewMessage) error { m.Reply("User banned.") return nil }) adminGroup.OnCommand("unban", func(m *telegram.NewMessage) error { m.Reply("User unbanned.") return nil }) ``` ``` -------------------------------- ### Register Message Update Handler Source: https://context7.com/amarnathcjd/gogram/llms.txt Registers a handler for all incoming new messages. Logs the chat ID, sender ID, and message text. Ensure `client.Idle()` is called to start processing updates. ```go // Handle all incoming messages client.On(telegram.OnMessage, func(m *telegram.NewMessage) error { log.Printf("[%d] %s: %s", m.ChatID(), m.SenderID(), m.MessageText()) return nil }) ``` -------------------------------- ### Retrieve Specific Messages with gogram Source: https://context7.com/amarnathcjd/gogram/llms.txt Fetch messages by their unique ID, retrieve the currently pinned message in a chat, or get all messages belonging to a media album group. Handles potential errors during retrieval. ```go // Fetch one message by ID msg, err := client.GetMessageByID("@channel", 42) log.Println(msg.MessageText()) ``` ```go // Get the pinned message in a chat pinned, err := client.GetPinnedMessage("@group") log.Println("Pinned:", pinned.MessageText()) ``` ```go // Get all messages in a media album album, err := client.GetMediaGroup("@channel", 100) // any message ID in the album for _, m := range album { log.Printf("Album item %d: %s", m.ID, m.File.Name) } ``` -------------------------------- ### QuickBot / QuickPhone - One-call client initialization Source: https://context7.com/amarnathcjd/gogram/llms.txt Creates a client and logs in in one call. `QuickBot` is for bot accounts, and `QuickPhone` is for user accounts using a phone number. ```APIDOC ## QuickBot / QuickPhone ### Description `QuickBot` creates a client and logs in as a bot in one call. `QuickPhone` does the same for user phone-number login. ### Method `QuickBot(appID int, appHash string, botToken string) (*Client, error)` `QuickPhone(appID int, appHash string, phoneNumber string) (*Client, error)` ### Parameters #### QuickBot - **appID** (int) - Required - Your Telegram application ID. - **appHash** (string) - Required - Your Telegram application hash. - **botToken** (string) - Required - Your Telegram bot token. #### QuickPhone - **appID** (int) - Required - Your Telegram application ID. - **appHash** (string) - Required - Your Telegram application hash. - **phoneNumber** (string) - Required - The phone number to log in with. ### Request Example ```go // Bot login (single call) client, err := telegram.QuickBot(12345, "your_app_hash", "110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw") if err != nil { log.Fatal(err) } defer client.Idle() // User (phone number) login client, err := telegram.QuickPhone(12345, "your_app_hash", "+14155552671") if err != nil { log.Fatal(err) } ``` ### Response #### Success Response - **Client** (*telegram.Client) - An initialized and logged-in Telegram client instance. - **error** - An error if initialization or login fails. ``` -------------------------------- ### Handle /start Command in Private Chats with Middleware Source: https://context7.com/amarnathcjd/gogram/llms.txt Registers a handler specifically for the /start command in private chats. It includes a middleware function to log the sender's ID before processing the command. The bot replies with a "Hello! Bot is online." message. ```go // Handle /start command only in private chats, with middleware client.On("message:/start", func(m *telegram.NewMessage) error { m.Reply("<b>Hello!</b> Bot is online.") return nil }).Filter(telegram.IsPrivate).Use(func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { log.Println("incoming /start from", m.SenderID()) return next(m) } }) ``` -------------------------------- ### Handle Inline Queries Source: https://context7.com/amarnathcjd/gogram/llms.txt Handle inline queries using client.On with an "inline:" prefix. Use the builder to create results like articles or photos. ```go client.On("inline:", func(iq *telegram.InlineQuery) error { builder := iq.Builder() builder.Article( "Result Title", "Short description shown in list", fmt.Sprintf("You searched for: <b>%s</b>", iq.Query), &telegram.ArticleOptions{LinkPreview: false}, ) builder.Photo("https://example.com/photo.jpg", &telegram.PhotoOptions{ Caption: "A photo result", }) return builder.Answer() }) ``` ```go // Pattern-matched inline handler client.On("inline:^search (.+)$", func(iq *telegram.InlineQuery) error { query := iq.Query builder := iq.Builder() builder.Article("Search: "+query, "Click to send", "Result for: "+query, nil) return builder.Answer(&telegram.InlineSendOptions{CacheTime: 10}) }) ``` -------------------------------- ### NewClient - Create and configure a Telegram client Source: https://context7.com/amarnathcjd/gogram/llms.txt Initializes the MTProto client, sets up the peer cache, update dispatcher, and optionally connects immediately. Credentials are obtained from my.telegram.org. ```APIDOC ## NewClient ### Description Initializes the MTProto client, sets up the peer cache, update dispatcher, and optionally connects immediately. Credentials (`AppID`, `AppHash`) are obtained from [my.telegram.org](https://my.telegram.org). ### Method `NewClient` ### Parameters #### Request Body - **ClientConfig** (struct) - Required - Configuration for the Telegram client. - **AppID** (int) - Required - Your Telegram application ID. - **AppHash** (string) - Required - Your Telegram application hash. - **Session** (string) - Optional - Path to the session file for persistence. - **ParseMode** (string) - Optional - Default parse mode for messages (e.g., "HTML"). - **LogLevel** (int) - Optional - Sets the logging level (e.g., `telegram.LogInfo`). ### Request Example ```go client, err := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "your_app_hash_here", Session: "my_session.session", // persists auth to disk ParseMode: "HTML", // default parse mode for messages LogLevel: telegram.LogInfo, }) if err != nil { log.Fatal(err) } if err := client.Connect(); err != nil { log.Fatal(err) } defer client.Disconnect() ``` ### Response #### Success Response - **Client** (*telegram.Client) - An initialized Telegram client instance. - **error** - An error if initialization fails. ``` -------------------------------- ### Quick Bot and Phone Login Source: https://context7.com/amarnathcjd/gogram/llms.txt Provides one-call functions for initializing and logging in as a bot (QuickBot) or a user via phone number (QuickPhone). ```go // Bot login (single call) client, err := telegram.QuickBot(12345, "your_app_hash", "110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw") if err != nil { log.Fatal(err) } defer client.Idle() // User (phone number) login client, err := telegram.QuickPhone(12345, "your_app_hash", "+14155552671") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Keyboard Builder Source: https://context7.com/amarnathcjd/gogram/llms.txt Construct inline and reply keyboards with rows, columns, and grids using the `NewKeyboard` builder. ```APIDOC ## Keyboard Builder — Construct reply and inline keyboards `NewKeyboard` / `KeyboardBuilder` builds inline and reply keyboards with rows, columns, and grids. ```go // Inline keyboard with mixed button types inlineKb := telegram.NewKeyboard(). AddRow( telegram.Button.Inline("Callback", "cb_data"), telegram.Button.URL("Open Link", "https://example.com"), ). AddRow(telegram.Button.SwitchInline("Share", "query")), .Build() // returns *ReplyInlineMarkup // Reply keyboard with grid layout (3 rows × 2 cols) replyKb := telegram.NewKeyboard(). NewGrid(3, 2, telegram.Button.Reply("🏠 Home"), telegram.Button.Reply("📝 Register"), telegram.Button.Reply("â„šī¸ Info"), telegram.Button.Reply("âš™ī¸ Settings"), telegram.Button.Reply("📞 Contact"), telegram.Button.Reply("❌ Cancel"), ). BuildReply(telegram.BuildReplyOptions{ ResizeKeyboard: true, OneTime: false, }) client.SendMessage("username", "Choose:", &telegram.SendOptions{ ReplyMarkup: inlineKb, }) ``` ``` -------------------------------- ### Fluent Client Configuration with ClientConfigBuilder Source: https://context7.com/amarnathcjd/gogram/llms.txt Uses ClientConfigBuilder for a chainable API to construct client configurations. Allows setting session, parse mode, log level, data center, sleep threshold, and flood wait handlers. ```go config := telegram.NewClientConfigBuilder(12345, "your_app_hash"). WithSession("bot.session"). WithParseMode("HTML"). WithLogLevel(telegram.LogDebug). WithDataCenter(4). WithSleepThresholdMs(5000). WithFloodHandler(func(err error) bool { log.Println("flood wait, retrying:", err) return true // return true to auto-retry after waiting }). Build() client, err := telegram.NewClient(config) ``` -------------------------------- ### Build Inline and Reply Keyboards with gogram Source: https://context7.com/amarnathcjd/gogram/llms.txt Use NewKeyboard/KeyboardBuilder to construct inline and reply keyboards with custom layouts. Supports mixed button types for inline keyboards and grid layouts for reply keyboards. ```go inlineKb := telegram.NewKeyboard(). AddRow( telegram.Button.Inline("Callback", "cb_data"), telegram.Button.URL("Open Link", "https://example.com"), ). AddRow(telegram.Button.SwitchInline("Share", "query")), Build() // returns *ReplyInlineMarkup ``` ```go replyKb := telegram.NewKeyboard(). NewGrid(3, 2, telegram.Button.Reply("🏠 Home"), telegram.Button.Reply("📝 Register"), telegram.Button.Reply("â„šī¸ Info"), telegram.Button.Reply("âš™ī¸ Settings"), telegram.Button.Reply("📞 Contact"), telegram.Button.Reply("❌ Cancel"), ). BuildReply(telegram.BuildReplyOptions{ ResizeKeyboard: true, OneTime: false, }) ``` ```go client.SendMessage("username", "Choose:", &telegram.SendOptions{ ReplyMarkup: inlineKb, }) ``` -------------------------------- ### Proxy Configuration Source: https://context7.com/amarnathcjd/gogram/llms.txt Configure SOCKS5, HTTP, or MTProxy connections via `ClientConfig` or `SetProxy`. ```APIDOC ## Proxy configuration — SOCKS5, HTTP, MTProxy Configure a proxy in `ClientConfig` or via `SetProxy`. ```go client, err := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "hash", Proxy: telegram.Socks5Proxy("proxy.example.com", 1080, "user", "pass"), }) // MTProxy with secret client2, _ := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "hash", Proxy: telegram.MTProxy("mtproxy.example.com", 443, "secret_hex_string"), }) // Set proxy at runtime client.SetProxy(telegram.HTTPProxy("proxy.example.com", 8080, "", "")) ``` ``` -------------------------------- ### ClientConfigBuilder - Fluent client configuration Source: https://context7.com/amarnathcjd/gogram/llms.txt Provides a chainable builder API for constructing `ClientConfig` without raw struct literals. ```APIDOC ## ClientConfigBuilder ### Description `NewClientConfigBuilder` provides a chainable builder API for constructing `ClientConfig` without raw struct literals. ### Method `NewClientConfigBuilder(appID int, appHash string)` ### Parameters #### Path Parameters - **appID** (int) - Required - Your Telegram application ID. - **appHash** (string) - Required - Your Telegram application hash. ### Chainable Methods - **WithSession(session string)**: Sets the session file path. - **WithParseMode(parseMode string)**: Sets the default parse mode. - **WithLogLevel(level int)**: Sets the logging level. - **WithDataCenter(dc int)**: Sets the data center ID. - **WithSleepThresholdMs(threshold int)**: Sets the sleep threshold in milliseconds. - **WithFloodHandler(handler func(error) bool)**: Sets a custom flood wait handler. ### Build Method - **Build() ClientConfig**: Returns the constructed `ClientConfig` struct. ### Request Example ```go config := telegram.NewClientConfigBuilder(12345, "your_app_hash"). WithSession("bot.session"). WithParseMode("HTML"). WithLogLevel(telegram.LogDebug). WithDataCenter(4). WithSleepThresholdMs(5000). WithFloodHandler(func(err error) bool { log.Println("flood wait, retrying:", err) return true // return true to auto-retry after waiting }). Build() client, err := telegram.NewClient(config) ``` ``` -------------------------------- ### Configure Telegram Client Proxy Settings Source: https://context7.com/amarnathcjd/gogram/llms.txt Set up proxy connections (SOCKS5, HTTP, MTProxy) for the Telegram client during initialization or at runtime. Supports authentication for SOCKS5 and secret keys for MTProxy. ```go client, err := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "hash", Proxy: telegram.Socks5Proxy("proxy.example.com", 1080, "user", "pass"), }) ``` ```go // MTProxy with secret client2, _ := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "hash", Proxy: telegram.MTProxy("mtproxy.example.com", 443, "secret_hex_string"), }) ``` ```go // Set proxy at runtime client.SetProxy(telegram.HTTPProxy("proxy.example.com", 8080, "", "")) ``` -------------------------------- ### Send Telegram Media and Albums Source: https://github.com/amarnathcjd/gogram/blob/master/README.md This snippet demonstrates how to send media files, including setting captions and TTL for one-time media. It also shows how to send an album of media and how to implement progress tracking for media uploads. ```golang // sending media client.SendMedia("username", "<file-name>", &telegram.MediaOptions{ // filename/inputmedia,... Caption: "Hello from Gogram!", TTL: int32((math.Pow(2, 31) - 1)), // TTL For OneTimeMedia }) client.SendAlbum("username", []string{"<file-name>", "<file-name>"}, &telegram.MediaOptions{ // Array of filenames/inputmedia,... Caption: "Hello from Gogram!", }) // with progress var pm *telegram.ProgressManager client.SendMedia("username", "<file-name>", &telegram.MediaOptions{ Progress: func(a,b int) { if pm == nil { pm = telegram.NewProgressManager(a, 3) // 3 is edit interval } if pm.ShouldEdit(b) { fmt.Println(pm.GetStats(b)) // client.EditMessage("<chat-id>", "<message-id>", pm.GetStats()) } }, }) ``` -------------------------------- ### Create and Connect Telegram Client Source: https://context7.com/amarnathcjd/gogram/llms.txt Initializes and connects a Telegram MTProto client using NewClient. Requires AppID, AppHash, and session details. Logs in and retrieves user information. ```go package main import ( "log" "github.com/amarnathcjd/gogram/telegram" ) func main() { client, err := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "your_app_hash_here", Session: "my_session.session", // persists auth to disk ParseMode: "HTML", // default parse mode for messages LogLevel: telegram.LogInfo, }) if err != nil { log.Fatal(err) } if err := client.Connect(); err != nil { log.Fatal(err) } defer client.Disconnect() me, _ := client.GetMe() log.Printf("Logged in as: %s (id=%d)", me.Username, me.ID) } ``` -------------------------------- ### Bot and Phone Number Authentication Source: https://context7.com/amarnathcjd/gogram/llms.txt Demonstrates different authentication methods: LoginBot for bot tokens, Login for phone numbers with custom callbacks for OTP and 2FA, and AuthPrompt for interactive terminal-based authentication. ```go // Bot token auth if err := client.Connect(); err != nil { log.Fatal(err) } if err := client.LoginBot("110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"); err != nil { log.Fatal(err) } // Phone number auth with custom code/password callbacks ok, err := client.Login("+14155552671", &telegram.LoginOptions{ CodeCallback: func() (string, error) { var code string fmt.Print("Enter OTP: ") fmt.Scan(&code) return code, nil }, PasswordCallback: func() (string, error) { var pwd string fmt.Print("Enter 2FA password: ") fmt.Scan(&pwd) return pwd, nil }, MaxRetries: 3, }) if err != nil || !ok { log.Fatal("login failed:", err) } // Interactive terminal prompt (auto-detects bot token vs phone number) if err := client.AuthPrompt(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Send Media Files Source: https://context7.com/amarnathcjd/gogram/llms.txt Upload and send various media types like photos, documents, and videos. Supports local paths, URLs, and raw input. Options include captions, parse modes, forcing documents, and upload progress callbacks. ```go // Send a photo from file path msg, err := client.SendMedia("username", "photo.jpg", &telegram.MediaOptions{ Caption: "<b>My photo</b>", ParseMode: "HTML", }) ``` ```go // Send a document, force-document to avoid embedding msg, err = client.SendMedia(123456789, "report.pdf", &telegram.MediaOptions{ Caption: "Monthly report", ForceDocument: true, FileName: "report_2024.pdf", }) ``` ```go // Send with upload progress callback msg, err = client.SendMedia("@channel", "bigvideo.mp4", &telegram.MediaOptions{ Caption: "Big video", Upload: &telegram.UploadOptions{ Threads: 4, ProgressCallback: func(p *telegram.ProgressInfo) { log.Printf("Upload: %.1f%% (%d/%d bytes)", p.Percentage, p.Uploaded, p.Total) }, ProgressInterval: 2, // report every 2 seconds }, }) ``` ```go // Send with self-destruct TTL (once-view media) _, err = client.SendMedia("username", "secret.jpg", &telegram.MediaOptions{ TTL: 30, // seconds Spoiler: true, }) ``` -------------------------------- ### Handle Callback Query for Inline Buttons Source: https://context7.com/amarnathcjd/gogram/llms.txt Register handlers for inline button clicks using client.On with a "callback:" prefix. Handlers can answer callbacks and edit messages. ```go // Send a message with inline buttons keyboard := telegram.NewKeyboard(). AddRow( telegram.Button.Inline("✅ Accept", "accept"), telegram.Button.Inline("❌ Reject", "reject"), ).Build() client.SendMessage("username", "Please confirm:", &telegram.SendOptions{ ReplyMarkup: keyboard, }) ``` ```go // Handle "accept" button client.On("callback:accept", func(cb *telegram.CallbackQuery) error { cb.Answer("You accepted!", &telegram.CallbackOptions{Alert: false}) client.EditMessage(cb.ChatID, cb.MessageID, "✅ Accepted!") return nil }) ``` ```go // Handle any callback with regex client.On("callback:^action_\d+$", func(cb *telegram.CallbackQuery) error { cb.Answer(fmt.Sprintf("Action data: %s", cb.Data), &telegram.CallbackOptions{Alert: true}) return nil }) ``` -------------------------------- ### Export and Import Telegram Session Source: https://context7.com/amarnathcjd/gogram/llms.txt Demonstrates how to export the current client session to a base64 string and later import it into a new client instance to resume the session. The exported string should be stored securely. ```go // Export session to string sessionStr := client.ExportStringSession() log.Println("Session:", sessionStr) // store this securely // Later, import it into a new client client2, _ := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "your_app_hash", StringSession: sessionStr, }) client2.Connect() me, _ := client2.GetMe() log.Println("Resumed as:", me.Username) ``` -------------------------------- ### Middleware Source: https://context7.com/amarnathcjd/gogram/llms.txt Implement cross-cutting handler logic for logging, rate-limiting, and authentication using global or per-handler middleware. ```APIDOC ## Middleware — Cross-cutting handler logic Middleware wraps handlers for logging, rate-limiting, auth checks, etc. Global middleware runs for all message events; per-handler middleware is added via `.Use()`. ```go // Global middleware (applied to all OnMessage handlers) client.Use(func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { start := time.Now() err := next(m) log.Printf("handler took %s (chat=%d)", time.Since(start), m.ChatID()) return err } }) // Per-handler auth middleware authMiddleware := func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { if m.SenderID() != 123456789 { m.Reply("Unauthorized.") return nil } return next(m) } } client.On("message:/admin", func(m *telegram.NewMessage) error { m.Reply("Welcome, admin!") return nil }).Use(authMiddleware) ``` ``` -------------------------------- ### Create Interactive Conversations Source: https://context7.com/amarnathcjd/gogram/llms.txt Use NewConversation to manage multi-step dialogs. Conversations have timeouts and can be aborted with specific keywords. ```go client.On("message:/register", func(m *telegram.NewMessage) error { conv, err := client.NewConversation(m.ChatID(), &telegram.ConversationOptions{ Timeout: 60, AbortKeywords: []string{"cancel", "exit"}, }) if err != nil { return err } defer conv.Close() m.Reply("What is your name?") nameMsg, err := conv.GetResponse() if err != nil { m.Reply("Timed out or cancelled.") return nil } m.Reply(fmt.Sprintf("Hello, %s! How old are you?", nameMsg.MessageText())) ageMsg, err := conv.GetResponse() if err != nil { m.Reply("Timed out.") return nil } m.Reply(fmt.Sprintf("Registered: %s, age %s", nameMsg.MessageText(), ageMsg.MessageText())) return nil }, telegram.IsPrivate) ``` -------------------------------- ### Create Handler Group with Shared Configuration Source: https://context7.com/amarnathcjd/gogram/llms.txt Creates a handler group for administrators, applying a filter for specific user IDs and a middleware to log admin actions. Commands like "ban" and "unban" are registered within this group. ```go adminGroup := client.NewGroup(). Filter(telegram.FromUsers(123456789)). Use(func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { log.Println("Admin action from", m.SenderID()) return next(m) } }) adminGroup.OnCommand("ban", func(m *telegram.NewMessage) error { m.Reply("User banned.") return nil }) adminGroup.OnCommand("unban", func(m *telegram.NewMessage) error { m.Reply("User unbanned.") return nil }) ``` -------------------------------- ### Callback Query Handlers Source: https://context7.com/amarnathcjd/gogram/llms.txt Register handlers that fire when users click inline keyboard buttons. The pattern is matched against the callback data. ```APIDOC ## Callback Query handlers — Handle inline button clicks Register handlers that fire when users click inline keyboard buttons. The pattern is matched against the callback data. ```go // Send a message with inline buttons keyboard := telegram.NewKeyboard(). AddRow( telegram.Button.Inline("✅ Accept", "accept"), telegram.Button.Inline("❌ Reject", "reject"), ).Build() client.SendMessage("username", "Please confirm:", &telegram.SendOptions{ ReplyMarkup: keyboard, }) // Handle "accept" button client.On("callback:accept", func(cb *telegram.CallbackQuery) error { cb.Answer("You accepted!", &telegram.CallbackOptions{Alert: false}) client.EditMessage(cb.ChatID, cb.MessageID, "✅ Accepted!") return nil }) // Handle any callback with regex client.On("callback:^action_\d+$", func(cb *telegram.CallbackQuery) error { cb.Answer(fmt.Sprintf("Action data: %s", cb.Data), &telegram.CallbackOptions{Alert: true}) return nil }) ``` ``` -------------------------------- ### Export and Import Telegram Session Strings Source: https://context7.com/amarnathcjd/gogram/llms.txt Ensure session portability by exporting the current session to a string and importing it into a new process. Handles errors during the import process. ```go // Export current session sessionStr := client.ExportStringSession() log.Println("Save this:", sessionStr) ``` ```go // Import in a new process ok, err := client.ImportStringSession(sessionStr) if err != nil || !ok { log.Fatal("session import failed") } ``` -------------------------------- ### Send Telegram Messages Source: https://github.com/amarnathcjd/gogram/blob/master/README.md Use this to send text messages or dice emojis to a specified username. It also shows how to set up a message handler for the /start command. ```golang // sending a message client.SendMessage("username", "Hello from Gogram!") client.SendDice("username", "🎲") client.On("message:/start", func(m *telegram.NewMessage) error { m.Reply("Hello from Gogram!") // m.Respond("...") return nil }) ``` -------------------------------- ### Implement Global and Per-Handler Middleware in gogram Source: https://context7.com/amarnathcjd/gogram/llms.txt Enhance message handling logic with middleware for tasks like logging, rate-limiting, or authentication. Global middleware applies to all handlers, while per-handler middleware is attached using `.Use()`. ```go // Global middleware (applied to all OnMessage handlers) client.Use(func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { start := time.Now() err := next(m) log.Printf("handler took %s (chat=%d)", time.Since(start), m.ChatID()) return err } }) ``` ```go // Per-handler auth middleware authMiddleware := func(next telegram.MessageHandler) telegram.MessageHandler { return func(m *telegram.NewMessage) error { if m.SenderID() != 123456789 { m.Reply("Unauthorized.") return nil } return next(m) } } client.On("message:/admin", func(m *telegram.NewMessage) error { m.Reply("Welcome, admin!") return nil }).Use(authMiddleware) ``` -------------------------------- ### Session export/import Source: https://context7.com/amarnathcjd/gogram/llms.txt Allows exporting the current session to a base64 string for reuse across different processes or machines. The imported session can be used to resume the client's state. ```APIDOC ## Session export/import — Portable session strings Export the current session to a base64 string for reuse across processes or machines. ```go // Export session to string sessionStr := client.ExportStringSession() log.Println("Session:", sessionStr) // store this securely // Later, import it into a new client client2, _ := telegram.NewClient(telegram.ClientConfig{ AppID: 12345, AppHash: "your_app_hash", StringSession: sessionStr, }) client2.Connect() me, _ := client2.GetMe() log.Println("Resumed as:", me.Username) ``` ``` -------------------------------- ### JoinChannel / LeaveChannel Source: https://context7.com/amarnathcjd/gogram/llms.txt Join or leave a channel or group by username, invite link, or ID. ```APIDOC ## JoinChannel / LeaveChannel — Channel management Join or leave a channel or group by username, invite link, or ID. ```go // Join by username ch, err := client.JoinChannel("@golang") if err != nil { log.Fatal(err) } log.Println("Joined:", ch.Title) // Join by invite link ch, err = client.JoinChannel("https://t.me/+AbCdEfGhIjKlMnOp") // Leave a channel _, err = client.LeaveChannel("@golang") ``` ``` -------------------------------- ### Send HTML-Formatted Message with Inline Keyboard Source: https://context7.com/amarnathcjd/gogram/llms.txt Sends an HTML-formatted message to a user ID, including an inline keyboard with clickable buttons and a URL button. It also enables link previews and is not silent. Error handling is included. ```go // HTML-formatted message with reply and inline keyboard keyboard := telegram.NewKeyboard(). AddRow(telegram.Button.Inline("Click Me", "btn_data")), AddRow(telegram.Button.URL("Visit", "https://example.com")), Build() msg, err = client.SendMessage(123456789, "<b>Bold</b> and <i>italic</i> text", &telegram.SendOptions{ ParseMode: "HTML", ReplyMarkup: keyboard, LinkPreview: true, Silent: false, }) ``` -------------------------------- ### Conversation Source: https://context7.com/amarnathcjd/gogram/llms.txt Creates a stateful conversation flow that awaits sequential user responses. ```APIDOC ## Conversation — Interactive multi-step dialogs `NewConversation` creates a stateful conversation flow that awaits sequential user responses. ```go client.On("message:/register", func(m *telegram.NewMessage) error { conv, err := client.NewConversation(m.ChatID(), &telegram.ConversationOptions{ Timeout: 60, AbortKeywords: []string{"cancel", "exit"}, }) if err != nil { return err } defer conv.Close() m.Reply("What is your name?") nameMsg, err := conv.GetResponse() if err != nil { m.Reply("Timed out or cancelled.") return nil } m.Reply(fmt.Sprintf("Hello, %s! How old are you?", nameMsg.MessageText())) ageMsg, err := conv.GetResponse() if err != nil { m.Reply("Timed out.") return nil } m.Reply(fmt.Sprintf("Registered: %s, age %s", nameMsg.MessageText(), ageMsg.MessageText())) return nil }, telegram.IsPrivate) ``` ``` -------------------------------- ### SendMedia Source: https://context7.com/amarnathcjd/gogram/llms.txt Uploads and sends any media type, including local file paths, URLs, InputFile, or raw InputMedia. Supports captions, force-document option, and upload progress callbacks. ```APIDOC ## SendMedia — Send files, photos, and documents `SendMedia` uploads and sends any media type: local file paths, URLs, `InputFile`, or raw `InputMedia`. ```go // Send a photo from file path msg, err := client.SendMedia("username", "photo.jpg", &telegram.MediaOptions{ Caption: "<b>My photo</b>", ParseMode: "HTML", }) // Send a document, force-document to avoid embedding msg, err = client.SendMedia(123456789, "report.pdf", &telegram.MediaOptions{ Caption: "Monthly report", ForceDocument: true, FileName: "report_2024.pdf", }) // Send with upload progress callback msg, err = client.SendMedia("@channel", "bigvideo.mp4", &telegram.MediaOptions{ Caption: "Big video", Upload: &telegram.UploadOptions{ Threads: 4, ProgressCallback: func(p *telegram.ProgressInfo) { log.Printf("Upload: %.1f%% (%d/%d bytes)", p.Percentage, p.Uploaded, p.Total) }, ProgressInterval: 2, // report every 2 seconds }, }) // Send with self-destruct TTL (once-view media) _, err = client.SendMedia("username", "secret.jpg", &telegram.MediaOptions{ TTL: 30, // seconds Spoiler: true, }) ``` ``` -------------------------------- ### ExportStringSession / ImportStringSession Source: https://context7.com/amarnathcjd/gogram/llms.txt Export and import the current session string for portability across different processes or machines. ```APIDOC ## ExportStringSession / ImportStringSession — Session portability ```go // Export current session sessionStr := client.ExportStringSession() log.Println("Save this:", sessionStr) // Import in a new process ok, err := client.ImportStringSession(sessionStr) if err != nil || !ok { log.Fatal("session import failed") } ``` ``` -------------------------------- ### Grant Admin Permissions Source: https://github.com/amarnathcjd/gogram/wiki/Admin-Permissions Use this snippet to grant administrator privileges to a user in a chat or channel. Ensure the `channel` and `who` variables are correctly set. ```golang client.EditAdmin(channel, who, &telegram.AdminOptions{IsAdmin: true}) ``` -------------------------------- ### LoginBot / Login / AuthPrompt - Authentication Source: https://context7.com/amarnathcjd/gogram/llms.txt Handles authentication for the Telegram client. `LoginBot` uses a bot token, `Login` uses phone number and OTP (with optional 2FA), and `AuthPrompt` provides an interactive terminal helper. ```APIDOC ## Authentication Methods ### Description `LoginBot` authenticates using a bot token. `Login` uses phone-number + OTP (with optional 2FA). `AuthPrompt` is an interactive terminal helper that accepts either format. ### Methods #### `LoginBot(botToken string) error` Authenticates the client using a bot token. #### `Login(phoneNumber string, options *LoginOptions) (bool, error)` Authenticates the client using a phone number. Requires callbacks for OTP and 2FA password if needed. #### `AuthPrompt() error` Provides an interactive terminal prompt to handle authentication, auto-detecting bot token or phone number login. ### Parameters #### `Login` Method Options (`LoginOptions` struct) - **CodeCallback** (func() (string, error)) - Callback function to retrieve the authentication code. - **PasswordCallback** (func() (string, error)) - Callback function to retrieve the 2FA password. - **MaxRetries** (int) - Optional - Maximum number of retries for authentication. ### Request Example ```go // Bot token auth if err := client.Connect(); err != nil { log.Fatal(err) } if err := client.LoginBot("110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"); err != nil { log.Fatal(err) } // Phone number auth with custom code/password callbacks ok, err := client.Login("+14155552671", &telegram.LoginOptions{ CodeCallback: func() (string, error) { var code string fmt.Print("Enter OTP: ") fmt.Scan(&code) return code, nil }, PasswordCallback: func() (string, error) { var pwd string fmt.Print("Enter 2FA password: ") fmt.Scan(&pwd) return pwd, nil }, MaxRetries: 3, }) if err != nil || !ok { log.Fatal("login failed:", err) } // Interactive terminal prompt (auto-detects bot token vs phone number) if err := client.AuthPrompt(); err != nil { log.Fatal(err) } ``` ### Response #### Success Response - **LoginBot**: No explicit return value on success, error indicates failure. - **Login**: `true` if login is successful, `false` otherwise. - **AuthPrompt**: No explicit return value on success, error indicates failure. - **error** - An error if authentication fails. ``` -------------------------------- ### Generate QR Code Login Token Source: https://context7.com/amarnathcjd/gogram/llms.txt Generates a QR code for user authorization via another Telegram session. Requires a 2FA password callback and sets a timeout. The QR code is printed to the console and the function waits for user login confirmation. ```go qr, err := client.QRLogin(telegram.QrOptions{ PasswordCallback: func() (string, error) { var pwd string fmt.Print("2FA Password: ") fmt.Scan(&pwd) return pwd, nil }, Timeout: 120, // seconds }) if err != nil { log.Fatal(err) } qr.PrintToConsole() // prints QR as ASCII to terminal // Wait for the user to scan and approve if err := qr.WaitLogin(); err != nil { log.Fatal("QR login failed:", err) } log.Println("QR login successful") ``` -------------------------------- ### Join and Leave Telegram Channels Source: https://context7.com/amarnathcjd/gogram/llms.txt Manage channel subscriptions using JoinChannel and LeaveChannel. Supports joining via username, invite link, or channel ID. Errors are returned for failed operations. ```go // Join by username ch, err := client.JoinChannel("@golang") if err != nil { log.Fatal(err) } log.Println("Joined:", ch.Title) ``` ```go // Join by invite link ch, err = client.JoinChannel("https://t.me/+AbCdEfGhIjKlMnOp") ``` ```go // Leave a channel _, err = client.LeaveChannel("@golang") ``` -------------------------------- ### Send Media Albums Source: https://context7.com/amarnathcjd/gogram/llms.txt Send multiple media files as a single grouped album message. Supports basic captions and per-item captions. ```go msgs, err := client.SendAlbum("@channel", []string{ "photo1.jpg", "photo2.jpg", "photo3.jpg", }, &telegram.MediaOptions{ Caption: "Holiday photos đŸ–ī¸", }) if err != nil { log.Fatal(err) } log.Printf("Sent album with %d messages", len(msgs)) ``` ```go // Per-item captions msgs, err = client.SendAlbum("username", []string{"a.jpg", "b.jpg"}, &telegram.MediaOptions{ Caption: []string{"First photo", "Second photo"}, }) ``` -------------------------------- ### Inline Query Handlers Source: https://context7.com/amarnathcjd/gogram/llms.txt Handle inline queries sent to a bot in any chat. ```APIDOC ## Inline Query handlers — Handle @bot inline mode Handle inline queries sent to a bot in any chat. ```go client.On("inline:", func(iq *telegram.InlineQuery) error { builder := iq.Builder() builder.Article( "Result Title", "Short description shown in list", fmt.Sprintf("You searched for: <b>%s</b>", iq.Query), &telegram.ArticleOptions{LinkPreview: false}, ) builder.Photo("https://example.com/photo.jpg", &telegram.PhotoOptions{ Caption: "A photo result", }) return builder.Answer() }) // Pattern-matched inline handler client.On("inline:^search (.+)$\", func(iq *telegram.InlineQuery) error { query := iq.Query builder := iq.Builder() builder.Article("Search: "+query, "Click to send", "Result for: "+query, nil) return builder.Answer(&telegram.InlineSendOptions{CacheTime: 10}) }) ``` ``` -------------------------------- ### SendAlbum Source: https://context7.com/amarnathcjd/gogram/llms.txt Sends multiple media files as a single grouped album message. Supports captions for the album and individual captions for each media item. ```APIDOC ## SendAlbum — Send grouped media albums `SendAlbum` sends multiple media as a single grouped album message. ```go msgs, err := client.SendAlbum("@channel", []string{ "photo1.jpg", "photo2.jpg", "photo3.jpg", }, &telegram.MediaOptions{ Caption: "Holiday photos đŸ–ī¸", }) if err != nil { log.Fatal(err) } log.Printf("Sent album with %d messages", len(msgs)) // Per-item captions msgs, err = client.SendAlbum("username", []string{"a.jpg", "b.jpg"}, &telegram.MediaOptions{ Caption: []string{"First photo", "Second photo"}, }) ``` ``` -------------------------------- ### Send Chat Action Indicator Source: https://context7.com/amarnathcjd/gogram/llms.txt Use SendAction to display typing or other chat action indicators. The action can be explicitly cancelled. ```go // Start "typing..." indicator action, err := client.SendAction("username", "typing") if err != nil { log.Fatal(err) } // Do some work... time.Sleep(2 * time.Second) // Cancel it explicitly action.Cancel() // Available action strings: "typing", "upload_photo", "record_video", // "upload_video", "record_voice", "upload_voice", "upload_document", // "choose_sticker", "find_location", "record_video_note", "upload_video_note" ``` -------------------------------- ### Send Simple Text Message Source: https://context7.com/amarnathcjd/gogram/llms.txt Sends a basic text message to a specified username. Logs the ID of the sent message. Error handling is included. ```go // Simple text message msg, err := client.SendMessage("username", "Hello from Gogram!") if err != nil { log.Fatal(err) } log.Println("Sent message ID:", msg.ID) ``` -------------------------------- ### Manage 2FA and Log Out with gogram Source: https://context7.com/amarnathcjd/gogram/llms.txt Securely manage your Telegram account by setting, changing, or removing the Two-Factor Authentication (2FA) password. Includes options for password hints, associated email, and email code callbacks. Log out to terminate the current session. ```go // Set or change 2FA password ok, err := client.Edit2FA("old_password", "new_password", &telegram.PasswordOptions{ Hint: "my hint", Email: "user@example.com", EmailCodeCallback: func() string { var code string fmt.Print("Email code: ") fmt.Scan(&code) return code }, }) ``` ```go // Remove 2FA password ok, err = client.Edit2FA("current_password", "") ``` ```go // Log out and delete session err = client.LogOut() ``` -------------------------------- ### Reply to an Existing Message Source: https://context7.com/amarnathcjd/gogram/llms.txt Sends a reply to a specific existing message identified by its ID. The message content is "This is a reply". ```go // Reply to an existing message _, err = client.SendMessage("@someuser", "This is a reply", &telegram.SendOptions{ ReplyID: msg.ID, }) ``` -------------------------------- ### Send Poll or Quiz Source: https://context7.com/amarnathcjd/gogram/llms.txt Use SendPoll to create interactive polls or quizzes. You can specify options, whether voters are public, if it's a quiz, the correct answers, and a solution explanation. ```go // Regular poll msg, err := client.SendPoll("@group", "What is your favorite language?", []string{"Go", "Python", "Rust", "TypeScript"}, &telegram.PollOptions{ PublicVoters: true, }, ) ``` ```go // Quiz with correct answer and explanation msg, err = client.SendPoll("@group", "What does `defer` do in Go?", []string{"Delays function call", "Exits program", "Allocates memory", "Imports package"}, &telegram.PollOptions{ IsQuiz: true, CorrectAnswers: []int{0}, Solution: "The `defer` statement postpones a function call until the surrounding function returns.", ClosePeriod: 300, // auto-close after 5 minutes }, ) ``` -------------------------------- ### SendAction Source: https://context7.com/amarnathcjd/gogram/llms.txt Sends a chat action indicator (typing, uploading, recording, etc.). ```APIDOC ## SendAction — Send typing / chat actions `SendAction` sends a chat action indicator (typing, uploading, recording, etc.). ```go // Start "typing..." indicator action, err := client.SendAction("username", "typing") if err != nil { log.Fatal(err) } // Do some work... time.Sleep(2 * time.Second) // Cancel it explicitly action.Cancel() // Available action strings: "typing", "upload_photo", "record_video", // "upload_video", "record_voice", "upload_voice", "upload_document", // "choose_sticker", "find_location", "record_video_note", "upload_video_note" ``` ```