### Install Telegram Bot API Go Wrapper Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/README.md Installs the go-telegram-bot-api library using the go get command. This is the primary dependency for interacting with the Telegram Bot API in Go. ```bash go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5 ``` -------------------------------- ### Initialize Telegram Bot API in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/README.md Initializes a new Telegram Bot API instance using an environment variable for the API token. It also enables debug mode to log API requests and verifies the token by calling the 'getMe' endpoint. ```go package main import ( "os" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) func main() { bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN")) if err != nil { panic(err) } bot.Debug = true } ``` -------------------------------- ### Install Telegram Bot API Go Package Source: https://github.com/ovyflash/telegram-bot-api/blob/master/README.md Installs the latest version of the Telegram Bot API Go package using the go get command. It's important to note that tag versioning is discouraged due to the API's unstable nature. ```bash go get -u github.com/OvyFlash/telegram-bot-api ``` -------------------------------- ### Create Echo Bot: Handle Telegram Updates in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/README.md Sets up a channel to receive updates from Telegram and processes incoming messages. For each message received, it constructs and sends back a reply containing the same text as the original message. ```go // Create a new UpdateConfig struct with an offset of 0. Offsets are used // to make sure Telegram knows we've handled previous values and we don't // need them repeated. updateConfig := tgbotapi.NewUpdate(0) // Tell Telegram we should wait up to 30 seconds on each request for an // update. This way we can get information just as quickly as making many // frequent requests without having to send nearly as many. updateConfig.Timeout = 30 // Start polling Telegram for updates. updates := bot.GetUpdatesChan(updateConfig) // Let's go through each update that we're getting from Telegram. for update := range updates { // Telegram can send many types of updates depending on what your Bot // is up to. We only want to look at messages for now, so we can discard any other updates. if update.Message == nil { continue } // Now that we know we've gotten a new message, we can construct a // reply! We'll take the Chat ID and Text from the incoming message // and use it to create a new message. msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) // We'll also say that this message is a reply to the previous message. // For any other specifications than Chat ID or Text, you'll need to // set fields on the `MessageConfig`. msg.ReplyToMessageID = update.Message.MessageID // Okay, we're sending our message off! We don't care about the message // we just sent, so we'll discard it. if _, err := bot.Send(msg); err != nil { // Note that panics are a bad way to handle errors. Telegram can // have service outages or network errors, you should retry sending // messages or more gracefully handle failures. panic(err) } } ``` -------------------------------- ### Setup Telegram Bot Webhook using Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Configures a webhook for receiving Telegram updates via HTTP POST. It requires a bot token and certificate files (cert.pem, key.pem). This example demonstrates setting the webhook, checking its status, and processing incoming updates. ```go package main import ( "log" "net/http" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } log.Printf("Authorized on account %s", bot.Self.UserName) // Set webhook with self-signed certificate webhook, err := api.NewWebhookWithCert( "https://your-domain.com:8443/"+bot.Token, api.FilePath("cert.pem"), ) if err != nil { log.Panic(err) } apiResponse, err := bot.Request(webhook) if err != nil { log.Panic(err) } if apiResponse.Ok { log.Printf("Webhook set successfully") } else { log.Printf("Failed to set webhook: %s", apiResponse.Description) } // Check webhook status info, err := bot.GetWebhookInfo() if err != nil { log.Panic(err) } if info.LastErrorDate != 0 { log.Printf("Webhook error: %s", info.LastErrorMessage) } log.Printf("Pending updates: %d", info.PendingUpdateCount) // Listen for webhook updates updates := bot.ListenForWebhook("/" + bot.Token) // Start HTTPS server go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) // Process updates for update := range updates { if update.Message != nil { log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) bot.Send(msg) } } } ``` -------------------------------- ### Handle Telegram Bot Commands in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/examples/command-handling.md This Go code snippet shows how to initialize a Telegram bot, listen for incoming updates, and process commands sent by users. It uses the tgbotapi library to interact with the Telegram API. The bot responds to specific commands with predefined text messages. ```go package main import ( "log" "os" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) func main() { bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN")) if err != nil { log.Panic(err) } bot.Debug = true log.Printf("Authorized on account %s", bot.Self.UserName) u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates := bot.GetUpdatesChan(u) for update := range updates { if update.Message == nil { // ignore any non-Message updates continue } if !update.Message.IsCommand() { // ignore any non-command Messages continue } // Create a new MessageConfig. We don't have text yet, // so we leave it empty. msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") // Extract the command from the Message. switch update.Message.Command() { case "help": msg.Text = "I understand /sayhi and /status." case "sayhi": msg.Text = "Hi :)" case "status": msg.Text = "I'm ok." default: msg.Text = "I don't know that command" } if _, err := bot.Send(msg); err != nil { log.Panic(err) } } } ``` -------------------------------- ### Create and handle inline keyboard in Telegram bot (Go) Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/examples/inline-keyboard.md This code snippet shows how to create an inline keyboard with URL and numeric buttons in a Telegram bot using the go-telegram-bot-api library. It waits for the 'open' command to display the keyboard and processes callback queries when users click the buttons. ```go package main import ( "log" "os" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonURL("1.com", "http://1.com"), tgbotapi.NewInlineKeyboardButtonData("2", "2"), tgbotapi.NewInlineKeyboardButtonData("3", "3"), ), tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("4", "4"), tgbotapi.NewInlineKeyboardButtonData("5", "5"), tgbotapi.NewInlineKeyboardButtonData("6", "6"), ), ) func main() { bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN")) if err != nil { log.Panic(err) } bot.Debug = true log.Printf("Authorized on account %s", bot.Self.UserName) u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates := bot.GetUpdatesChan(u) for update := range updates { if update.Message != nil { msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) switch update.Message.Text { case "open": msg.ReplyMarkup = numericKeyboard } if _, err = bot.Send(msg); err != nil { panic(err) } } else if update.CallbackQuery != nil { callback := tgbotapi.NewCallback(update.CallbackQuery.ID, update.CallbackQuery.Data) if _, err := bot.Request(callback); err != nil { panic(err) } msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Data) if _, err := bot.Send(msg); err != nil { panic(err) } } } } ``` -------------------------------- ### Manage Bot Commands with Go Telegram Bot API Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt This snippet shows how to set, get, and handle bot commands using the telegram-bot-api library in Go. It defines commands, retrieves the current list of commands, and processes incoming commands from user messages. ```go package main import ( "log" "strings" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } // Set bot commands commands := api.SetMyCommandsConfig{ Commands: []api.BotCommand{ {Command: "start", Description: "Start the bot"}, {Command: "help", Description: "Get help information"}, {Command: "settings", Description: "Configure bot settings"}, {Command: "stats", Description: "View statistics"}, }, } _, err = bot.Request(commands) if err != nil { log.Printf("Error setting commands: %v", err) } else { log.Println("Commands set successfully") } // Get current commands getCommands := api.GetMyCommandsConfig{} currentCommands, err := bot.GetMyCommandsWithConfig(getCommands) if err != nil { log.Printf("Error: %v", err) } else { for _, cmd := range currentCommands { log.Printf("/%s - %s", cmd.Command, cmd.Description) } } // Handle commands in updates updateConfig := api.NewUpdate(0) updates := bot.GetUpdatesChan(updateConfig) for update := range updates { if update.Message == nil || !update.Message.IsCommand() { continue } command := update.Message.Command() args := update.Message.CommandArguments() log.Printf("Command: /%s, Args: %s", command, args) var response string switch command { case "start": response = "Welcome! Use /help to see available commands." case "help": response = "Available commands:\n/start - Start bot\n/help - This message\n/settings - Settings" case "settings": response = "Settings page (not implemented)" default: response = "Unknown command. Use /help for available commands." } msg := api.NewMessage(update.Message.Chat.ID, response) bot.Send(msg) } } ``` -------------------------------- ### Generate SSL Certificate for Webhook Setup Source: https://github.com/ovyflash/telegram-bot-api/blob/master/README.md Generates a self-signed SSL certificate and private key using OpenSSL, which is required for setting up a webhook with the Telegram Bot API. This is useful for testing or development environments when a proper certificate authority is not used. ```bash openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -subj "//O=Org\CN=Test" -nodes ``` -------------------------------- ### Create Inline Keyboards in Telegram Bot API with Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt This Go code example illustrates creating and sending inline keyboards with various button types (data, URL, WebApp, switch inline query) in Telegram bots. It also handles callback queries to answer and edit messages or keyboards. Depends on the telegram-bot-api library; requires bot token and chat ID; demonstrates synchronous event polling with basic logging. ```go package main import ( "log" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } chatID := int64(123456789) // Simple inline keyboard msg := api.NewMessage(chatID, "Choose an option:") msg.ReplyMarkup = api.NewInlineKeyboardMarkup( api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonData("Option 1", "option_1"), api.NewInlineKeyboardButtonData("Option 2", "option_2"), ), api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonURL("Visit Website", "https://example.com"), ), ) bot.Send(msg) // Keyboard with various button types keyboard := api.NewInlineKeyboardMarkup( api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonData("Callback", "callback_data"), ), api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonURL("URL", "https://telegram.org"), api.NewInlineKeyboardButtonWebApp("Web App", api.WebAppInfo{URL: "https://example.com/app"}), ), api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonSwitchInlineQuery("Share", "query"), ), ) msg2 := api.NewMessage(chatID, "Advanced keyboard:") msg2.ReplyMarkup = keyboard bot.Send(msg2) // Handle callback queries updateConfig := api.NewUpdate(0) updates := bot.GetUpdatesChan(updateConfig) for update := range updates { if update.CallbackQuery != nil { callback := update.CallbackQuery log.Printf("Callback data: %s", callback.Data) // Answer callback query (removes loading state) answer := api.NewCallback(callback.ID, "Button clicked!") answer.ShowAlert = false // Show as notification, not alert bot.Request(answer) // Edit message text after button click edit := api.NewEditMessageText( callback.Message.Chat.ID, callback.Message.MessageID, "You selected: "+callback.Data, ) bot.Send(edit) // Or edit just the keyboard newKeyboard := api.NewInlineKeyboardMarkup( api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonData("Action completed", "done"), ), ) editMarkup := api.NewEditMessageReplyMarkup( callback.Message.Chat.ID, callback.Message.MessageID, newKeyboard, ) bot.Send(editMarkup) } } } ``` -------------------------------- ### Manage Telegram Chat Members and Settings in Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Demonstrates various chat administration tasks such as getting chat details, listing administrators, managing member counts, and manipulating user permissions. Requires a valid bot token and appropriate chat/user IDs. Shows how to ban/unban users, restrict messaging capabilities, and promote users to admin roles. ```Go package main import ( "log" "time" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } chatID := int64(-1001234567890) // Group/supergroup chat ID userID := int64(123456789) // Get chat information chatConfig := api.ChatInfoConfig{ChatConfig: api.ChatConfig{ChatID: chatID}} chat, err := bot.GetChat(chatConfig) if err != nil { log.Printf("Error: %v", err) } else { log.Printf("Chat: %s, Members: %d", chat.Title, chat.MemberCount) } // Get chat administrators adminsConfig := api.ChatAdministratorsConfig{ChatConfig: api.ChatConfig{ChatID: chatID}} admins, err := bot.GetChatAdministrators(adminsConfig) if err != nil { log.Printf("Error: %v", err) } else { for _, admin := range admins { log.Printf("Admin: %s", admin.User.UserName) } } // Get member count countConfig := api.ChatMemberCountConfig{ChatConfig: api.ChatConfig{ChatID: chatID}} count, err := bot.GetChatMembersCount(countConfig) if err != nil { log.Printf("Error: %v", err) } else { log.Printf("Total members: %d", count) } // Get specific chat member memberConfig := api.GetChatMemberConfig{ ChatConfigWithUser: api.ChatConfigWithUser{ ChatConfig: api.ChatConfig{ChatID: chatID}, UserID: userID, }, } member, err := bot.GetChatMember(memberConfig) if err != nil { log.Printf("Error: %v", err) } else { log.Printf("Status: %s", member.Status) } // Ban user banConfig := api.BanChatMemberConfig{ ChatMemberConfig: api.ChatMemberConfig{ ChatConfig: api.ChatConfig{ChatID: chatID}, UserID: userID, }, UntilDate: time.Now().Add(24 * time.Hour).Unix(), // Ban for 24 hours } _, err = bot.Request(banConfig) if err != nil { log.Printf("Error banning user: %v", err) } // Unban user unbanConfig := api.UnbanChatMemberConfig{ ChatMemberConfig: api.ChatMemberConfig{ ChatConfig: api.ChatConfig{ChatID: chatID}, UserID: userID, }, OnlyIfBanned: true, } bot.Request(unbanConfig) // Restrict user (mute) restrictConfig := api.RestrictChatMemberConfig{ ChatMemberConfig: api.ChatMemberConfig{ ChatConfig: api.ChatConfig{ChatID: chatID}, UserID: userID, }, Permissions: &api.ChatPermissions{ CanSendMessages: false, CanSendPhotos: false, CanSendVideos: false, }, UntilDate: time.Now().Add(1 * time.Hour).Unix(), } bot.Request(restrictConfig) // Promote to admin promoteConfig := api.PromoteChatMemberConfig{ ChatMemberConfig: api.ChatMemberConfig{ ChatConfig: api.ChatConfig{ChatID: chatID}, UserID: userID, }, CanDeleteMessages: true, CanManageChat: true, CanPinMessages: true, } bot.Request(promoteConfig) } ``` -------------------------------- ### Create custom reply keyboards using telegram-bot-api (Go) Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Shows how to build simple and special reply keyboards, configure their behavior, send messages with these keyboards, remove them, and use a force reply markup. Requires the telegram-bot-api library and a valid bot token. Outputs messages with attached keyboards to a specified chat. ```Go package main import ( "log" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } chatID := int64(123456789) // Simple reply keyboard keyboard := api.NewReplyKeyboard( api.NewKeyboardButtonRow( api.NewKeyboardButton("Option 1"), api.NewKeyboardButton("Option 2"), ), api.NewKeyboardButtonRow( api.NewKeyboardButton("Option 3"), ), ) keyboard.ResizeKeyboard = true // Make keyboard smaller keyboard.OneTimeKeyboard = true // Hide after use msg := api.NewMessage(chatID, "Choose from keyboard:") msg.ReplyMarkup = keyboard bot.Send(msg) // Keyboard with special buttons contactKeyboard := api.NewReplyKeyboard( api.NewKeyboardButtonRow( api.NewKeyboardButtonContact("Share Contact"), api.NewKeyboardButtonLocation("Share Location"), ), api.NewKeyboardButtonRow( api.NewKeyboardButton("Regular Button"), ), ) msg2 := api.NewMessage(chatID, "Special features:") msg2.ReplyMarkup = contactKeyboard bot.Send(msg2) // Remove keyboard removeMsg := api.NewMessage(chatID, "Keyboard removed") removeMsg.ReplyMarkup = api.NewRemoveKeyboard(true) bot.Send(removeMsg) // Force reply (makes user reply to message) forceReplyMsg := api.NewMessage(chatID, "Please reply to this message:") forceReplyMsg.ReplyMarkup = api.ForceReply{ ForceReply: true, Selective: false, } bot.Send(forceReplyMsg) } ``` -------------------------------- ### Initialize Telegram Bot in Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Creates a new bot instance with various configuration options including custom HTTP clients and API endpoints. Requires a valid bot token from @BotFather. ```go package main import ( "log" api "github.com/OvyFlash/telegram-bot-api" ) func main() { // Create bot with default settings bot, err := api.NewBotAPI("YOUR_BOT_TOKEN_HERE") if err != nil { log.Panic(err) } // Enable debug logging to see API requests and responses bot.Debug = true log.Printf("Authorized on account %s", bot.Self.UserName) // Custom HTTP client customClient := &http.Client{Timeout: 30 * time.Second} bot2, err := api.NewBotAPIWithClient("TOKEN", api.APIEndpoint, customClient) if err != nil { log.Panic(err) } // Custom API endpoint (for local bot API server) bot3, err := api.NewBotAPIWithAPIEndpoint("TOKEN", "https://custom-api.example.com/bot%s/%s") if err != nil { log.Panic(err) } } ``` -------------------------------- ### Handle inline queries using telegram-bot-api (Go) Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Demonstrates processing inline queries, constructing article and photo results, adding an inline keyboard to a result, and sending the compiled results back to the user. Requires the telegram-bot-api library and a running bot. Returns various inline query result types with optional caching. ```Go package main import ( "fmt" "log" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } log.Printf("Authorized on account %s", bot.Self.UserName) updateConfig := api.NewUpdate(0) updateConfig.Timeout = 60 updates := bot.GetUpdatesChan(updateConfig) for update := range updates { if update.InlineQuery == nil { continue } query := update.InlineQuery log.Printf("Inline query from %s: %s", query.From.UserName, query.Query) // Article result article := api.NewInlineQueryResultArticle( query.ID+"-article", "Echo", query.Query, ) article.Description = "Echo your query" article.InputMessageContent = api.InputTextMessageContent{ Text: fmt.Sprintf("You searched for: %s", query.Query), ParseMode: api.ModeHTML, } // Photo result photo := api.NewInlineQueryResultPhoto( query.ID+"-photo", "https://example.com/photo.jpg", ) photo.ThumbURL = "https://example.com/thumb.jpg" photo.Title = "Sample Photo" photo.Description = "A sample photo result" // Article with keyboard article2 := api.NewInlineQueryResultArticle( query.ID+"-article2", "Button Example", "Click to see buttons", ) article2.ReplyMarkup = &api.InlineKeyboardMarkup{ InlineKeyboard: [][]api.InlineKeyboardButton{ { api.NewInlineKeyboardButtonURL("Visit", "https://example.com"), }, }, } article2.InputMessageContent = api.InputTextMessageContent{ Text: "Message with buttons", } // Send results inlineConfig := api.InlineConfig{ InlineQueryID: query.ID, IsPersonal: true, CacheTime: 300, Results: []interface{}{article, photo, article2}, } if _, err := bot.Request(inlineConfig); err != nil { log.Printf("Error answering inline query: %v", err) } } } ``` -------------------------------- ### Send Various File Types with Telegram Bot API in Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Demonstrates sending different types of files including photos, documents, audio, video, and stickers using the Telegram Bot API in Go. It shows how to send files from local paths, URLs, and byte arrays, and also how to send media groups. ```go package main import ( "log" "os" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } chatID := int64(123456789) // Send photo from local file photo := api.NewPhoto(chatID, api.FilePath("photo.jpg")) photo.Caption = "This is a photo" photo.ParseMode = api.ModeHTML bot.Send(photo) // Send photo from URL photoURL := api.NewPhoto(chatID, api.FileURL("https://example.com/image.jpg")) bot.Send(photoURL) // Send photo from bytes photoData, _ := os.ReadFile("photo.jpg") photoBytes := api.NewPhoto(chatID, api.FileBytes{ Name: "photo.jpg", Bytes: photoData, }) bot.Send(photoBytes) // Send document doc := api.NewDocument(chatID, api.FilePath("document.pdf")) doc.Caption = "Important document" bot.Send(doc) // Send audio audio := api.NewAudio(chatID, api.FilePath("song.mp3")) audio.Title = "Song Title" audio.Performer = "Artist Name" audio.Duration = 180 bot.Send(audio) // Send video video := api.NewVideo(chatID, api.FilePath("video.mp4")) video.Duration = 60 video.Caption = "Video caption" bot.Send(video) // Send sticker sticker := api.NewSticker(chatID, api.FilePath("sticker.webp")) bot.Send(sticker) // Send media group (multiple photos/videos) media1 := api.NewInputMediaPhoto(api.FilePath("photo1.jpg")) media2 := api.NewInputMediaPhoto(api.FilePath("photo2.jpg")) media2.Caption = "Second photo" mediaGroup := api.NewMediaGroup(chatID, []interface{}{media1, media2}) messages, err := bot.SendMediaGroup(mediaGroup) if err != nil { log.Printf("Error: %v", err) } else { log.Printf("Sent %d media items", len(messages)) } } ``` -------------------------------- ### Create and Run an Echo Bot using Polling in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/README.md Demonstrates how to create a simple echo bot in Go using the telegram-bot-api library. The bot authorizes using a token, configures update fetching with a timeout, and echoes back received messages. It uses polling to receive updates from the Telegram API. ```go package main import ( "log" "time" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("BOT_TOKEN") if err != nil { panic(err) } log.Printf("Authorized on account %s", bot.Self.UserName) updateConfig := api.NewUpdate(0) updateConfig.Timeout = 60 updatesChannel := bot.GetUpdatesChan(updateConfig) // Optional: Clear initial updates time.Sleep(time.Millisecond * 500) updatesChannel.Clear() for update := range updatesChannel { if update.Message == nil { continue } log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) msg.ReplyParameters.MessageID = update.Message.MessageID bot.Send(msg) } } ``` -------------------------------- ### Send Text Messages via Telegram Bot in Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt Demonstrates various methods for sending text messages including simple messages, replies, formatted messages (Markdown/HTML), and channel messages. Shows message customization options like link preview control. ```go package main import ( "log" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } // Simple text message msg := api.NewMessage(123456789, "Hello from Go!") sentMessage, err := bot.Send(msg) if err != nil { log.Printf("Error sending message: %v", err) } else { log.Printf("Message sent with ID: %d", sentMessage.MessageID) } // Message with reply to another message replyMsg := api.NewMessage(123456789, "This is a reply") replyMsg.ReplyParameters.MessageID = 999 bot.Send(replyMsg) // Message with Markdown formatting markdownMsg := api.NewMessage(123456789, "*Bold text* and _italic text_") markdownMsg.ParseMode = api.ModeMarkdown bot.Send(markdownMsg) // Message with HTML formatting htmlMsg := api.NewMessage(123456789, "Bold and italic and code") htmlMsg.ParseMode = api.ModeHTML bot.Send(htmlMsg) // Message with disabled link preview linkMsg := api.NewMessage(123456789, "Check out https://example.com") linkMsg.LinkPreviewOptions.IsDisabled = true bot.Send(linkMsg) // Send to channel by username channelMsg := api.NewMessageToChannel("@mychannel", "Channel announcement") bot.Send(channelMsg) } ``` -------------------------------- ### Go: Handle Telegram Bot API Errors and Context Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt This Go code snippet showcases how to initialize the Telegram Bot API, send messages, and handle potential errors. It specifically demonstrates parsing API errors to access details like error codes, messages, retry delays, and chat migration information. Additionally, it illustrates using `context.WithTimeout` and `context.WithCancel` to manage request lifecycles, handle timeouts, and cancel operations gracefully. It also includes checking if a message is directed to the bot using `IsMessageToMe`. ```go package main import ( "context" "errors" "log" "time" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } chatID := int64(123456789) // Handle API errors msg := api.NewMessage(chatID, "Test message") _, err = bot.Send(msg) if err != nil { if apiErr, ok := err.(*api.Error); ok { log.Printf("API Error Code: %d", apiErr.Code) log.Printf("API Error Message: %s", apiErr.Message) if apiErr.RetryAfter != 0 { log.Printf("Rate limited. Retry after %d seconds", apiErr.RetryAfter) time.Sleep(time.Duration(apiErr.RetryAfter) * time.Second) } if apiErr.MigrateToChatID != 0 { log.Printf("Chat migrated to supergroup: %d", apiErr.MigrateToChatID) chatID = apiErr.MigrateToChatID } } else { log.Printf("Network or other error: %v", err) } } // Use context for cancellation ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() updateConfig := api.UpdateConfig{ Offset: 0, Timeout: 60, } updates, err := bot.GetUpdatesWithContext(ctx, updateConfig) if err != nil { if errors.Is(err, context.DeadlineExceeded) { log.Println("Request timed out") } else if errors.Is(err, context.Canceled) { log.Println("Request canceled") } else { log.Printf("Error: %v", err) } } else { log.Printf("Got %d updates", len(updates)) } // Make request with context ctx2, cancel2 := context.WithCancel(context.Background()) go func() { time.Sleep(2 * time.Second) cancel2() // Cancel after 2 seconds }() resp, err := bot.MakeRequestWithContext(ctx2, "getMe", nil) if err != nil { log.Printf("Request error: %v", err) } else if resp.Ok { log.Println("Request successful") } // Check if message is directed to bot updateConfig2 := api.NewUpdate(0) updatesChannel := bot.GetUpdatesChan(updateConfig2) for update := range updatesChannel { if update.Message == nil { continue } // Check if bot is mentioned if bot.IsMessageToMe(*update.Message) { msg := api.NewMessage(update.Message.Chat.ID, "You mentioned me!") bot.Send(msg) } } } ``` -------------------------------- ### Download Files with Telegram Bot API in Go Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt This Go code snippet shows how to download files sent by users in a Telegram bot using the OvyFlash/telegram-bot-api library. It retrieves file URLs for photos and documents, downloads them via HTTP, and saves to local disk. Requires a bot token; handles errors for file retrieval and network issues but assumes basic user message structure. ```go package main import ( "io" "log" "net/http" "os" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } updateConfig := api.NewUpdate(0) updates := bot.GetUpdatesChan(updateConfig) for update := range updates { if update.Message != nil && update.Message.Photo != nil { // Get highest resolution photo photos := update.Message.Photo fileID := photos[len(photos)-1].FileID // Get file info fileConfig := api.FileConfig{FileID: fileID} file, err := bot.GetFile(fileConfig) if err != nil { log.Printf("Error getting file: %v", err) continue } // Get direct download URL fileURL := file.Link(bot.Token) log.Printf("File URL: %s", fileURL) // Download file resp, err := http.Get(fileURL) if err != nil { log.Printf("Error downloading: %v", err) continue } defer resp.Body.Close() // Save to disk out, err := os.Create("downloaded_photo.jpg") if err != nil { log.Printf("Error creating file: %v", err) continue } defer out.Close() _, err = io.Copy(out, resp.Body) if err != nil { log.Printf("Error saving file: %v", err) } else { log.Printf("File saved successfully") } } // Handle documents if update.Message != nil && update.Message.Document != nil { fileURL, err := bot.GetFileDirectURL(update.Message.Document.FileID) if err != nil { log.Printf("Error: %v", err) continue } log.Printf("Document URL: %s", fileURL) } } } ``` -------------------------------- ### Specify local file path in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/files.md Uses a local file path to reference a file for the Telegram Bot API. The file must be accessible from the running application. ```go file := tgbotapi.FilePath("tests/image.jpg") ``` -------------------------------- ### Create InputMediaPhoto with FilePath (Go) Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/uploading-files.md This Go code snippet demonstrates creating an InputMediaPhoto struct using a local file path. It's used as part of a media group upload. ```go photo := tgbotapi.NewInputMediaPhoto(tgbotapi.FilePath("tests/image.jpg")) ``` -------------------------------- ### Create InputMediaPhoto with FileURL (Go) Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/uploading-files.md This Go code snippet demonstrates creating an InputMediaPhoto struct using a URL. This is useful for including remote images in media group uploads. ```go url := tgbotapi.NewInputMediaPhoto(tgbotapi.FileURL("https://i.imgur.com/unQLJIb.jpg")) ``` -------------------------------- ### Reference file by URL in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/files.md Uses a publicly accessible URL to reference a file. The URL must serve the file with the correct MIME type. ```go file := tgbotapi.FileURL("https://i.imgur.com/unQLJIb.jpg") ``` -------------------------------- ### Create Media Group with InputMedia (Go) Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/uploading-files.md This Go code illustrates creating a media group using the NewMediaGroup function. It accepts a ChatID and a slice of interfaces, which can include InputMediaPhoto or InputMediaVideo objects. ```go mediaGroup := NewMediaGroup(ChatID, []interface{}{ photo, url, }) ``` -------------------------------- ### Implement File Uploads for DocumentConfig (Go) Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/uploading-files.md This Go code implements the Fileable interface for DocumentConfig to handle file uploads. It supports uploading a primary document and an optional thumbnail, returning a slice of RequestFile structs. ```go func (config DocumentConfig) files() []RequestFile { // We can have multiple files, so we'll create an array. We also know that // there always is a document file, so initialize the array with that. files := []RequestFile{{ Name: "document", Data: config.File, }} // We'll only add a file if we have one. if config.Thumb != nil { files = append(files, RequestFile{ Name: "thumb", Data: config.Thumb, }) } return files } ``` -------------------------------- ### Manage Numeric Keyboard in Telegram Bot using Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/examples/keyboard.md This Go program creates a Telegram bot that listens for 'open' or 'close' messages to show or hide a numeric reply keyboard. It depends on the Telegram Bot API library (tgbotapi) and requires a valid TELEGRAM_APITOKEN environment variable. The bot processes incoming updates in a loop, sending replies without echoing unless specifying 'open' or 'close'; limitations include no error handling for invalid tokens and a fixed keyboard layout. ```go package main import ( "log" "os" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) var numericKeyboard = tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("1"), tgbotapi.NewKeyboardButton("2"), tgbotapi.NewKeyboardButton("3"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("4"), tgbotapi.NewKeyboardButton("5"), tgbotapi.NewKeyboardButton("6"), ), ) func main() { bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN")) if err != nil { log.Panic(err) } bot.Debug = true log.Printf("Authorized on account %s", bot.Self.UserName) u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates := bot.GetUpdatesChan(u) for update := range updates { if update.Message == nil { // ignore non-Message updates continue } msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) switch update.Message.Text { case "open": msg.ReplyMarkup = numericKeyboard case "close": msg.ReplyMarkup = tgbotapi.NewRemoveKeyboard(true) } if _, err := bot.Send(msg); err != nil { log.Panic(err) } } } ``` -------------------------------- ### Create DeleteMessageConfig Helper in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/adding-endpoints.md This Go function simplifies the creation of a DeleteMessageConfig by accepting only the essential chatID and messageID. It is part of a Telegram bot API helper library and requires no external dependencies beyond the Config type definitions. ```go func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { return DeleteMessageConfig{ ChatID: chatID, MessageID: messageID, } } ``` -------------------------------- ### Provide file via byte array in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/files.md Uses a byte array to provide file contents directly. Not recommended for large files due to memory usage. Requires a filename. ```go var data []byte file := tgbotapi.FileBytes{ Name: "image.jpg", Bytes: data, } ``` -------------------------------- ### Define DeleteMessageConfig Struct Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/adding-endpoints.md Defines the configuration struct for the `deleteMessage` API endpoint. It includes fields for specifying the chat and message identifiers, and potentially file data for uploads. ```go type DeleteMessageConfig struct { ChannelUsername string ChatID int64 MessageID int Delete RequestFileData Thumb RequestFileData } ``` -------------------------------- ### Utilize BaseChat for Message Configuration Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/adding-endpoints.md Demonstrates how to use the `BaseChat` struct to embed common fields like `ChatID`, `ChannelUsername`, `ReplyToMessageID`, and `ReplyMarkup` into a custom configuration struct. This reduces code duplication for chat-related operations. ```go type MessageConfig struct { BaseChat Text string ParseMode string DisableWebPagePreview bool } func (config MessageConfig) params() (Params, error) { params, err := config.BaseChat.params() if err != nil { return params, err } params.AddNonEmpty("text", config.Text) // Add your other fields return params, nil } ``` -------------------------------- ### Edit and Delete Messages with Go Telegram Bot API Source: https://context7.com/ovyflash/telegram-bot-api/llms.txt This Go code demonstrates how to edit existing messages (text, captions, reply markups) and delete messages using the telegram-bot-api library. It covers sending an initial message, then modifying it in various ways, and finally removing it. ```go package main import ( "log" "time" api "github.com/OvyFlash/telegram-bot-api" ) func main() { bot, err := api.NewBotAPI("YOUR_BOT_TOKEN") if err != nil { log.Panic(err) } chatID := int64(123456789) // Send initial message msg := api.NewMessage(chatID, "Initial message") sentMsg, err := bot.Send(msg) if err != nil { log.Printf("Error: %v", err) return } time.Sleep(2 * time.Second) // Edit message text edit := api.NewEditMessageText(chatID, sentMsg.MessageID, "Edited message text") edit.ParseMode = api.ModeHTML _, err = bot.Send(edit) if err != nil { log.Printf("Error editing: %v", err) } // Edit message with keyboard keyboard := api.NewInlineKeyboardMarkup( api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonData("Click me", "button_clicked"), ), ) edit2 := api.NewEditMessageText(chatID, sentMsg.MessageID, "Message with button") edit2.ReplyMarkup = &keyboard bot.Send(edit2) // Edit only the reply markup (keep text same) newKeyboard := api.NewInlineKeyboardMarkup( api.NewInlineKeyboardRow( api.NewInlineKeyboardButtonData("Updated button", "new_data"), ), ) editMarkup := api.NewEditMessageReplyMarkup(chatID, sentMsg.MessageID, newKeyboard) bot.Send(editMarkup) // Send photo and edit caption photo := api.NewPhoto(chatID, api.FileURL("https://example.com/photo.jpg")) photo.Caption = "Original caption" photoMsg, err := bot.Send(photo) if err != nil { log.Printf("Error: %v", err) return } time.Sleep(2 * time.Second) editCaption := api.NewEditMessageCaption(chatID, photoMsg.MessageID, "Updated caption") editCaption.ParseMode = api.ModeMarkdown bot.Send(editCaption) // Delete message time.Sleep(2 * time.Second) deleteConfig := api.NewDeleteMessage(chatID, sentMsg.MessageID) bot.Request(deleteConfig) // Delete multiple messages at once messageIDs := []int{1001, 1002, 1003} deleteMultiple := api.NewDeleteMessages(chatID, messageIDs) bot.Request(deleteMultiple) } ``` -------------------------------- ### Implement Fileable Interface for File Uploads Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/internals/adding-endpoints.md Implements the `Fileable` interface to enable file uploads for an API endpoint. This involves defining the `files` method, which returns a slice of `RequestFile` containing the files to be uploaded along with their names and data. ```go func (config DeleteMessageConfig) files() []RequestFile { files := []RequestFile{{ Name: "delete", Data: config.Delete, }} if config.Thumb != nil { files = append(files, RequestFile{ Name: "thumb", Data: config.Thumb, }) } return files } ``` -------------------------------- ### Provide file via IO reader in Go Source: https://github.com/ovyflash/telegram-bot-api/blob/master/docs/getting-started/files.md Uses an io.Reader interface to lazily read file contents, saving memory. Requires specifying a filename for the virtual file. ```go var reader io.Reader file := tgbotapi.FileReader{ Name: "image.jpg", Reader: reader, } ```