Categorygithub.com/go-telegram-bot-api/telegram-bot-api/v5

# README

Golang bindings for the Telegram Bot API

Go Reference Test

All methods are fairly self-explanatory, and reading the godoc page should explain everything. If something isn't clear, open an issue or submit a pull request.

There are more tutorials and high-level information on the website, go-telegram-bot-api.dev.

The scope of this project is just to provide a wrapper around the API without any additional features. There are other projects for creating something with plugins and command handlers without having to design all that yourself.

Join the development group if you want to ask questions or discuss development.

Example

First, ensure the library is installed and up to date by running go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5.

This is a very simple bot that just displays any gotten updates, then replies it to that chat.

package main

import (
	"log"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
	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 { // If we got a message
			log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

			msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
			msg.ReplyToMessageID = update.Message.MessageID

			bot.Send(msg)
		}
	}
}

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

package main

import (
	"log"
	"net/http"

	"github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
	if err != nil {
		log.Fatal(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	wh, _ := tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")

	_, err = bot.SetWebhook(wh)
	if err != nil {
		log.Fatal(err)
	}

	info, err := bot.GetWebhookInfo()
	if err != nil {
		log.Fatal(err)
	}

	if info.LastErrorDate != 0 {
		log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
	}

	updates := bot.ListenForWebhook("/" + bot.Token)
	go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

	for update := range updates {
		log.Printf("%+v\n", update)
	}
}

If you need, you may generate a self-signed certificate, as this requires HTTPS / TLS. The above example tells Telegram that this is your certificate and that it should be trusted, even though it is not properly signed.

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes

Now that Let's Encrypt is available, you may wish to generate your free TLS certificate there.

# Functions

EscapeText takes an input text and escape Telegram markup symbols.
NewAnimation creates a new sendAnimation request.
NewAudio creates a new sendAudio request.
NewBotAPI creates a new BotAPI instance.
NewBotAPIWithAPIEndpoint creates a new BotAPI instance and allows you to pass API endpoint.
NewBotAPIWithClient creates a new BotAPI instance and allows you to pass a http.Client.
NewBotCommandScopeAllChatAdministrators represents the scope of bot commands, covering all group and supergroup chat administrators.
NewBotCommandScopeAllGroupChats represents the scope of bot commands, covering all group and supergroup chats.
NewBotCommandScopeAllPrivateChats represents the scope of bot commands, covering all private chats.
NewBotCommandScopeChat represents the scope of bot commands, covering a specific chat.
NewBotCommandScopeChatAdministrators represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.
NewBotCommandScopeChatMember represents the scope of bot commands, covering a specific member of a group or supergroup chat.
NewBotCommandScopeDefault represents the default scope of bot commands.
NewCallback creates a new callback message.
NewCallbackWithAlert creates a new callback message that alerts the user.
NewChatAction sets a chat action.
NewChatDescription allows you to update the description of a chat.
NewChatPhoto allows you to update the photo for a chat.
NewChatTitle allows you to update the title of a chat.
NewContact allows you to send a shared contact.
NewCopyMessage creates a new copy message.
NewDeleteChatPhoto allows you to delete the photo for a chat.
NewDeleteMessage creates a request to delete a message.
NewDeleteMyCommands allows you to delete the registered commands.
NewDeleteMyCommandsWithScope allows you to delete the registered commands for a given scope.
NewDeleteMyCommandsWithScopeAndLanguage allows you to delete the registered commands for a given scope and language code.
NewDice allows you to send a random dice roll.
NewDiceWithEmoji allows you to send a random roll of one of many types.
NewDocument creates a new sendDocument request.
NewEditMessageCaption allows you to edit the caption of a message.
NewEditMessageReplyMarkup allows you to edit the inline keyboard markup.
NewEditMessageText allows you to edit the text of a message.
NewEditMessageTextAndMarkup allows you to edit the text and replymarkup of a message.
NewForward creates a new forward.
NewGetMyCommandsWithScope allows you to set the registered commands for a given scope.
NewGetMyCommandsWithScopeAndLanguage allows you to set the registered commands for a given scope and language code.
NewInlineKeyboardButtonData creates an inline keyboard button with text and data for a callback.
NewInlineKeyboardButtonLoginURL creates an inline keyboard button with text which goes to a LoginURL.
NewInlineKeyboardButtonSwitch creates an inline keyboard button with text which allows the user to switch to a chat or return to a chat.
NewInlineKeyboardButtonURL creates an inline keyboard button with text which goes to a URL.
NewInlineKeyboardMarkup creates a new inline keyboard.
NewInlineKeyboardRow creates an inline keyboard row with buttons.
NewInlineQueryResultArticle creates a new inline query article.
NewInlineQueryResultArticleHTML creates a new inline query article with HTML parsing.
NewInlineQueryResultArticleMarkdown creates a new inline query article with Markdown parsing.
NewInlineQueryResultArticleMarkdownV2 creates a new inline query article with MarkdownV2 parsing.
NewInlineQueryResultAudio creates a new inline query audio.
NewInlineQueryResultCachedAudio create a new inline query with cached photo.
NewInlineQueryResultCachedDocument create a new inline query with cached photo.
NewInlineQueryResultCachedGIF create a new inline query with cached photo.
NewInlineQueryResultCachedMPEG4GIF create a new inline query with cached MPEG4 GIF.
NewInlineQueryResultCachedPhoto create a new inline query with cached photo.
NewInlineQueryResultCachedSticker create a new inline query with cached sticker.
NewInlineQueryResultCachedVideo create a new inline query with cached video.
NewInlineQueryResultCachedVoice create a new inline query with cached photo.
NewInlineQueryResultDocument creates a new inline query document.
NewInlineQueryResultGIF creates a new inline query GIF.
NewInlineQueryResultLocation creates a new inline query location.
NewInlineQueryResultMPEG4GIF creates a new inline query MPEG4 GIF.
NewInlineQueryResultPhoto creates a new inline query photo.
NewInlineQueryResultPhotoWithThumb creates a new inline query photo.
NewInlineQueryResultVenue creates a new inline query venue.
NewInlineQueryResultVideo creates a new inline query video.
NewInlineQueryResultVoice creates a new inline query voice.
NewInputMediaAnimation creates a new InputMediaAnimation.
NewInputMediaAudio creates a new InputMediaAudio.
NewInputMediaDocument creates a new InputMediaDocument.
NewInputMediaPhoto creates a new InputMediaPhoto.
NewInputMediaVideo creates a new InputMediaVideo.
NewInvoice creates a new Invoice request to the user.
NewKeyboardButton creates a regular keyboard button.
NewKeyboardButtonContact creates a keyboard button that requests user contact information upon click.
NewKeyboardButtonLocation creates a keyboard button that requests user location information upon click.
NewKeyboardButtonRow creates a row of keyboard buttons.
NewLocation shares your location.
NewMediaGroup creates a new media group.
NewMessage creates a new Message.
NewMessageToChannel creates a new Message that is sent to a channel by username.
NewOneTimeReplyKeyboard creates a new one time keyboard.
NewPhoto creates a new sendPhoto request.
NewPhotoToChannel creates a new photo uploader to send a photo to a channel.
NewPoll allows you to create a new poll.
NewRemoveKeyboard hides the keyboard, with the option for being selective or hiding for everyone.
NewReplyKeyboard creates a new regular keyboard with sane defaults.
NewSetMyCommands allows you to set the registered commands.
NewSetMyCommandsWithScope allows you to set the registered commands for a given scope.
NewSetMyCommandsWithScopeAndLanguage allows you to set the registered commands for a given scope and language code.
NewSticker creates a new sendSticker request.
NewStopPoll allows you to stop a poll.
NewUpdate gets updates since the last Offset.
NewUserProfilePhotos gets user profile photos.
NewVenue allows you to send a venue and its location.
NewVideo creates a new sendVideo request.
NewVideoNote creates a new sendVideoNote request.
NewVoice creates a new sendVoice request.
NewWebhook creates a new webhook.
NewWebhookWithCert creates a new webhook with a certificate.
SetLogger specifies the logger that the package should use.
WriteToHTTPResponse writes the request to the HTTP ResponseWriter.

# Constants

APIEndpoint is the endpoint for all API methods, with formatting for Sprintf.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
Constant values for ChatActions.
ErrAPIForbidden happens when a token is bad.
Library errors.
FileEndpoint is the endpoint for downloading a file from Telegram.
Constant values for ParseMode in MessageConfig.
Constant values for ParseMode in MessageConfig.
Constant values for ParseMode in MessageConfig.
UpdateTypeCallbackQuery is new incoming callback query.
UpdateTypeChannelPost is new incoming channel post of any kind — text, photo, sticker, etc.
UpdateTypeChatMember is when the bot must be an administrator in the chat and must explicitly specify this update in the list of allowed_updates to receive these updates.
UpdateTypeChosenInlineResult i the result of an inline query that was chosen by a user and sent to their chat partner.
UpdateTypeEditedChannelPost is new version of a channel post that is known to the bot and was edited.
UpdateTypeEditedMessage is new version of a message that is known to the bot and was edited.
UpdateTypeInlineQuery is new incoming inline query.
UpdateTypeMessage is new incoming message of any kind — text, photo, sticker, etc.
UpdateTypeMyChatMember is when the bot's chat member status was updated in a chat.
UpdateTypePoll is new poll state.
UpdateTypePollAnswer is when user changed their answer in a non-anonymous poll.
UpdateTypePreCheckoutQuery is new incoming pre-checkout query.
UpdateTypeShippingQuery is new incoming shipping query.

# Structs

AddStickerConfig allows you to add a sticker to a set.
Animation represents an animation file.
AnimationConfig contains information about a SendAnimation request.
APIResponse is a response from the Telegram API with the result stored raw.
ApproveChatJoinRequestConfig allows you to approve a chat join request.
Audio represents an audio file to be treated as music by the Telegram clients.
AudioConfig contains information about a SendAudio request.
BanChatMemberConfig contains extra fields to kick user.
BanChatSenderChatConfig bans a channel chat in a supergroup or a channel.
BaseChat is base type for all chat config types.
BaseEdit is base type of all chat edits.
BaseFile is a base type for all file config types.
BaseInputMedia is a base type for the InputMedia types.
BotAPI allows you to interact with the Telegram Bot API.
BotCommand represents a bot command.
BotCommandScope represents the scope to which bot commands are applied.
CallbackConfig contains information on making a CallbackQuery response.
CallbackGame is for starting a game in an inline keyboard button.
CallbackQuery represents an incoming callback query from a callback button in an inline keyboard.
Chat represents a chat.
ChatActionConfig contains information about a SendChatAction request.
ChatAdministratorsConfig contains information about getting chat administrators.
ChatConfig contains information about getting information on a chat.
ChatConfigWithUser contains information about a chat and a user.
ChatInfoConfig contains information about getting chat information.
ChatInviteLink represents an invite link for a chat.
ChatInviteLinkConfig contains information about getting a chat link.
ChatJoinRequest represents a join request sent to a chat.
ChatLocation represents a location to which a chat is connected.
ChatMember contains information about one member of a chat.
ChatMemberConfig contains information about a user in a chat for use with administrative functions such as kicking or unbanning a user.
ChatMemberCountConfig contains information about getting the number of users in a chat.
ChatMemberUpdated represents changes in the status of a chat member.
ChatPermissions describes actions that a non-administrator user is allowed to take in a chat.
ChatPhoto represents a chat photo.
ChosenInlineResult is an inline query result chosen by a User.
CloseConfig is a request to close the bot instance on a local server.
Contact represents a phone contact.
ContactConfig allows you to send a contact.
CopyMessageConfig contains information about a copyMessage request.
CreateChatInviteLinkConfig allows you to create an additional invite link for a chat.
No description provided by the author
No description provided by the author
DeclineChatJoinRequest allows you to decline a chat join request.
DeleteChatPhotoConfig allows you to delete a group, supergroup, or channel's photo.
DeleteChatStickerSetConfig allows you to remove a supergroup's sticker set.
DeleteMessageConfig contains information of a message in a chat to delete.
No description provided by the author
DeleteStickerConfig allows you to delete a sticker from a set.
DeleteWebhookConfig is a helper to delete a webhook.
Dice represents an animated emoji that displays a random value.
DiceConfig contains information about a sendDice request.
Document represents a general file.
DocumentConfig contains information about a SendDocument request.
EditChatInviteLinkConfig allows you to edit a non-primary invite link created by the bot.
EditMessageCaptionConfig allows you to modify the caption of a message.
EditMessageLiveLocationConfig allows you to update a live location.
EditMessageMediaConfig allows you to make an editMessageMedia request.
EditMessageReplyMarkupConfig allows you to modify the reply markup of a message.
EditMessageTextConfig allows you to modify the text in a message.
No description provided by the author
No description provided by the author
Error is an error containing extra information returned by the Telegram API.
File contains information about a file to download from Telegram.
FileBytes contains information about a set of bytes to upload as a File.
FileConfig has information about a file hosted on Telegram.
No description provided by the author
FileReader contains information about a reader to upload as a File.
ForceReply when receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply').
ForwardConfig contains information about a ForwardMessage request.
Game represents a game.
GameConfig allows you to send a game.
GameHighScore is a user's score and position on the leaderboard.
GetChatMemberConfig is information about getting a specific member in a chat.
GetGameHighScoresConfig allows you to fetch the high scores for a game.
GetMyCommandsConfig gets a list of the currently registered commands.
GetStickerSetConfig allows you to get the stickers in a set.
No description provided by the author
InlineConfig contains information on making an InlineQuery response.
InlineKeyboardButton represents one button of an inline keyboard.
InlineKeyboardMarkup represents an inline keyboard that appears right next to the message it belongs to.
InlineQuery is a Query from Telegram for an inline request.
InlineQueryResultArticle represents a link to an article or web page.
InlineQueryResultAudio is an inline query response audio.
InlineQueryResultCachedAudio is an inline query response with cached audio.
InlineQueryResultCachedDocument is an inline query response with cached document.
InlineQueryResultCachedGIF is an inline query response with cached gif.
InlineQueryResultCachedMPEG4GIF is an inline query response with cached H.264/MPEG-4 AVC video without sound gif.
InlineQueryResultCachedPhoto is an inline query response with cached photo.
InlineQueryResultCachedSticker is an inline query response with cached sticker.
InlineQueryResultCachedVideo is an inline query response with cached video.
InlineQueryResultCachedVoice is an inline query response with cached voice.
InlineQueryResultContact is an inline query response contact.
InlineQueryResultDocument is an inline query response document.
InlineQueryResultGame is an inline query response game.
InlineQueryResultGIF is an inline query response GIF.
InlineQueryResultLocation is an inline query response location.
InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF.
InlineQueryResultPhoto is an inline query response photo.
InlineQueryResultVenue is an inline query response venue.
InlineQueryResultVideo is an inline query response video.
InlineQueryResultVoice is an inline query response voice.
InputContactMessageContent contains a contact for displaying as an inline query result.
InputInvoiceMessageContent represents the content of an invoice message to be sent as the result of an inline query.
InputLocationMessageContent contains a location for displaying as an inline query result.
InputMediaAnimation is an animation to send as part of a media group.
InputMediaAudio is an audio to send as part of a media group.
InputMediaDocument is a general file to send as part of a media group.
InputMediaPhoto is a photo to send as part of a media group.
InputMediaVideo is a video to send as part of a media group.
InputTextMessageContent contains text for displaying as an inline query result.
InputVenueMessageContent contains a venue for displaying as an inline query result.
Invoice contains basic information about an invoice.
InvoiceConfig contains information for sendInvoice request.
KeyboardButton represents one button of the reply keyboard.
KeyboardButtonPollType represents type of poll, which is allowed to be created and sent when the corresponding button is pressed.
LabeledPrice represents a portion of the price for goods or services.
LeaveChatConfig allows you to leave a chat.
Location represents a point on the map.
LocationConfig contains information about a SendLocation request.
LoginURL represents a parameter of the inline keyboard button used to automatically authorize a user.
LogOutConfig is a request to log out of the cloud Bot API server.
MaskPosition describes the position on faces where a mask should be placed by default.
MediaGroupConfig allows you to send a group of media.
Message represents a message.
MessageAutoDeleteTimerChanged represents a service message about a change in auto-delete timer settings.
MessageConfig contains information about a SendMessage request.
MessageEntity represents one special entity in a text message.
MessageID represents a unique message identifier.
NewStickerSetConfig allows creating a new sticker set.
OrderInfo represents information about an order.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
PassportRequestInfoConfig allows you to request passport info.
PassportScope is the requested scopes of data.
PassportScopeElementOne requires the specified element be provided.
PassportScopeElementOneOfSeveral allows you to request any one of the requested documents.
No description provided by the author
PhotoConfig contains information about a SendPhoto request.
PhotoSize represents one size of a photo or a file / sticker thumbnail.
PinChatMessageConfig contains information of a message in a chat to pin.
Poll contains information about a poll.
PollAnswer represents an answer of a user in a non-anonymous poll.
PollOption contains information about one answer option in a poll.
PreCheckoutConfig conatins information for answerPreCheckoutQuery request.
PreCheckoutQuery contains information about an incoming pre-checkout query.
PromoteChatMemberConfig contains fields to promote members of chat.
ProximityAlertTriggered represents a service message sent when a user in the chat triggers a proximity alert sent by another user.
ReplyKeyboardMarkup represents a custom keyboard with reply options.
ReplyKeyboardRemove Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard.
RequestFile represents a file associated with a field name.
ResponseParameters are various errors that can be returned in APIResponse.
RestrictChatMemberConfig contains fields to restrict members of chat.
RevokeChatInviteLinkConfig allows you to revoke an invite link created by the bot.
No description provided by the author
SendPollConfig allows you to send a poll.
SetChatAdministratorCustomTitle sets the title of an administrative user promoted by the bot for a chat.
SetChatDescriptionConfig allows you to set the description of a supergroup or channel.
SetChatPermissionsConfig allows you to set default permissions for the members in a group.
SetChatPhotoConfig allows you to set a group, supergroup, or channel's photo.
SetChatStickerSetConfig allows you to set the sticker set for a supergroup.
SetChatTitleConfig allows you to set the title of something other than a private chat.
SetGameScoreConfig allows you to update the game score in a chat.
SetMyCommandsConfig sets a list of commands the bot understands.
SetStickerPositionConfig allows you to change the position of a sticker in a set.
SetStickerSetThumbConfig allows you to set the thumbnail for a sticker set.
ShippingAddress represents a shipping address.
ShippingConfig contains information for answerShippingQuery request.
ShippingOption represents one shipping option.
ShippingQuery contains information about an incoming shipping query.
Sticker represents a sticker.
StickerConfig contains information about a SendSticker request.
StickerSet represents a sticker set.
StopMessageLiveLocationConfig stops updating a live location.
StopPollConfig allows you to stop a poll sent by the bot.
SuccessfulPayment contains basic information about a successful payment.
UnbanChatMemberConfig allows you to unban a user.
UnbanChatSenderChatConfig unbans a previously banned channel chat in a supergroup or channel.
UnpinAllChatMessagesConfig contains information of all messages to unpin in a chat.
UnpinChatMessageConfig contains information of a chat message to unpin.
Update is an update response, from GetUpdates.
UpdateConfig contains information about a GetUpdates request.
UploadStickerConfig allows you to upload a sticker for use in a set later.
User represents a Telegram user or bot.
UserProfilePhotos contains a set of user profile photos.
UserProfilePhotosConfig contains information about a GetUserProfilePhotos request.
Venue represents a venue.
VenueConfig contains information about a SendVenue request.
Video represents a video file.
VideoConfig contains information about a SendVideo request.
VideoNote object represents a video message.
VideoNoteConfig contains information about a SendVideoNote request.
Voice represents a voice note.
VoiceChatEnded represents a service message about a voice chat ended in the chat.
VoiceChatParticipantsInvited represents a service message about new members invited to a voice chat.
VoiceChatScheduled represents a service message about a voice chat scheduled in the chat.
VoiceChatStarted represents a service message about a voice chat started in the chat.
VoiceConfig contains information about a SendVoice request.
WebhookConfig contains information about a SetWebhook request.
WebhookInfo is information about a currently set webhook.

# Interfaces

BotLogger is an interface that represents the required methods to log data.
Chattable is any config type that can be sent.
Fileable is any config type that can be sent that includes a file.
HTTPClient is the type needed for the bot to perform HTTP requests.
No description provided by the author
PassportScopeElement supports using one or one of several elements.
RequestFileData represents the data to be used for a file.

# Type aliases

FileID is an ID of a file already uploaded to Telegram.
FilePath is a path to a local file.
FileURL is a URL to use as a file for a request.
KickChatMemberConfig contains extra fields to ban user.
Params represents a set of parameters that gets passed to a request.
No description provided by the author