### Start Bot with Webhooks Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Configures and starts the bot to receive updates via webhooks. It requires setting up an HTTP server to listen for incoming requests and uses a secret token for security. Remember to call methods.SetWebhook if needed. ```go func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() opts := []bot.Option{ bot.WithDefaultHandler(handler), bot.WithWebhookSecretToken(os.Getenv("EXAMPLE_TELEGRAM_WEBHOOK_SECRET_TOKEN")) } b, _ := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...) // call methods.SetWebhook if needed go b.StartWebhook(ctx) http.ListenAndServe(":2000", b.WebhookHandler()) // call methods.DeleteWebhook if needed } func handler(ctx context.Context, b *bot.Bot, update *models.Update) { b.SendMessage(ctx, &bot.SendMessageParams{ ChatID: update.Message.Chat.ID, Text: update.Message.Text, }) } ``` -------------------------------- ### Start Bot Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Starts the bot. This method is typically called once when the bot is initialized. ```APIDOC ## POST /start ### Description Starts the bot. This method is typically called once when the bot is initialized. ### Method POST ### Endpoint /start ### Parameters #### Request Body - **ctx** (context.Context) - Required - The context for the request. ### Response This method does not return a value directly, but it initiates the bot's operation. ``` -------------------------------- ### Start Webhook Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Starts the webhook listener for the bot. This method is typically called once when the bot is initialized to handle incoming updates via webhook. ```APIDOC ## POST /startWebhook ### Description Starts the webhook listener for the bot. This method is typically called once when the bot is initialized to handle incoming updates via webhook. ### Method POST ### Endpoint /startWebhook ### Parameters #### Request Body - **ctx** (context.Context) - Required - The context for the request. ### Response This method does not return a value directly, but it initiates the webhook listener. ``` -------------------------------- ### Install Telegram Bot Dependencies Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Installs the go-telegram-bot library using go get. Ensure you are using Go version 1.18 or later. ```bash go get -u github.com/go-telegram/bot ``` -------------------------------- ### GET /getFile Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Gets basic information about a file and prepares it for downloading using GetFileParams. ```APIDOC ## GET /getFile ### Description Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. ### Method GET ### Endpoint /getFile ### Parameters #### Query Parameters - **file_id** (string) - Required - File identifier to get information about. ``` -------------------------------- ### GET /getMe Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Retrieves information about the bot account. ```APIDOC ## GET /getMe ### Description A simple method for testing your bot's authentication token. Requires no parameters. ### Method GET ### Endpoint /getMe ### Response #### Success Response (200) - **User** (models.User) - Returns basic information about the bot in form of a User object. ``` -------------------------------- ### Set My Commands Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to change the list of the bot's commands. See the bot commands documentation for more details. If the bot is an inline bot, you can also set the commands for inline mode. The commands must be between 1 and 32 characters long. The commands can contain letters, numbers, and underscores. The commands cannot start or end with an underscore. The commands cannot contain any special characters. ```APIDOC ## POST /bot/setMyCommands ### Description Use this method to change the list of the bot's commands. See the bot commands documentation for more details. If the bot is an inline bot, you can also set the commands for inline mode. The commands must be between 1 and 32 characters long. The commands can contain letters, numbers, and underscores. The commands cannot start or end with an underscore. The commands cannot contain any special characters. ### Method POST ### Endpoint /bot/setMyCommands ### Parameters #### Request Body - **commands** (array of BotCommand) - Required - A JSON-serialized list of bot commands. Each object in the list must have the `command` and `description` fields. - **scope** (BotCommandScope) - Optional - A JSON-serialized object specifying the scope of bot commands. Default scope is the empty string, which means the commands are active for all chats and all users. - **language_code** (string) - Optional - A two-letter ISO 639-1 language code. If not specified, commands will be active for all languages. ### Request Example ```json { "commands": [ { "command": "start", "description": "Starts the bot" }, { "command": "help", "description": "Shows help information" } ], "scope": { "type": "default" }, "language_code": "en" } ``` ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful - **result** (boolean) - True if the commands were successfully set #### Response Example ```json { "ok": true, "result": true } ``` ``` -------------------------------- ### Configure Bot with Options Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Illustrates how to apply various configuration options when initializing the bot. The `opts` slice can contain multiple `bot.Option` values to customize bot behavior. ```go b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", opts...) ``` -------------------------------- ### Initialize New Bot Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Creates a new instance of the Bot. ```go func New(token string, options ...Option) (*Bot, error) ``` -------------------------------- ### Bot Initialization Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Creates a new Bot instance with the provided token and optional configurations. ```APIDOC ## New Bot Instance ### Description Creates a new Bot instance using the provided API token and optional configuration settings. ### Method `New` ### Parameters - **token** (string) - Required - The unique token for your Telegram Bot. - **options** (...Option) - Optional - A variadic list of `Option` functions to configure the bot. ### Response - **(*Bot, error)** - Returns a pointer to the Bot instance and an error if creation fails. ``` -------------------------------- ### Initialize Bot Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Basic initialization of the bot. The bot will call the getMe method upon creation with a default 5-second timeout. Errors during this initial check will be returned. ```go b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER") b.Start(context.TODO()) ``` -------------------------------- ### Initialize and Run Echo Bot Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Sets up a basic echo bot that responds to text messages with the same text. Requires a bot token from BotFather and handles interrupt signals to shut down gracefully. ```go package main import ( "context" "os" "os/signal" "github.com/go-telegram/bot" "github.com/go-telegram/bot/models" ) // Send any text message to the bot after the bot has been started func main() { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() opts := []bot.Option{ bot.WithDefaultHandler(handler), } b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", opts...) if err != nil { panic(err) } b.Start(ctx) } func handler(ctx context.Context, b *bot.Bot, update *models.Update) { b.SendMessage(ctx, &bot.SendMessageParams{ ChatID: update.Message.Chat.ID, Text: update.Message.Text, }) } ``` -------------------------------- ### GET /getChat Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Retrieves full information about a chat. ```APIDOC ## GET /getChat ### Description Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). ### Method GET ### Endpoint /getChat ### Parameters #### Query Parameters - **params** (GetChatParams) - Required - Parameters containing the chat identifier. ### Response #### Success Response (200) - **ChatFullInfo** (models.ChatFullInfo) - Returns a ChatFullInfo object. ``` -------------------------------- ### Define Business Account Parameters Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Structs for configuring business account details like name, profile photo, and username. ```go type SetBusinessAccountNameParams struct { BusinessConnectionID string `json:"business_connection_id"` FirstName string `json:"first_name"` LastName string `json:"last_name,omitempty"` } ``` ```go type SetBusinessAccountProfilePhotoParams struct { BusinessConnectionID string `json:"business_connection_id"` Photo models.InputProfilePhoto `json:"photo"` IsPublic bool `json:"is_public,omitempty"` } ``` ```go type SetBusinessAccountUsernameParams struct { BusinessConnectionID string `json:"business_connection_id"` Username string `json:"username,omitempty"` } ``` -------------------------------- ### Create Sticker Set with Local and Remote Stickers Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Shows how to create a new sticker set with both a remote sticker URL and a locally attached sticker. For local stickers, use `attach://` and provide a `StickerAttachment` with the file content. ```go fileContent, _ := os.ReadFile("/path/to/telegram.png") inputSticker1 := models.InputSticker{ Sticker: "https://github.com/go-telegram/bot/blob/main/examples/create_new_sticker_set/images/telegram.png?raw=true", Format: "static", EmojiList: []string{"1️⃣"}, } inputSticker2 := models.InputSticker{ Sticker: "attach://telegram.png", Format: "static", EmojiList: []string{"2️⃣"}, StickerAttachment: bytes.NewReader(fileContent), } params := &bot.CreateNewStickerSetParams{ UserID: update.Message.Chat.ID, Name: fmt.Sprintf("Example%d_by_%s", time.Now().Unix(), botUsername), Title: "Example sticker set", Stickers: []models.InputSticker{ inputSticker1, inputSticker2, }, } b.CreateNewStickerSet(ctx, params) ``` -------------------------------- ### GET getUserGifts Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Retrieves the list of gifts for a specific user. ```APIDOC ## GET getUserGifts ### Description Retrieves the list of gifts for a specific user. ### Method GET ### Endpoint getUserGifts ### Parameters #### Request Body - **user_id** (int64) - Required - **offset** (string) - Optional - **limit** (int) - Optional ``` -------------------------------- ### GET getChatGifts Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Retrieves the list of gifts for a specific chat. ```APIDOC ## GET getChatGifts ### Description Retrieves the list of gifts for a specific chat. ### Method GET ### Endpoint getChatGifts ### Parameters #### Request Body - **chat_id** (any) - Required - **offset** (string) - Optional - **limit** (int) - Optional ``` -------------------------------- ### Set My Description Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the bot's description. ```go func (b *Bot) SetMyDescription(ctx context.Context, params *SetMyDescriptionParams) (bool, error) ``` -------------------------------- ### GET getBusinessAccountGifts Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Retrieves the list of gifts for a business account. ```APIDOC ## GET getBusinessAccountGifts ### Description Retrieves the list of gifts for a business account. ### Method GET ### Endpoint getBusinessAccountGifts ### Parameters #### Request Body - **business_connection_id** (string) - Required - **exclude_unsaved** (bool) - Optional - **exclude_saved** (bool) - Optional - **exclude_unlimited** (bool) - Optional - **exclude_limited_upgradable** (bool) - Optional - **exclude_limited_non_upgradable** (bool) - Optional - **exclude_unique** (bool) - Optional - **exclude_from_blockchain** (bool) - Optional - **sort_by_price** (bool) - Optional - **offset** (string) - Optional - **limit** (int) - Optional ``` -------------------------------- ### GET getUserProfileAudios Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Retrieves the list of audio files in a user's profile. ```APIDOC ## GET getUserProfileAudios ### Description Retrieves the list of audio files in a user's profile. ### Method GET ### Endpoint getUserProfileAudios ### Parameters #### Request Body - **user_id** (int64) - Required - **offset** (int) - Optional - **limit** (int) - Optional ``` -------------------------------- ### Define Bot and Game Configuration Parameters Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Structs for configuring bot commands, descriptions, names, game scores, and message reactions. ```go type SetCustomEmojiStickerSetThumbnailParams struct { Name string `json:"name"` CustomEmojiID string `json:"custom_emoji_id,omitempty"` } ``` ```go type SetGameScoreParams struct { UserID int64 `json:"user_id"` Score int `json:"score"` Force bool `json:"force,omitempty"` DisableEditMessage bool `json:"disable_edit_message,omitempty"` ChatID any `json:"chat_id,omitempty"` MessageID int `json:"message_id,omitempty"` InlineMessageID int `json:"inline_message_id,omitempty"` } ``` ```go type SetMessageReactionParams struct { ChatID any `json:"chat_id"` MessageID int `json:"message_id"` Reaction []models.ReactionType `json:"reaction,omitempty"` IsBig *bool `json:"is_big,omitempty"` } ``` ```go type SetMyCommandsParams struct { Commands []models.BotCommand `json:"commands"` Scope models.BotCommandScope `json:"scope,omitempty"` LanguageCode string `json:"language_code,omitempty"` } ``` ```go type SetMyDefaultAdministratorRightsParams struct { Rights *models.ChatAdministratorRights `json:"rights,omitempty"` ForChannels bool `json:"for_channels,omitempty"` } ``` ```go type SetMyDescriptionParams struct { Description string `json:"description,omitempty"` LanguageCode string `json:"language_code,omitempty"` } ``` ```go type SetMyNameParams struct { Name string `json:"name,omitempty"` LanguageCode string `json:"language_code,omitempty"` } ``` -------------------------------- ### Implement WithMiddlewares Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to apply one or more middleware functions to each incoming request. ```go func WithMiddlewares(middlewares ...Middleware) Option ``` -------------------------------- ### Get Pointer to False Boolean in Go Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Returns a pointer to a boolean value set to false. Useful for setting optional boolean parameters in API requests. ```go func False() *bool ``` -------------------------------- ### Get Pointer to True Boolean in Go Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Returns a pointer to a boolean value set to true. This is commonly used when setting optional boolean parameters in API calls. ```go func True() *bool ``` -------------------------------- ### Set My Commands Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Sets the list of commands for the bot. ```go func (b *Bot) SetMyCommands(ctx context.Context, params *SetMyCommandsParams) (bool, error) ``` -------------------------------- ### Set My Short Description Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the bot's short description. ```go func (b *Bot) SetMyShortDescription(ctx context.Context, params *SetMyShortDescriptionParams) (bool, error) ``` -------------------------------- ### Set Chat Menu Button Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme A chat menu button is a button that appears at the top of the chat. It can be used to open a URL, send a message, or start a game. Returns true on success. ```APIDOC ## POST /setChatMenuButton ### Description A chat menu button is a button that appears at the top of the chat. It can be used to open a URL, send a message, or start a game. Returns true on success. ### Method POST ### Endpoint /setChatMenuButton ### Parameters #### Request Body - **chat_id** (int64 | string) - Optional - Unique identifier for the target chat or username of the target channel (in the format "@channelusername") - **menu_button** (MenuButton) - Optional - A JSON-serialized object for the bot's new menu button. Returns an empty object if the menu button is removed. ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### SetWebhookParams Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this struct to specify a URL and get receiving updates remotely. When you send something to the bot, the bot server will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. ```APIDOC ## SetWebhookParams ### Description Sets a webhook for receiving updates. The bot server will send HTTPS POST requests to the specified URL with JSON-serialized Update objects. ### Method POST ### Endpoint /setWebhook ### Parameters #### Request Body - **url** (string) - Required - HTTPS URL to send updates to. Use an empty string to remove the webhook. - **certificate** (InputFile) - Optional - Upload your public key certificate so that the root certificate in the chain can be checked. - **ip_address** (string) - Optional - The fixed IP address which will be used to send webhook requests instead of the IP address resolved to your domain. - **max_connections** (integer) - Optional - Maximum allowed number of simultaneous HTTPS connections to the webhook. Should be an integer between 1 and 100. - **allowed_updates** (array of strings) - Optional - A list of update types you want your bot to receive. For example, specify `["message", "edited_channel_post", "callback_query"]` to only receive these types of updates. - **drop_pending_updates** (boolean) - Optional - Pass `True` to drop all pending updates before setting the new webhook. - **secret_token** (string) - Optional - A secret token to be sent in the `X-Telegram-Bot-Api-Secret-Token` header when the webhook is called. Useful for security. ### Request Example ```json { "url": "https://yourdomain.com/webhook", "certificate": "attach://webhook_cert.pem", "max_connections": 40, "allowed_updates": ["message", "callback_query"] } ``` ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful. #### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Implement WithServerURL Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set a custom server URL for the bot, useful for self-hosted instances or specific network configurations. ```go func WithServerURL(serverURL string) Option ``` -------------------------------- ### Set Webhook Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to specify a url and get ingress updates via an outgoing webhook. Therefore, custom webhook servers will be notified about new updates until the webhook is disabled. Returns true on success. ```APIDOC ## POST /setWebhook ### Description Use this method to specify a url and get ingress updates via an outgoing webhook. Therefore, custom webhook servers will be notified about new updates until the webhook is disabled. Returns true on success. ### Method POST ### Endpoint /setWebhook ### Parameters #### Request Body - **url** (string) - Required - HTTPS url to send updates to. Use an empty string to remove webhook integration. - **certificate** (InputFile) - Optional - Upload your public key certificate so that the root certificate in the chain can be checked. See our guide for details. - **ip_address** (string) - Optional - The fixed IP address which will be used to send webhook requests instead of the IP address resolved to your domain. Use this only if you want to force HTTPS connection from a specific IP address. - **max_connections** (int32) - Optional - Maximum number of webhook requests at any given time. Can be used to decrease or increase the threat of DoS attacks. - **allowed_updates** (array of string) - Optional - A list of update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive these types of updates. ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Set Business Account Username Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to change the username of a business account. The username must be between 5 and 32 characters long. The username can contain letters, numbers, and underscores. The username cannot start or end with an underscore. The username cannot contain any special characters. ```APIDOC ## POST /bot/setBusinessAccountUsername ### Description Use this method to change the username of a business account. The username must be between 5 and 32 characters long. The username can contain letters, numbers, and underscores. The username cannot start or end with an underscore. The username cannot contain any special characters. ### Method POST ### Endpoint /bot/setBusinessAccountUsername ### Parameters #### Request Body - **business_connection_id** (string) - Required - Unique identifier for the business connection - **username** (string) - Optional - New username for the business account ### Request Example ```json { "business_connection_id": "string", "username": "string" } ``` ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful - **result** (boolean) - True if the username was successfully changed #### Response Example ```json { "ok": true, "result": true } ``` ``` -------------------------------- ### GetMe Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Returns basic information about the bot. ```APIDOC ## GET getMe ### Description A simple method for testing your bot's authentication token. Requires no parameters. ### Method GET ### Endpoint https://core.telegram.org/bots/api#getme ### Response #### Success Response (200) - **result** (models.User) - Basic information about the bot ``` -------------------------------- ### Implement UseTestEnvironment Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to configure the bot to use the test environment. Requires Go v1.7.1 or later. ```go func UseTestEnvironment() Option ``` -------------------------------- ### Set My Default Administrator Rights Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Sets the default administrator rights for the bot. ```go func (b *Bot) SetMyDefaultAdministratorRights(ctx context.Context, params *SetMyDefaultAdministratorRightsParams) (bool, error) ``` -------------------------------- ### Define CreateChatSubscriptionInviteLinkParams Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Parameters for creating a subscription invite link for a chat. ```go type CreateChatSubscriptionInviteLinkParams struct { ChatID any `json:"chat_id"` Name string `json:"name,omitempty"` SubscriptionPeriod int `json:"subscription_period"` SubscriptionPrice int `json:"subscription_price"` } ``` -------------------------------- ### Initialize Bot with Default Handler Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Initializes the bot and sets a default handler function that will be invoked for all incoming updates. This is useful for setting up a catch-all message processing logic. ```go b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", bot.WithDefaultHandler(handler)) func handler(ctx context.Context, b *bot.Bot, update *models.Update) { // this handler will be called for all updates } ``` -------------------------------- ### SetMyShortDescriptionParams Structure Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Defines parameters for setting a bot's short description. ```go type SetMyShortDescriptionParams struct { ShortDescription string `json:"short_description,omitempty"` LanguageCode string `json:"language_code,omitempty"` } ``` -------------------------------- ### Implement WithHTTPClient Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set a custom HTTP client, allowing configuration of poll timeout and the client itself. ```go func WithHTTPClient(pollTimeout time.Duration, client HttpClient) Option ``` -------------------------------- ### POST /createChatSubscriptionInviteLink Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Creates a subscription invite link for a chat. ```APIDOC ## POST /createChatSubscriptionInviteLink ### Description Creates a new subscription invite link for a chat. ### Endpoint https://core.telegram.org/bots/api#createchatsubscriptioninvitelink ### Parameters #### Request Body - **params** (CreateChatSubscriptionInviteLinkParams) - Required - Parameters for creating the subscription invite link. ### Response #### Success Response (200) - **result** (models.ChatInviteLink) - The created chat invite link. ``` -------------------------------- ### Bot Initialization Options Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Configuration options used during the initialization of the Telegram bot instance. ```APIDOC ## Bot Initialization Options ### Description List of available options to configure the bot behavior during initialization. ### Options - **WithCheckInitTimeout(timeout time.Duration)** - Timeout for check init bot - **WithMiddlewares(middlewares ...Middleware)** - Add middlewares - **WithMessageTextHandler(pattern string, matchType MatchType, handler HandlerFunc)** - Add handler for Message.Text field - **WithCallbackQueryDataHandler(pattern string, matchType MatchType, handler HandlerFunc)** - Add handler for CallbackQuery.Data field - **WithDebug()** - Enable debug mode - **WithHTTPClient(pollTimeout time.Duration, client HttpClient)** - Set custom http client - **WithServerURL(serverURL string)** - Set server url - **WithWorkers(count int)** - Set the number of workers processing the Updates channel ``` -------------------------------- ### Configure Bot Initialization Timeout Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Customizes the timeout duration for the initial getMe API call made when the bot is initialized. Use bot.WithCheckInitTimeout to specify a different duration. ```go b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", bot.WithCheckInitTimeout(5*time.Second)) ``` -------------------------------- ### Set Chat Menu Button Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Configures the menu button for a chat. ```go func (b *Bot) SetChatMenuButton(ctx context.Context, params *SetChatMenuButtonParams) (bool, error) ``` -------------------------------- ### Send Media Group with Local and Remote Files Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Demonstrates sending a media group with both a remote URL and a locally attached photo. Use `attach://` for local files and provide a `MediaAttachment` with the file content. ```go fileContent, _ := os.ReadFile("/path/to/image.png") media1 := &models.InputMediaPhoto{ Media: "https://telegram.org/img/t_logo.png", } media2 := &models.InputMediaPhoto{ Media: "attach://image.png", Caption: "2", MediaAttachment: bytes.NewReader(fileContent), } params := &bot.SendMediaGroupParams{ ChatID: update.Message.Chat.ID, Media: []models.InputMedia{ media1, media2, }, } bot.SendMediaGroup(ctx, params) ``` -------------------------------- ### Implement WithDebug Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to enable debug mode, which logs all requests and responses. ```go func WithDebug() Option ``` -------------------------------- ### Define GiftPremiumSubscriptionParams Struct Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Defines parameters for gifting a premium subscription. Requires Go v1.15.0 or later. ```go type GiftPremiumSubscriptionParams struct { UserID int64 `json:"user_id"` MonthCount int `json:"month_count"` StarCount int `json:"star_count"` Text string `json:"text,omitempty"` TextParseMode string `json:"text_parse_mode,omitempty"` TextEntities []models.MessageEntity `json:"text_entities,omitempty"` } ``` -------------------------------- ### SetMyShortDescriptionParams Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this struct to set a short description for the bot. This description will be shown in the chat with the bot. Supports localization. ```APIDOC ## SetMyShortDescriptionParams ### Description Sets a short description for the bot, which is displayed in the chat with the bot. Supports localization. ### Method POST ### Endpoint /setMyShortDescription ### Parameters #### Request Body - **short_description** (string) - Optional - New short description for the bot. Maximum 120 characters. - **language_code** (string) - Optional - ISO 639-1 language code. If not specified, the description will be applied to all languages. ### Request Example ```json { "short_description": "Your friendly neighborhood bot!", "language_code": "en" } ``` ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful. #### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Implement WithPhotoCaptionHandler Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set a handler for incoming photos with captions. Can also be registered using bot.RegisterHandler. Requires Go v1.12.1 or later. ```go func WithPhotoCaptionHandler(pattern string, matchType MatchType, handler HandlerFunc) Option ``` -------------------------------- ### Send Message with Bot API Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Demonstrates how to send a message using the bot.SendMessage function. Parameters for the message, including ChatID and Text, should be provided as a pointer to a SendMessageParams struct. ```go bot.SendMessage(ctx, &bot.SendMessageParams{...}) ``` -------------------------------- ### Implement WithDefaultHandler Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set a default handler for any incoming updates that do not match other specific handlers. ```go func WithDefaultHandler(handler HandlerFunc) Option ``` -------------------------------- ### Set Business Account Username Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the username for a business account. ```go func (b *Bot) SetBusinessAccountUsername(ctx context.Context, params *SetBusinessAccountUsernameParams) (bool, error) ``` -------------------------------- ### Set My Name Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the bot's name. ```go func (b *Bot) SetMyName(ctx context.Context, params *SetMyNameParams) (bool, error) ``` -------------------------------- ### Implement WithInitialOffset Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set an initial offset for the getUpdates method, useful for resuming updates from a specific point. Requires Go v1.13.3 or later. ```go func WithInitialOffset(offset int64) Option ``` -------------------------------- ### Set Business Account Name Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the business account name. ```go func (b *Bot) SetBusinessAccountName(ctx context.Context, params *SetBusinessAccountNameParams) (bool, error) ``` -------------------------------- ### Implement WithCallbackQueryDataHandler Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set a handler for incoming callback query data. Can also be registered using bot.RegisterHandler. ```go func WithCallbackQueryDataHandler(pattern string, matchType MatchType, handler HandlerFunc) Option ``` -------------------------------- ### CreateChatSubscriptionInviteLinkParams Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Parameters for creating a subscription invite link for a chat. ```APIDOC ## CreateChatSubscriptionInviteLinkParams ### Description Parameters for creating a subscription invite link for a chat. ### Method POST ### Endpoint /createChatSubscriptionInviteLink ### Parameters #### Request Body - **ChatID** (any) - Required - The chat ID. - **Name** (string) - Optional - The name of the subscription. - **SubscriptionPeriod** (int) - Required - The subscription period in seconds. - **SubscriptionPrice** (int) - Required - The subscription price in the smallest units of the currency. ### Request Example ```json { "chat_id": "@mychannel", "name": "Premium Subscription", "subscription_period": 2592000, "subscription_price": 1000 } ``` ### Response #### Success Response (200) - **InviteLink** (string) - The invite link. #### Response Example ```json { "ok": true, "result": { "invite_link": "https://t.me/+abcdefg12345" } } ``` ``` -------------------------------- ### Define CreateNewStickerSetParams Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Parameters for creating a new sticker set. ```go type CreateNewStickerSetParams struct { UserID int64 `json:"user_id"` Name string `json:"name"` Title string `json:"title"` Stickers []models.InputSticker `json:"stickers"` StickerType string `json:"sticker_type,omitempty"` NeedsRepainting bool `json:"needs_repainting,omitempty"` } ``` -------------------------------- ### Define Chat Management Parameters Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Structs for modifying chat properties such as titles, descriptions, permissions, and administrator settings. ```go type SetChatAdministratorCustomTitleParams struct { ChatID any `json:"chat_id"` UserID int64 `json:"user_id"` CustomTitle string `json:"custom_title"` } ``` ```go type SetChatDescriptionParams struct { ChatID any `json:"chat_id"` Description string `json:"description"` } ``` ```go type SetChatMemberTagParams struct { ChatID any `json:"chat_id" rules:"required,chat_id"` UserID int64 `json:"user_id" rules:"required"` Tag string `json:"tag,omitempty"` } ``` ```go type SetChatMenuButtonParams struct { ChatID any `json:"chat_id,omitempty"` MenuButton models.InputMenuButton `json:"menu_button"` } ``` ```go type SetChatPermissionsParams struct { ChatID any `json:"chat_id"` Permissions models.ChatPermissions `json:"permissions"` UseIndependentChatPermissions bool `json:"use_independent_chat_permissions,omitempty"` } ``` ```go type SetChatPhotoParams struct { ChatID any `json:"chat_id"` Photo models.InputFile `json:"photo"` } ``` ```go type SetChatStickerSetParams struct { ChatID any `json:"chat_id"` StickerSetName string `json:"sticker_set_name"` } ``` ```go type SetChatTitleParams struct { ChatID any `json:"chat_id"` Title string `json:"title"` } ``` -------------------------------- ### Set My Commands Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to change the list of the bot's commands. See this manual for more details. ```APIDOC ## POST /setMyCommands ### Description Use this method to change the list of the bot's commands. See this manual for more details. ### Method POST ### Endpoint /setMyCommands ### Parameters #### Request Body - **commands** (Array of BotCommand) - Required - A JSON-serialized list of bot commands. You can use this method to clear the existing commands by passing an empty list. - **scope** (BotCommandScope) - Optional - A JSON-serialized object, describing the scope of bot commands. Defaults to BotCommandScopeDefault. - **language_code** (String) - Optional - A two-letter ISO 639-1 language code. If not specified, commands will be applied to all languages. ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful. #### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Bot Configuration Options Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Options for configuring the Telegram bot, including environment, handlers, and timeouts. ```APIDOC ## Bot Configuration Options ### Description These options are used to configure the behavior of the Telegram bot instance. ### Options #### `UseTestEnvironment()` - **Description**: Allows the bot to use the Telegram test environment. - **Added in**: v1.7.1 #### `WithAllowedUpdates(params AllowedUpdates)` - **Description**: Allows setting custom parameters for the `getUpdates` method. - **Added in**: v1.1.5 #### `WithCallbackQueryDataHandler(pattern string, matchType MatchType, handler HandlerFunc)` - **Description**: Allows setting a handler for incoming callback query data. Can also be used with `*bot.RegisterHandler` after bot creation. #### `WithCheckInitTimeout(timeout time.Duration)` - **Description**: Allows redefining the `CheckInitTimeout`. - **Added in**: v0.3.0 #### `WithDebug()` - **Description**: Allows enabling debug mode. In debug mode, all requests and responses are logged by a debug handler. #### `WithDebugHandler(handler DebugHandler)` - **Description**: Allows setting a custom handler for debug messages. - **Added in**: v0.7.5 #### `WithDefaultHandler(handler HandlerFunc)` - **Description**: Allows setting a default handler for all incoming updates. #### `WithErrorsHandler(handler ErrorsHandler)` - **Description**: Allows setting a handler for errors. #### `WithHTTPClient(pollTimeout time.Duration, client HttpClient)` - **Description**: Allows setting a custom HTTP client and poll timeout. #### `WithInitialOffset(offset int64)` - **Description**: Allows setting an initial offset for the `getUpdates` method. - **Added in**: v1.13.3 #### `WithMessageTextHandler(pattern string, matchType MatchType, handler HandlerFunc)` - **Description**: Allows setting a handler for incoming text messages. Can also be used with `*bot.RegisterHandler` after bot creation. #### `WithMiddlewares(middlewares ...Middleware)` - **Description**: Allows setting middlewares for each incoming request. #### `WithNotAsyncHandlers()` - **Description**: Allows handlers to run in the main goroutine instead of asynchronously. - **Added in**: v1.9.0 #### `WithPhotoCaptionHandler(pattern string, matchType MatchType, handler HandlerFunc)` - **Description**: Allows setting a handler for incoming photos with captions. Can also be used with `*bot.RegisterHandler` after bot creation. - **Added in**: v1.12.1 #### `WithServerURL(serverURL string)` - **Description**: Allows setting a custom server URL for the bot. ### Handler Types - **`HandlerFunc`**: A function type that handles incoming updates. - **`HandlerType`**: An integer type representing different kinds of handlers. - `HandlerTypeMessageText` - `HandlerTypeCallbackQueryData` - `HandlerTypeCallbackQueryGameShortName` - `HandlerTypePhotoCaption` ### Match Types - **`MatchType`**: An integer type used for pattern matching in handlers. - `MatchTypeExact` - `MatchTypePrefix` - `MatchTypeContains` - `MatchTypeCommand` - `MatchTypeCommandStartOnly` ### Match Function - **`MatchFunc`**: A function type that determines if an update should be handled. - **Added in**: v0.3.3 ### Middleware - **`Middleware`**: A function type that wraps `HandlerFunc` to add pre- or post-processing logic. ### Other Types - **`HttpClient`**: An interface for making HTTP requests. - **`MigrateError`**: An error type indicating a migration is needed, including the target chat ID. - **Added in**: v1.2.1 ``` -------------------------------- ### POST /sendDocument Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to send general files. ```APIDOC ## POST /sendDocument ### Description Use this method to send general files. ### Method POST ### Request Body - **business_connection_id** (string) - Optional - Unique identifier of the business connection - **chat_id** (any) - Required - Unique identifier for the target chat - **message_thread_id** (int) - Optional - Unique identifier for the target message thread - **direct_messages_topic_id** (int) - Optional - Unique identifier for the target direct messages topic - **document** (models.InputFile) - Required - File to send - **thumbnail** (models.InputFile) - Optional - Thumbnail of the file sent - **caption** (string) - Optional - Document caption - **parse_mode** (models.ParseMode) - Optional - Mode for parsing entities in the caption - **caption_entities** ([]models.MessageEntity) - Optional - List of special entities in the caption - **disable_content_type_detection** (bool) - Optional - Disables automatic server-side content type detection - **disable_notification** (bool) - Optional - Sends the message silently - **protect_content** (bool) - Optional - Protects the contents of the sent message - **allow_paid_broadcast** (bool) - Optional - Allows the message to be a paid broadcast - **message_effect_id** (string) - Optional - Unique identifier of the message effect - **suggested_post_parameters** (models.SuggestedPostParameters) - Optional - Suggested post parameters - **reply_parameters** (models.ReplyParameters) - Optional - Description of the message to reply to - **reply_markup** (models.ReplyMarkup) - Optional - Additional interface options ``` -------------------------------- ### Set My Commands Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to change the list of the bot's commands. See this manual for more details on how to use commands. Returns true on success. ```APIDOC ## POST /setMyCommands ### Description Use this method to change the list of the bot's commands. See this manual for more details on how to use commands. Returns true on success. ### Method POST ### Endpoint /setMyCommands ### Parameters #### Request Body - **commands** (array of BotCommand) - Required - A JSON-serialized list of bot commands - **scope** (BotCommandScope) - Optional - A JSON-serialized object, describing the scope of bot commands - **language_code** (string) - Optional - A two-letter ISO 639-1 language code. If empty, commands will be applied to all languages. ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Set My Description Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to change the bot's description, which is shown in the chat with the bot. Returns true on success. ```APIDOC ## POST /setMyDescription ### Description Use this method to change the bot's description, which is shown in the chat with the bot. Returns true on success. ### Method POST ### Endpoint /setMyDescription ### Parameters #### Request Body - **description** (string) - Optional - New bot description, 1-512 characters - **language_code** (string) - Optional - A two-letter ISO 639-1 language code. If empty, the description will be applied to all languages. ### Response #### Success Response (200) - **ok** (boolean) - True if the request was successful ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Send Photo using File Contents Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Send a photo by uploading its contents from a local file path. Use `models.InputFileUpload` and provide the filename and a reader for the file data. Ensure the file exists and is readable. ```go fileContent, _ := os.ReadFile("/path/to/image.png") params := &bot.SendPhotoParams{ ChatID: chatID, Photo: &models.InputFileUpload{Filename: "image.png", Data: bytes.NewReader(fileContent)}, } bot.SendPhoto(ctx, params) ``` -------------------------------- ### Set Chat Description Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the description of a chat. ```go func (b *Bot) SetChatDescription(ctx context.Context, params *SetChatDescriptionParams) (bool, error) ``` -------------------------------- ### POST /sendGame Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Use this method to send a game. ```APIDOC ## POST /sendGame ### Description Use this method to send a game. ### Method POST ### Request Body - **business_connection_id** (string) - Optional - Unique identifier of the business connection - **chat_id** (any) - Required - Unique identifier for the target chat - **message_thread_id** (int) - Optional - Unique identifier for the target message thread - **game_short_name** (string) - Required - Short name of the game - **disable_notification** (bool) - Optional - Sends the message silently - **protect_content** (bool) - Optional - Protects the contents of the sent message - **allow_paid_broadcast** (bool) - Optional - Allows the message to be a paid broadcast - **message_effect_id** (string) - Optional - Unique identifier of the message effect - **reply_parameters** (models.ReplyParameters) - Optional - Description of the message to reply to - **reply_markup** (models.ReplyMarkup) - Optional - Additional interface options ``` -------------------------------- ### Set Business Account Profile Photo Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the profile photo for a business account. ```go func (b *Bot) SetBusinessAccountProfilePhoto(ctx context.Context, params *SetBusinessAccountProfilePhotoParams) (bool, error) ``` -------------------------------- ### Implement WithDebugHandler Option Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Option function to set a custom handler for debug messages. Requires Go v0.7.5 or later. ```go func WithDebugHandler(handler DebugHandler) Option ``` -------------------------------- ### Set Chat Permissions Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the default permissions for chat members. ```go func (b *Bot) SetChatPermissions(ctx context.Context, params *SetChatPermissionsParams) (bool, error) ``` -------------------------------- ### Create Chat Invite Link Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Creates an invite link for a chat. Requires `CreateChatInviteLinkParams`. ```APIDOC ## POST /createChatInviteLink ### Description Creates an invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate permissions. ### Method `CreateChatInviteLink` ### Endpoint `https://core.telegram.org/bots/api#createchatinvitelink` ### Parameters #### Request Body - **params** (*CreateChatInviteLinkParams) - Required - Parameters for creating the invite link. - **ChatID** (any) - Required - Unique identifier for the target chat or username of the target channel (in the format `@channelusername`). - **ExpireDate** (int) - Optional - Point in time (Unix timestamp) when the link will expire. - **MemberLimit** (int) - Optional - Maximum number of users that can be members of the chat accessed via the link. The default is unlimited. - **CreatesJoinRequest** (bool) - Optional - True, if users joining the chat via the link need to be approved by chat administrators. ### Response #### Success Response (200) - **(*models.ChatInviteLink)** - Returns the created `ChatInviteLink` object. #### Response Example ```json { "ok": true, "result": { "invite_link": "https://t.me/+ExampleLink", "creator_user_id": 123456789, "is_primary": false, "is_revoked": false, "expire_date": 1678886400, "member_limit": 10 } } ``` ``` -------------------------------- ### Set My Profile Photo Source: https://pkg.go.dev/github.com/go-telegram/bot#section-readme Updates the bot's profile photo. ```go func (b *Bot) SetMyProfilePhoto(ctx context.Context, params *SetMyProfilePhotoParams) (bool, error) ```