Documentation
¶
Overview ¶
Package golagram is a Go framework for building Telegram bots: a Router/Ctx dispatch model routes each of Telegram's ~25 update kinds to composable filters and handlers, an FSM tracks per-chat/user conversation state across any update kind (including callback queries), and generated code covers the full Bot API surface (all methods, types, and polymorphic union decoding) straight from Telegram's published spec.
Both polling (Run) and webhook (RunWebhook) runtimes share one dispatcher and worker pool, so a bot's handlers don't change when switching between them. See the README for a quick start and a tour of the utility belt (keyboards, formatting, deep links, payments, i18n, WebApp validation); types.gen.go and methods.gen.go are generated from scripts/api.json — see internal/gen and `go generate ./...` to regenerate after a Bot API update.
Index ¶
- Constants
- Variables
- func ChatMemberIsMember(m ChatMember) bool
- func ChatMemberStatus(m ChatMember) string
- func DecodeStartPayload(payload string) (string, error)
- func EncodeStartPayload(raw string) string
- func EscapeHTML(s string) string
- func EscapeMarkdownV2(s string) string
- func EscapeMarkdownV2Code(s string) string
- func EscapeMarkdownV2Link(s string) string
- func FSMGet[T any](f *FSMContext, key string) (T, bool, error)
- func FSMSet(f *FSMContext, key string, value any) error
- func IsBlockedByUser(err error) bool
- func IsChatNotFound(err error) bool
- func IsConflict(err error) bool
- func IsFlood(err error) bool
- func KeepChatAction(c *Ctx, action string) (stop func())
- func Reply(req webhookMethodNamer) error
- func RichBlockPlainText(b RichBlock) string
- func RichTextPlainText(t RichText) string
- func SplitText(text string, limit ...int) []string
- func Typing(c *Ctx) (stop func())
- func ValidateToken(token string) error
- type ACO
- type AIO
- type APIError
- type AcceptedGiftTypes
- type AddStickerToSetRequest
- type AdminCache
- type AffiliateInfo
- type Animation
- type AnswerCallbackOptions
- type AnswerCallbackQueryRequest
- type AnswerChatJoinRequestQueryRequest
- type AnswerGuestQueryRequest
- type AnswerInlineOptions
- type AnswerInlineQueryRequest
- type AnswerPreCheckoutQueryRequest
- type AnswerShippingQueryRequest
- type AnswerWebAppQueryRequest
- type ApproveChatJoinRequestRequest
- type ApproveSuggestedPostRequest
- type Audio
- type BackgroundFill
- type BackgroundFillFreeformGradient
- type BackgroundFillGradient
- type BackgroundFillSolid
- type BackgroundType
- type BackgroundTypeChatTheme
- type BackgroundTypeFill
- type BackgroundTypePattern
- type BackgroundTypeWallpaper
- type Backoff
- type BanChatMemberRequest
- type BanChatSenderChatRequest
- type Birthdate
- type BotAccessSettings
- type BotCommand
- type BotCommandScope
- type BotCommandScopeAllChatAdministrators
- type BotCommandScopeAllGroupChats
- type BotCommandScopeAllPrivateChats
- type BotCommandScopeChat
- type BotCommandScopeChatAdministrators
- type BotCommandScopeChatMember
- type BotCommandScopeDefault
- type BotDescription
- type BotName
- type BotShortDescription
- type BroadcastOption
- type BroadcastProgress
- type BroadcastResult
- type BroadcastSendFunc
- type BusinessBotRights
- type BusinessConnection
- type BusinessIntro
- type BusinessLocation
- type BusinessMessagesDeleted
- type BusinessOpeningHours
- type BusinessOpeningHoursInterval
- type CallbackData
- func (cd *CallbackData[T]) Button(text string, v T) InlineKeyboardButton
- func (cd *CallbackData[T]) Filter() Filter
- func (cd *CallbackData[T]) FilterWhere(pred func(T) bool) Filter
- func (cd *CallbackData[T]) FromCtx(c *Ctx) (T, error)
- func (cd *CallbackData[T]) MustPack(v T) string
- func (cd *CallbackData[T]) Pack(v T) (string, error)
- func (cd *CallbackData[T]) Unpack(data string) (T, error)
- func (cd *CallbackData[T]) WithHMAC(secret []byte) *CallbackData[T]
- type CallbackGame
- type CallbackQuery
- func (e *CallbackQuery) Answer(text string, options ...*AnswerCallbackOptions) error
- func (e *CallbackQuery) Answered() bool
- func (e *CallbackQuery) ChatID() int64
- func (e *CallbackQuery) FSM() *FSMContext
- func (e *CallbackQuery) FromID() int64
- func (e *CallbackQuery) Reply(text string, options ...*SendMessageOptions) (*Message, error)
- func (e *CallbackQuery) SendMessage(text string, options ...*SendMessageOptions) (*Message, error)
- type Chat
- type ChatAdministratorRights
- type ChatBackground
- type ChatBoost
- type ChatBoostAdded
- type ChatBoostRemoved
- type ChatBoostSource
- type ChatBoostSourceGiftCode
- type ChatBoostSourceGiveaway
- type ChatBoostSourcePremium
- type ChatBoostUpdated
- type ChatFullInfo
- type ChatID
- type ChatInviteLink
- type ChatJoinRequest
- type ChatLocation
- type ChatMember
- type ChatMemberAdministrator
- type ChatMemberBanned
- type ChatMemberLeft
- type ChatMemberMember
- type ChatMemberOwner
- type ChatMemberRestricted
- type ChatMemberUpdated
- type ChatOwnerChanged
- type ChatOwnerLeft
- type ChatPermissions
- type ChatPhoto
- type ChatShared
- type Checklist
- type ChecklistTask
- type ChecklistTasksAdded
- type ChecklistTasksDone
- type ChosenInlineResult
- type CloseForumTopicRequest
- type CloseGeneralForumTopicRequest
- type CommandObject
- type Contact
- type ConvertGiftToStarsRequest
- type CopyMessageRequest
- type CopyMessagesRequest
- type CopyTextButton
- type CreateChatInviteLinkRequest
- type CreateChatSubscriptionInviteLinkRequest
- type CreateForumTopicRequest
- type CreateInvoiceLinkRequest
- type CreateNewStickerSetRequest
- type Ctx
- func (c *Ctx) Answer(text string, options ...*SendMessageOptions) (*Message, error)
- func (c *Ctx) AnswerCallback(text string, options ...*AnswerCallbackOptions) error
- func (c *Ctx) AnswerInline(results []InlineQueryResult, options ...*AnswerInlineOptions) error
- func (c *Ctx) AnswerPreCheckout() error
- func (c *Ctx) AnswerPreCheckoutError(reason string) error
- func (c *Ctx) AnswerShipping(options []ShippingOption) error
- func (c *Ctx) AnswerShippingError(reason string) error
- func (c *Ctx) Bot() *TelegramBot
- func (c *Ctx) Chat() *Chat
- func (c *Ctx) Command() *CommandObject
- func (c *Ctx) Delete() error
- func (c *Ctx) EditCaption(caption string, options ...*EditCaptionOptions) (*Message, error)
- func (c *Ctx) EditReplyMarkup(markup *InlineKeyboardMarkup) (*Message, error)
- func (c *Ctx) EditText(text string, options ...*EditMessageOptions) (*Message, error)
- func (c *Ctx) FSM() *FSMContext
- func (c *Ctx) Flags() map[string]any
- func (c *Ctx) From() *User
- func (c *Ctx) Get(key string) (any, bool)
- func (c *Ctx) Locale() string
- func (c *Ctx) Reply(text string, options ...*SendMessageOptions) (*Message, error)
- func (c *Ctx) SendChatAction(action string) error
- func (c *Ctx) SendStarsInvoice(title, description, payload string, stars int64) (*Message, error)
- func (c *Ctx) Sender() *Sender
- func (c *Ctx) Set(key string, value any)
- func (c *Ctx) SetLocale(locale string) error
- func (c *Ctx) T(key string, args ...any) string
- func (c *Ctx) TN(key string, n int, args ...any) string
- func (c *Ctx) Text() string
- type DeclineChatJoinRequestRequest
- type DeclineSuggestedPostRequest
- type DeleteAllMessageReactionsRequest
- type DeleteBusinessMessagesRequest
- type DeleteChatPhotoRequest
- type DeleteChatStickerSetRequest
- type DeleteForumTopicRequest
- type DeleteMessageReactionRequest
- type DeleteMessageRequest
- type DeleteMessagesRequest
- type DeleteMyCommandsRequest
- type DeleteStickerFromSetRequest
- type DeleteStickerSetRequest
- type DeleteStoryRequest
- type DeleteWebhookRequest
- type Dice
- type DirectMessagePriceChanged
- type DirectMessagesTopic
- type Document
- type ECO
- type EMO
- type EditCaptionOptions
- type EditChatInviteLinkRequest
- type EditChatSubscriptionInviteLinkRequest
- type EditForumTopicRequest
- type EditGeneralForumTopicRequest
- type EditMessageCaptionRequest
- type EditMessageChecklistRequest
- type EditMessageLiveLocationRequest
- type EditMessageMediaRequest
- type EditMessageOptions
- type EditMessageReplyMarkupRequest
- type EditMessageTextRequest
- type EditStoryRequest
- type EditUserStarSubscriptionRequest
- type EncryptedCredentials
- type EncryptedPassportElement
- type Entity
- type EntitySegment
- type ErrorHandlerFunc
- type ExportChatInviteLinkRequest
- type ExternalReplyInfo
- type FSMContext
- func (f *FSMContext) Clear() error
- func (f *FSMContext) Data() (map[string]any, error)
- func (f *FSMContext) Key() StorageKey
- func (f *FSMContext) SetData(data map[string]any) error
- func (f *FSMContext) SetState(state State) error
- func (f *FSMContext) State() (State, error)
- func (f *FSMContext) UpdateData(partial map[string]any) (map[string]any, error)
- type FSMKeyStrategy
- type FSMStorage
- type File
- type Filter
- func And(filters ...Filter) Filter
- func FilterAnimation() Filter
- func FilterAudio() Filter
- func FilterBotBlocked() Filter
- func FilterBotUnblocked() Filter
- func FilterCallbackData(data string) Filter
- func FilterCallbackPrefix(prefix string) Filter
- func FilterChatType(types ...string) Filter
- func FilterCommand(command string) Filter
- func FilterCommandStart() Filter
- func FilterCommandStartDeepLink() Filter
- func FilterContact() Filter
- func FilterDice() Filter
- func FilterDiceValue(values ...int64) Filter
- func FilterDocument() Filter
- func FilterFromSender(ids ...int64) Filter
- func FilterFromUser(ids ...int64) Filter
- func FilterFromUsername(usernames ...string) Filter
- func FilterHasEntity(types ...string) Filter
- func FilterIsForwarded() Filter
- func FilterIsReply() Filter
- func FilterIsTopicMessage() Filter
- func FilterJoined() Filter
- func FilterLeft() Filter
- func FilterLeftChatMember() Filter
- func FilterLocation() Filter
- func FilterMediaGroup() Filter
- func FilterNewChatMembers() Filter
- func FilterPhoto() Filter
- func FilterPoll() Filter
- func FilterPromotedToAdmin() Filter
- func FilterRegexp(re *regexp.Regexp) Filter
- func FilterSticker() Filter
- func FilterSuccessfulPayment() Filter
- func FilterText(text string) Filter
- func FilterTextContains(substr string) Filter
- func FilterTextEqualFold(text string) Filter
- func FilterTextPrefix(prefix string) Filter
- func FilterTextSuffix(suffix string) Filter
- func FilterVenue() Filter
- func FilterViaBot() Filter
- func FilterVideo() Filter
- func FilterVideoNote() Filter
- func FilterVoice() Filter
- func FilterWebAppData() Filter
- func Not(f Filter) Filter
- func Or(filters ...Filter) Filter
- func StateIn(group StateGroup) Filter
- func StateIs(states ...State) Filter
- type ForceReply
- type ForumTopic
- type ForumTopicClosed
- type ForumTopicCreated
- type ForumTopicEdited
- type ForumTopicReopened
- type ForwardMessageRequest
- type ForwardMessagesRequest
- type Game
- type GameHighScore
- type GeneralForumTopicHidden
- type GeneralForumTopicUnhidden
- type GetBusinessAccountGiftsRequest
- type GetBusinessAccountStarBalanceRequest
- type GetBusinessConnectionRequest
- type GetChatAdministratorsRequest
- type GetChatGiftsRequest
- type GetChatMemberCountRequest
- type GetChatMemberRequest
- type GetChatMenuButtonRequest
- type GetChatRequest
- type GetCustomEmojiStickersRequest
- type GetFileRequest
- type GetGameHighScoresRequest
- type GetManagedBotAccessSettingsRequest
- type GetManagedBotTokenRequest
- type GetMyCommandsRequest
- type GetMyDefaultAdministratorRightsRequest
- type GetMyDescriptionRequest
- type GetMyNameRequest
- type GetMyShortDescriptionRequest
- type GetStarTransactionsRequest
- type GetStickerSetRequest
- type GetUpdatesRequest
- type GetUserChatBoostsRequest
- type GetUserGiftsRequest
- type GetUserPersonalChatMessagesRequest
- type GetUserProfileAudiosRequest
- type GetUserProfilePhotosRequest
- type Gift
- type GiftBackground
- type GiftInfo
- type GiftPremiumSubscriptionRequest
- type Gifts
- type Giveaway
- type GiveawayCompleted
- type GiveawayCreated
- type GiveawayWinners
- type HandlerFunc
- type HealthGate
- type HealthMonitor
- func (hm *HealthMonitor) GetStatus() HealthStatus
- func (hm *HealthMonitor) HealthCheckHandler() http.HandlerFunc
- func (hm *HealthMonitor) IncrementDispatched(kind string)
- func (hm *HealthMonitor) IncrementMatched(kind string)
- func (hm *HealthMonitor) IncrementUnmatched(kind string)
- func (hm *HealthMonitor) RecordError(err error)
- func (hm *HealthMonitor) StartHealthServer(ctx context.Context, addr string, gate ...HealthGate) error
- type HealthStatus
- type HideGeneralForumTopicRequest
- type I18n
- func (t *I18n) Add(locale string, messages map[string]string) *I18n
- func (t *I18n) AddJSON(locale string, data []byte) error
- func (t *I18n) DefaultLocale() string
- func (t *I18n) SetPluralRule(locale string, rule PluralRule) *I18n
- func (t *I18n) Translate(locale, key string, args ...any) string
- func (t *I18n) TranslateN(locale, key string, n int, args ...any) string
- type InaccessibleMessage
- type InlineKeyboard
- func (kb *InlineKeyboard) Add(buttons ...InlineKeyboardButton) *InlineKeyboard
- func (kb *InlineKeyboard) Adjust(sizes ...int) *InlineKeyboard
- func (kb *InlineKeyboard) Build() *InlineKeyboardMarkup
- func (kb *InlineKeyboard) Insert(button InlineKeyboardButton) *InlineKeyboard
- func (kb *InlineKeyboard) Row(buttons ...InlineKeyboardButton) *InlineKeyboard
- type InlineKeyboardButton
- func NewInlineButton(text, callbackData string) InlineKeyboardButton
- func NewInlineButtonSwitchInline(text, query string) InlineKeyboardButton
- func NewInlineButtonSwitchInlineCurrent(text, query string) InlineKeyboardButton
- func NewInlineButtonURL(text, url string) InlineKeyboardButton
- func NewInlineButtonWebApp(text, webAppURL string) InlineKeyboardButton
- type InlineKeyboardMarkup
- type InlineQuery
- type InlineQueryResult
- type InlineQueryResultArticle
- type InlineQueryResultAudio
- type InlineQueryResultCachedAudio
- type InlineQueryResultCachedDocument
- type InlineQueryResultCachedGif
- type InlineQueryResultCachedMpeg4Gif
- type InlineQueryResultCachedPhoto
- type InlineQueryResultCachedSticker
- type InlineQueryResultCachedVideo
- type InlineQueryResultCachedVoice
- type InlineQueryResultContact
- type InlineQueryResultDocument
- type InlineQueryResultGame
- type InlineQueryResultGif
- type InlineQueryResultLocation
- type InlineQueryResultMpeg4Gif
- type InlineQueryResultPhoto
- type InlineQueryResultVenue
- type InlineQueryResultVideo
- type InlineQueryResultVoice
- type InlineQueryResultsButton
- type InputChecklist
- type InputChecklistTask
- type InputContactMessageContent
- type InputFile
- type InputInvoiceMessageContent
- type InputLocationMessageContent
- type InputMedia
- type InputMediaAnimation
- type InputMediaAudio
- type InputMediaDocument
- type InputMediaLink
- type InputMediaLivePhoto
- type InputMediaLocation
- type InputMediaPhoto
- type InputMediaSticker
- type InputMediaVenue
- type InputMediaVideo
- type InputMessageContent
- type InputPaidMedia
- type InputPaidMediaLivePhoto
- type InputPaidMediaPhoto
- type InputPaidMediaVideo
- type InputPollMedia
- type InputPollOption
- type InputPollOptionMedia
- type InputProfilePhoto
- type InputProfilePhotoAnimated
- type InputProfilePhotoStatic
- type InputRichMessage
- type InputRichMessageContent
- type InputSticker
- type InputStoryContent
- type InputStoryContentPhoto
- type InputStoryContentVideo
- type InputTextMessageContent
- type InputVenueMessageContent
- type Invoice
- type KeyboardButton
- func NewKeyboardButton(text string) KeyboardButton
- func NewKeyboardButtonContact(text string) KeyboardButton
- func NewKeyboardButtonLocation(text string) KeyboardButton
- func NewKeyboardButtonPoll(text string, pollType string) KeyboardButton
- func NewKeyboardButtonWebApp(text, webAppURL string) KeyboardButton
- type KeyboardButtonPollType
- type KeyboardButtonRequestChat
- type KeyboardButtonRequestManagedBot
- type KeyboardButtonRequestUsers
- type LabeledPrice
- type LeaveChatRequest
- type LifecycleFunc
- type Link
- type LinkPreviewOptions
- type LivePhoto
- type Location
- type LocationAddress
- type LoginURL
- type LoginWidgetData
- type ManagedBotCreated
- type ManagedBotUpdated
- type MaskPosition
- type MaybeInaccessibleMessage
- type MediaGroup
- func (g *MediaGroup) Add(item InputMedia) *MediaGroup
- func (g *MediaGroup) Audio(media InputFile, caption ...string) *MediaGroup
- func (g *MediaGroup) Build() ([]InputMedia, error)
- func (g *MediaGroup) Document(media InputFile, caption ...string) *MediaGroup
- func (g *MediaGroup) LivePhoto(video, photo InputFile, caption ...string) *MediaGroup
- func (g *MediaGroup) Photo(media InputFile, caption ...string) *MediaGroup
- func (g *MediaGroup) Send(c *Ctx) ([]Message, error)
- func (g *MediaGroup) Video(media InputFile, caption ...string) *MediaGroup
- type MemoryStorage
- func (s *MemoryStorage) Clear(_ context.Context, key StorageKey) error
- func (s *MemoryStorage) Close()
- func (s *MemoryStorage) GetData(_ context.Context, key StorageKey) (map[string]any, error)
- func (s *MemoryStorage) GetState(_ context.Context, key StorageKey) (State, error)
- func (s *MemoryStorage) SetData(_ context.Context, key StorageKey, data map[string]any) error
- func (s *MemoryStorage) SetState(_ context.Context, key StorageKey, state State) error
- func (s *MemoryStorage) UpdateData(_ context.Context, key StorageKey, partial map[string]any) (map[string]any, error)
- type MenuButton
- type MenuButtonCommands
- type MenuButtonDefault
- type MenuButtonWebApp
- type Message
- func (e *Message) Answer(text string, options ...*SendMessageOptions) (*Message, error)
- func (e *Message) ChatID() int64
- func (e *Message) Command() *CommandObject
- func (e *Message) Delete() error
- func (e *Message) EditCaption(caption string, options ...*EditCaptionOptions) (*Message, error)
- func (e *Message) EditReplyMarkup(markup *InlineKeyboardMarkup) (*Message, error)
- func (e *Message) EditText(text string, options ...*EditMessageOptions) (*Message, error)
- func (m *Message) EntityText(e Entity) string
- func (e *Message) FSM() *FSMContext
- func (e *Message) FromID() int64
- func (e *Message) IsInaccessible() bool
- func (e *Message) Reply(text string, options ...*SendMessageOptions) (*Message, error)
- func (e *Message) SendChatAction(action string) error
- func (v *Message) UnmarshalJSON(data []byte) error
- type MessageAutoDeleteTimerChanged
- type MessageEntity
- type MessageID
- type MessageOrigin
- type MessageOriginChannel
- type MessageOriginChat
- type MessageOriginHiddenUser
- type MessageOriginUser
- type MessageReactionCountUpdated
- type MessageReactionUpdated
- type MiddlewareFunc
- func CallbackAnswerMiddleware() MiddlewareFunc
- func ChatActionMiddleware() MiddlewareFunc
- func I18nMiddleware(t Translator) MiddlewareFunc
- func LoggingMiddleware(logger *slog.Logger) MiddlewareFunc
- func RateLimitMiddleware(rl *RateLimiter, onLimited func(c *Ctx) error) MiddlewareFunc
- func RateLimitMiddlewareBySender(rl *RateLimiter, onLimited func(c *Ctx) error) MiddlewareFunc
- type Node
- func Blockquote(parts ...any) Node
- func Bold(parts ...any) Node
- func Code(text string) Node
- func CustomEmoji(text, customEmojiID string) Node
- func ExpandableBlockquote(parts ...any) Node
- func Italic(parts ...any) Node
- func Mention(text string, user *User) Node
- func Pre(text, language string) Node
- func Spoiler(parts ...any) Node
- func Strikethrough(parts ...any) Node
- func Text(parts ...any) Node
- func TextLink(text, url string) Node
- func Underline(parts ...any) Node
- type Option
- func WithAllowedUpdates(kinds ...string) Option
- func WithAutoRetry(maxWait time.Duration) Option
- func WithBaseURL(url string) Option
- func WithDropPendingUpdates() Option
- func WithFSMKeyStrategy(s FSMKeyStrategy) Option
- func WithFSMStorage(storage FSMStorage) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithLogger(logger *slog.Logger) Option
- func WithPollTimeout(seconds int) Option
- func WithSenderIdentity() Option
- func WithUpdateBuffer(n int) Option
- func WithWorkers(n int) Option
- func WithoutGetMe() Option
- type OrderInfo
- type OuterMiddlewareFunc
- type OwnedGift
- type OwnedGiftRegular
- type OwnedGiftUnique
- type OwnedGifts
- type Pagination
- type PaidMedia
- type PaidMediaInfo
- type PaidMediaLivePhoto
- type PaidMediaPhoto
- type PaidMediaPreview
- type PaidMediaPurchased
- type PaidMediaVideo
- type PaidMessagePriceChanged
- type PassportData
- type PassportElementError
- type PassportElementErrorDataField
- type PassportElementErrorFile
- type PassportElementErrorFiles
- type PassportElementErrorFrontSide
- type PassportElementErrorReverseSide
- type PassportElementErrorSelfie
- type PassportElementErrorTranslationFile
- type PassportElementErrorTranslationFiles
- type PassportElementErrorUnspecified
- type PassportFile
- type PhotoSize
- type PinChatMessageRequest
- type PluralCategory
- type PluralRule
- type Poll
- type PollAnswer
- type PollMedia
- type PollOption
- type PollOptionAdded
- type PollOptionDeleted
- type PostStoryRequest
- type PreCheckoutQuery
- type PreparedInlineMessage
- type PreparedKeyboardButton
- type PromoteChatMemberRequest
- type ProximityAlertTriggered
- type RateLimiter
- type ReactionCount
- type ReactionType
- type ReactionTypeCustomEmoji
- type ReactionTypeEmoji
- type ReactionTypePaid
- type ReadBusinessMessageRequest
- type RefundStarPaymentRequest
- type RefundedPayment
- type RemoveBusinessAccountProfilePhotoRequest
- type RemoveChatVerificationRequest
- type RemoveUserVerificationRequest
- type ReopenForumTopicRequest
- type ReopenGeneralForumTopicRequest
- type ReplaceManagedBotTokenRequest
- type ReplaceStickerInSetRequest
- type ReplyKeyboard
- func (kb *ReplyKeyboard) Add(buttons ...KeyboardButton) *ReplyKeyboard
- func (kb *ReplyKeyboard) Adjust(sizes ...int) *ReplyKeyboard
- func (kb *ReplyKeyboard) Build() *ReplyKeyboardMarkup
- func (kb *ReplyKeyboard) Insert(button KeyboardButton) *ReplyKeyboard
- func (kb *ReplyKeyboard) OneTime(oneTime bool) *ReplyKeyboard
- func (kb *ReplyKeyboard) Placeholder(text string) *ReplyKeyboard
- func (kb *ReplyKeyboard) Row(buttons ...KeyboardButton) *ReplyKeyboard
- func (kb *ReplyKeyboard) Selective(selective bool) *ReplyKeyboard
- type ReplyKeyboardMarkup
- type ReplyKeyboardRemove
- type ReplyMarkup
- type ReplyParameters
- type RepostStoryRequest
- type ResponseParameters
- type RestrictChatMemberRequest
- type RevenueWithdrawalState
- type RevenueWithdrawalStateFailed
- type RevenueWithdrawalStatePending
- type RevenueWithdrawalStateSucceeded
- type RevokeChatInviteLinkRequest
- type RichBlock
- func RichAnchorBlock(name string) RichBlock
- func RichBlockquote(credit RichText, blocks ...RichBlock) RichBlock
- func RichDetails(open bool, summary RichText, blocks ...RichBlock) RichBlock
- func RichDivider() RichBlock
- func RichFooter(spans ...RichText) RichBlock
- func RichHeading(size int, spans ...RichText) RichBlock
- func RichList(items ...RichBlockListItem) RichBlock
- func RichMap(lat, long float64, zoom int) RichBlock
- func RichMathBlock(latex string) RichBlock
- func RichParagraph(spans ...RichText) RichBlock
- func RichPreformatted(language string, spans ...RichText) RichBlock
- func RichPullquote(credit RichText, spans ...RichText) RichBlock
- func RichTable(bordered, striped bool, caption RichText, rows ...[]RichBlockTableCell) RichBlock
- func RichThinking(spans ...RichText) RichBlock
- type RichBlockAnchor
- type RichBlockAnimation
- type RichBlockAudio
- type RichBlockAuthoredMedia
- type RichBlockBlockQuotation
- type RichBlockCaption
- type RichBlockCollage
- type RichBlockDetails
- type RichBlockDivider
- type RichBlockFooter
- type RichBlockList
- type RichBlockListItem
- type RichBlockMap
- type RichBlockMathematicalExpression
- type RichBlockParagraph
- type RichBlockPhoto
- type RichBlockPreformatted
- type RichBlockPullQuotation
- type RichBlockSectionHeading
- type RichBlockSlideshow
- type RichBlockTable
- type RichBlockTableCell
- type RichBlockThinking
- type RichBlockVideo
- type RichBlockVoiceNote
- type RichMessage
- type RichPlainText
- type RichText
- func RichAnchorLink(name string, spans ...RichText) RichText
- func RichAnchorPoint(name string) RichText
- func RichBold(spans ...RichText) RichText
- func RichCode(spans ...RichText) RichText
- func RichInlineMath(latex string) RichText
- func RichItalic(spans ...RichText) RichText
- func RichLink(url string, spans ...RichText) RichText
- func RichPlain(s string) RichText
- func RichSpoiler(spans ...RichText) RichText
- func RichStrikethrough(spans ...RichText) RichText
- func RichUnderline(spans ...RichText) RichText
- func RichUserMention(user *User, spans ...RichText) RichText
- type RichTextAnchor
- type RichTextAnchorLink
- type RichTextBankCardNumber
- type RichTextBold
- type RichTextBotCommand
- type RichTextCashtag
- type RichTextCode
- type RichTextCustomEmoji
- type RichTextDateTime
- type RichTextEmailAddress
- type RichTextHashtag
- type RichTextItalic
- type RichTextMarked
- type RichTextMathematicalExpression
- type RichTextMention
- type RichTextPhoneNumber
- type RichTextReference
- type RichTextReferenceLink
- type RichTextSequence
- type RichTextSpoiler
- type RichTextStrikethrough
- type RichTextSubscript
- type RichTextSuperscript
- type RichTextTextMention
- type RichTextURL
- type RichTextUnderline
- type Router
- func (r *Router) BusinessConnection(filters ...Filter) *registration
- func (r *Router) BusinessMessage(filters ...Filter) *registration
- func (r *Router) CallbackQuery(filters ...Filter) *registration
- func (r *Router) ChannelPost(filters ...Filter) *registration
- func (r *Router) ChatBoost(filters ...Filter) *registration
- func (r *Router) ChatJoinRequest(filters ...Filter) *registration
- func (r *Router) ChatMember(filters ...Filter) *registration
- func (r *Router) ChosenInlineResult(filters ...Filter) *registration
- func (r *Router) DeletedBusinessMessages(filters ...Filter) *registration
- func (r *Router) EditedBusinessMessage(filters ...Filter) *registration
- func (r *Router) EditedChannelPost(filters ...Filter) *registration
- func (r *Router) EditedMessage(filters ...Filter) *registration
- func (r *Router) GuestMessage(filters ...Filter) *registration
- func (r *Router) Include(sub *Router)
- func (r *Router) InlineQuery(filters ...Filter) *registration
- func (r *Router) ManagedBot(filters ...Filter) *registration
- func (r *Router) Message(filters ...Filter) *registration
- func (r *Router) MessageReaction(filters ...Filter) *registration
- func (r *Router) MessageReactionCount(filters ...Filter) *registration
- func (r *Router) MyChatMember(filters ...Filter) *registration
- func (r *Router) OnError(h ErrorHandlerFunc)
- func (r *Router) Poll(filters ...Filter) *registration
- func (r *Router) PollAnswer(filters ...Filter) *registration
- func (r *Router) PreCheckoutQuery(filters ...Filter) *registration
- func (r *Router) PurchasedPaidMedia(filters ...Filter) *registration
- func (r *Router) RemovedChatBoost(filters ...Filter) *registration
- func (r *Router) ShippingQuery(filters ...Filter) *registration
- func (r *Router) Update(filters ...Filter) *registration
- func (r *Router) Use(mw MiddlewareFunc)
- func (r *Router) UseOuter(mw OuterMiddlewareFunc)
- func (r *Router) UsedUpdateKinds() []string
- type SMO
- type SavePreparedInlineMessageRequest
- type SavePreparedKeyboardButtonRequest
- type SendAnimationRequest
- type SendAudioRequest
- type SendChatActionRequest
- type SendChatJoinRequestWebAppRequest
- type SendChecklistRequest
- type SendContactRequest
- type SendDiceRequest
- type SendDocumentRequest
- type SendGameRequest
- type SendGiftRequest
- type SendInvoiceRequest
- type SendLivePhotoRequest
- type SendLocationRequest
- type SendMediaGroupRequest
- type SendMessageDraftRequest
- type SendMessageOptions
- type SendMessageRequest
- type SendPaidMediaRequest
- type SendPhotoRequest
- type SendPollRequest
- type SendRichMessageDraftRequest
- type SendRichMessageRequest
- type SendStickerRequest
- type SendVenueRequest
- type SendVideoNoteRequest
- type SendVideoRequest
- type SendVoiceRequest
- type Sender
- type SentGuestMessage
- type SentWebAppMessage
- type SetBusinessAccountBioRequest
- type SetBusinessAccountGiftSettingsRequest
- type SetBusinessAccountNameRequest
- type SetBusinessAccountProfilePhotoRequest
- type SetBusinessAccountUsernameRequest
- type SetChatAdministratorCustomTitleRequest
- type SetChatDescriptionRequest
- type SetChatMemberTagRequest
- type SetChatMenuButtonRequest
- type SetChatPermissionsRequest
- type SetChatPhotoRequest
- type SetChatStickerSetRequest
- type SetChatTitleRequest
- type SetCustomEmojiStickerSetThumbnailRequest
- type SetGameScoreRequest
- type SetManagedBotAccessSettingsRequest
- type SetMessageReactionRequest
- type SetMyCommandsRequest
- type SetMyDefaultAdministratorRightsRequest
- type SetMyDescriptionRequest
- type SetMyNameRequest
- type SetMyProfilePhotoRequest
- type SetMyShortDescriptionRequest
- type SetPassportDataErrorsRequest
- type SetStickerEmojiListRequest
- type SetStickerKeywordsRequest
- type SetStickerMaskPositionRequest
- type SetStickerPositionInSetRequest
- type SetStickerSetThumbnailRequest
- type SetStickerSetTitleRequest
- type SetUserEmojiStatusRequest
- type SetWebhookRequest
- type SharedUser
- type ShippingAddress
- type ShippingOption
- type ShippingQuery
- type StarAmount
- type StarTransaction
- type StarTransactions
- type State
- type StateGroup
- type StepOption
- type Sticker
- type StickerSet
- type StopMessageLiveLocationRequest
- type StopPollRequest
- type StorageKey
- type Story
- type StoryArea
- type StoryAreaPosition
- type StoryAreaType
- type StoryAreaTypeLink
- type StoryAreaTypeLocation
- type StoryAreaTypeSuggestedReaction
- type StoryAreaTypeUniqueGift
- type StoryAreaTypeWeather
- type SuccessfulPayment
- type SuggestedPostApprovalFailed
- type SuggestedPostApproved
- type SuggestedPostDeclined
- type SuggestedPostInfo
- type SuggestedPostPaid
- type SuggestedPostParameters
- type SuggestedPostPrice
- type SuggestedPostRefunded
- type SwitchInlineQueryChosenChat
- type TelegramBot
- func (b *TelegramBot) AddStickerToSet(ctx context.Context, req *AddStickerToSetRequest) (bool, error)
- func (b *TelegramBot) AnswerCallbackQuery(ctx context.Context, req *AnswerCallbackQueryRequest) (bool, error)
- func (b *TelegramBot) AnswerChatJoinRequestQuery(ctx context.Context, req *AnswerChatJoinRequestQueryRequest) (bool, error)
- func (b *TelegramBot) AnswerGuestQuery(ctx context.Context, req *AnswerGuestQueryRequest) (*SentGuestMessage, error)
- func (b *TelegramBot) AnswerInlineQuery(ctx context.Context, req *AnswerInlineQueryRequest) (bool, error)
- func (b *TelegramBot) AnswerPreCheckoutQuery(ctx context.Context, req *AnswerPreCheckoutQueryRequest) (bool, error)
- func (b *TelegramBot) AnswerShippingQuery(ctx context.Context, req *AnswerShippingQueryRequest) (bool, error)
- func (b *TelegramBot) AnswerWebAppQuery(ctx context.Context, req *AnswerWebAppQueryRequest) (*SentWebAppMessage, error)
- func (b *TelegramBot) ApproveChatJoinRequest(ctx context.Context, req *ApproveChatJoinRequestRequest) (bool, error)
- func (b *TelegramBot) ApproveSuggestedPost(ctx context.Context, req *ApproveSuggestedPostRequest) (bool, error)
- func (b *TelegramBot) BanChatMember(ctx context.Context, req *BanChatMemberRequest) (bool, error)
- func (b *TelegramBot) BanChatSenderChat(ctx context.Context, req *BanChatSenderChatRequest) (bool, error)
- func (b *TelegramBot) Close(ctx context.Context) (bool, error)
- func (b *TelegramBot) CloseForumTopic(ctx context.Context, req *CloseForumTopicRequest) (bool, error)
- func (b *TelegramBot) CloseGeneralForumTopic(ctx context.Context, req *CloseGeneralForumTopicRequest) (bool, error)
- func (b *TelegramBot) ConvertGiftToStars(ctx context.Context, req *ConvertGiftToStarsRequest) (bool, error)
- func (b *TelegramBot) CopyMessage(ctx context.Context, req *CopyMessageRequest) (*MessageID, error)
- func (b *TelegramBot) CopyMessages(ctx context.Context, req *CopyMessagesRequest) ([]MessageID, error)
- func (b *TelegramBot) CreateChatInviteLink(ctx context.Context, req *CreateChatInviteLinkRequest) (*ChatInviteLink, error)
- func (b *TelegramBot) CreateChatSubscriptionInviteLink(ctx context.Context, req *CreateChatSubscriptionInviteLinkRequest) (*ChatInviteLink, error)
- func (b *TelegramBot) CreateForumTopic(ctx context.Context, req *CreateForumTopicRequest) (*ForumTopic, error)
- func (b *TelegramBot) CreateInvoiceLink(ctx context.Context, req *CreateInvoiceLinkRequest) (string, error)
- func (b *TelegramBot) CreateNewStickerSet(ctx context.Context, req *CreateNewStickerSetRequest) (bool, error)
- func (b *TelegramBot) CreateStartGroupLink(payload string, encode bool) (string, error)
- func (b *TelegramBot) CreateStartLink(payload string, encode bool) (string, error)
- func (b *TelegramBot) DeclineChatJoinRequest(ctx context.Context, req *DeclineChatJoinRequestRequest) (bool, error)
- func (b *TelegramBot) DeclineSuggestedPost(ctx context.Context, req *DeclineSuggestedPostRequest) (bool, error)
- func (b *TelegramBot) DeleteAllMessageReactions(ctx context.Context, req *DeleteAllMessageReactionsRequest) (bool, error)
- func (b *TelegramBot) DeleteBusinessMessages(ctx context.Context, req *DeleteBusinessMessagesRequest) (bool, error)
- func (b *TelegramBot) DeleteChatPhoto(ctx context.Context, req *DeleteChatPhotoRequest) (bool, error)
- func (b *TelegramBot) DeleteChatStickerSet(ctx context.Context, req *DeleteChatStickerSetRequest) (bool, error)
- func (b *TelegramBot) DeleteForumTopic(ctx context.Context, req *DeleteForumTopicRequest) (bool, error)
- func (b *TelegramBot) DeleteMessage(ctx context.Context, req *DeleteMessageRequest) (bool, error)
- func (b *TelegramBot) DeleteMessageReaction(ctx context.Context, req *DeleteMessageReactionRequest) (bool, error)
- func (b *TelegramBot) DeleteMessages(ctx context.Context, req *DeleteMessagesRequest) (bool, error)
- func (b *TelegramBot) DeleteMyCommands(ctx context.Context, req *DeleteMyCommandsRequest) (bool, error)
- func (b *TelegramBot) DeleteStickerFromSet(ctx context.Context, req *DeleteStickerFromSetRequest) (bool, error)
- func (b *TelegramBot) DeleteStickerSet(ctx context.Context, req *DeleteStickerSetRequest) (bool, error)
- func (b *TelegramBot) DeleteStory(ctx context.Context, req *DeleteStoryRequest) (bool, error)
- func (b *TelegramBot) DeleteWebhook(ctx context.Context, req *DeleteWebhookRequest) (bool, error)
- func (b *TelegramBot) Dispatch(r *Router)
- func (b *TelegramBot) EditChatInviteLink(ctx context.Context, req *EditChatInviteLinkRequest) (*ChatInviteLink, error)
- func (b *TelegramBot) EditChatSubscriptionInviteLink(ctx context.Context, req *EditChatSubscriptionInviteLinkRequest) (*ChatInviteLink, error)
- func (b *TelegramBot) EditForumTopic(ctx context.Context, req *EditForumTopicRequest) (bool, error)
- func (b *TelegramBot) EditGeneralForumTopic(ctx context.Context, req *EditGeneralForumTopicRequest) (bool, error)
- func (b *TelegramBot) EditMessageCaption(ctx context.Context, req *EditMessageCaptionRequest) (*Message, error)
- func (b *TelegramBot) EditMessageChecklist(ctx context.Context, req *EditMessageChecklistRequest) (*Message, error)
- func (b *TelegramBot) EditMessageLiveLocation(ctx context.Context, req *EditMessageLiveLocationRequest) (*Message, error)
- func (b *TelegramBot) EditMessageMedia(ctx context.Context, req *EditMessageMediaRequest) (*Message, error)
- func (b *TelegramBot) EditMessageReplyMarkup(ctx context.Context, req *EditMessageReplyMarkupRequest) (*Message, error)
- func (b *TelegramBot) EditMessageText(ctx context.Context, req *EditMessageTextRequest) (*Message, error)
- func (b *TelegramBot) EditStory(ctx context.Context, req *EditStoryRequest) (*Story, error)
- func (b *TelegramBot) EditUserStarSubscription(ctx context.Context, req *EditUserStarSubscriptionRequest) (bool, error)
- func (b *TelegramBot) ExportChatInviteLink(ctx context.Context, req *ExportChatInviteLinkRequest) (string, error)
- func (b *TelegramBot) ForwardMessage(ctx context.Context, req *ForwardMessageRequest) (*Message, error)
- func (b *TelegramBot) ForwardMessages(ctx context.Context, req *ForwardMessagesRequest) ([]MessageID, error)
- func (b *TelegramBot) GetAvailableGifts(ctx context.Context) (*Gifts, error)
- func (b *TelegramBot) GetBusinessAccountGifts(ctx context.Context, req *GetBusinessAccountGiftsRequest) (*OwnedGifts, error)
- func (b *TelegramBot) GetBusinessAccountStarBalance(ctx context.Context, req *GetBusinessAccountStarBalanceRequest) (*StarAmount, error)
- func (b *TelegramBot) GetBusinessConnection(ctx context.Context, req *GetBusinessConnectionRequest) (*BusinessConnection, error)
- func (b *TelegramBot) GetChat(ctx context.Context, req *GetChatRequest) (*ChatFullInfo, error)
- func (b *TelegramBot) GetChatAdministrators(ctx context.Context, req *GetChatAdministratorsRequest) ([]ChatMember, error)
- func (b *TelegramBot) GetChatGifts(ctx context.Context, req *GetChatGiftsRequest) (*OwnedGifts, error)
- func (b *TelegramBot) GetChatMember(ctx context.Context, req *GetChatMemberRequest) (ChatMember, error)
- func (b *TelegramBot) GetChatMemberCount(ctx context.Context, req *GetChatMemberCountRequest) (int64, error)
- func (b *TelegramBot) GetChatMenuButton(ctx context.Context, req *GetChatMenuButtonRequest) (MenuButton, error)
- func (b *TelegramBot) GetCustomEmojiStickers(ctx context.Context, req *GetCustomEmojiStickersRequest) ([]Sticker, error)
- func (b *TelegramBot) GetFile(ctx context.Context, req *GetFileRequest) (*File, error)
- func (b *TelegramBot) GetForumTopicIconStickers(ctx context.Context) ([]Sticker, error)
- func (b *TelegramBot) GetGameHighScores(ctx context.Context, req *GetGameHighScoresRequest) ([]GameHighScore, error)
- func (b *TelegramBot) GetHealthMonitor() *HealthMonitor
- func (b *TelegramBot) GetManagedBotAccessSettings(ctx context.Context, req *GetManagedBotAccessSettingsRequest) (*BotAccessSettings, error)
- func (b *TelegramBot) GetManagedBotToken(ctx context.Context, req *GetManagedBotTokenRequest) (string, error)
- func (b *TelegramBot) GetMe(ctx context.Context) (*User, error)
- func (b *TelegramBot) GetMyCommands(ctx context.Context, req *GetMyCommandsRequest) ([]BotCommand, error)
- func (b *TelegramBot) GetMyDefaultAdministratorRights(ctx context.Context, req *GetMyDefaultAdministratorRightsRequest) (*ChatAdministratorRights, error)
- func (b *TelegramBot) GetMyDescription(ctx context.Context, req *GetMyDescriptionRequest) (*BotDescription, error)
- func (b *TelegramBot) GetMyName(ctx context.Context, req *GetMyNameRequest) (*BotName, error)
- func (b *TelegramBot) GetMyShortDescription(ctx context.Context, req *GetMyShortDescriptionRequest) (*BotShortDescription, error)
- func (b *TelegramBot) GetMyStarBalance(ctx context.Context) (*StarAmount, error)
- func (b *TelegramBot) GetStarTransactions(ctx context.Context, req *GetStarTransactionsRequest) (*StarTransactions, error)
- func (b *TelegramBot) GetStickerSet(ctx context.Context, req *GetStickerSetRequest) (*StickerSet, error)
- func (b *TelegramBot) GetUpdates(ctx context.Context, req *GetUpdatesRequest) ([]Update, error)
- func (b *TelegramBot) GetUserChatBoosts(ctx context.Context, req *GetUserChatBoostsRequest) (*UserChatBoosts, error)
- func (b *TelegramBot) GetUserGifts(ctx context.Context, req *GetUserGiftsRequest) (*OwnedGifts, error)
- func (b *TelegramBot) GetUserPersonalChatMessages(ctx context.Context, req *GetUserPersonalChatMessagesRequest) ([]Message, error)
- func (b *TelegramBot) GetUserProfileAudios(ctx context.Context, req *GetUserProfileAudiosRequest) (*UserProfileAudios, error)
- func (b *TelegramBot) GetUserProfilePhotos(ctx context.Context, req *GetUserProfilePhotosRequest) (*UserProfilePhotos, error)
- func (b *TelegramBot) GetWebhookInfo(ctx context.Context) (*WebhookInfo, error)
- func (b *TelegramBot) GiftPremiumSubscription(ctx context.Context, req *GiftPremiumSubscriptionRequest) (bool, error)
- func (b *TelegramBot) HandleUpdate(ctx context.Context, u *Update)
- func (b *TelegramBot) Handler(cfg WebhookConfig) http.Handler
- func (b *TelegramBot) HideGeneralForumTopic(ctx context.Context, req *HideGeneralForumTopicRequest) (bool, error)
- func (b *TelegramBot) LeaveChat(ctx context.Context, req *LeaveChatRequest) (bool, error)
- func (b *TelegramBot) LoadMe(ctx context.Context) error
- func (b *TelegramBot) LogOut(ctx context.Context) (bool, error)
- func (b *TelegramBot) Me() *User
- func (b *TelegramBot) OnError(handler ErrorHandlerFunc)
- func (b *TelegramBot) OnShutdown(f LifecycleFunc)
- func (b *TelegramBot) OnStartup(f LifecycleFunc)
- func (b *TelegramBot) PinChatMessage(ctx context.Context, req *PinChatMessageRequest) (bool, error)
- func (b *TelegramBot) PostStory(ctx context.Context, req *PostStoryRequest) (*Story, error)
- func (b *TelegramBot) PromoteChatMember(ctx context.Context, req *PromoteChatMemberRequest) (bool, error)
- func (b *TelegramBot) ReadBusinessMessage(ctx context.Context, req *ReadBusinessMessageRequest) (bool, error)
- func (b *TelegramBot) RefundStarPayment(ctx context.Context, req *RefundStarPaymentRequest) (bool, error)
- func (b *TelegramBot) RefundStars(ctx context.Context, userID int64, telegramPaymentChargeID string) error
- func (b *TelegramBot) RemoveBusinessAccountProfilePhoto(ctx context.Context, req *RemoveBusinessAccountProfilePhotoRequest) (bool, error)
- func (b *TelegramBot) RemoveChatVerification(ctx context.Context, req *RemoveChatVerificationRequest) (bool, error)
- func (b *TelegramBot) RemoveMyProfilePhoto(ctx context.Context) (bool, error)
- func (b *TelegramBot) RemoveUserVerification(ctx context.Context, req *RemoveUserVerificationRequest) (bool, error)
- func (b *TelegramBot) ReopenForumTopic(ctx context.Context, req *ReopenForumTopicRequest) (bool, error)
- func (b *TelegramBot) ReopenGeneralForumTopic(ctx context.Context, req *ReopenGeneralForumTopicRequest) (bool, error)
- func (b *TelegramBot) ReplaceManagedBotToken(ctx context.Context, req *ReplaceManagedBotTokenRequest) (string, error)
- func (b *TelegramBot) ReplaceStickerInSet(ctx context.Context, req *ReplaceStickerInSetRequest) (bool, error)
- func (b *TelegramBot) RepostStory(ctx context.Context, req *RepostStoryRequest) (*Story, error)
- func (b *TelegramBot) RestrictChatMember(ctx context.Context, req *RestrictChatMemberRequest) (bool, error)
- func (b *TelegramBot) RevokeChatInviteLink(ctx context.Context, req *RevokeChatInviteLinkRequest) (*ChatInviteLink, error)
- func (b *TelegramBot) Run(ctx context.Context) error
- func (b *TelegramBot) RunWebhook(ctx context.Context, cfg WebhookConfig) error
- func (b *TelegramBot) SavePreparedInlineMessage(ctx context.Context, req *SavePreparedInlineMessageRequest) (*PreparedInlineMessage, error)
- func (b *TelegramBot) SavePreparedKeyboardButton(ctx context.Context, req *SavePreparedKeyboardButtonRequest) (*PreparedKeyboardButton, error)
- func (b *TelegramBot) SendAnimation(ctx context.Context, req *SendAnimationRequest) (*Message, error)
- func (b *TelegramBot) SendAudio(ctx context.Context, req *SendAudioRequest) (*Message, error)
- func (b *TelegramBot) SendChatAction(ctx context.Context, req *SendChatActionRequest) (bool, error)
- func (b *TelegramBot) SendChatJoinRequestWebApp(ctx context.Context, req *SendChatJoinRequestWebAppRequest) (bool, error)
- func (b *TelegramBot) SendChecklist(ctx context.Context, req *SendChecklistRequest) (*Message, error)
- func (b *TelegramBot) SendContact(ctx context.Context, req *SendContactRequest) (*Message, error)
- func (b *TelegramBot) SendDice(ctx context.Context, req *SendDiceRequest) (*Message, error)
- func (b *TelegramBot) SendDocument(ctx context.Context, req *SendDocumentRequest) (*Message, error)
- func (b *TelegramBot) SendGame(ctx context.Context, req *SendGameRequest) (*Message, error)
- func (b *TelegramBot) SendGift(ctx context.Context, req *SendGiftRequest) (bool, error)
- func (b *TelegramBot) SendInvoice(ctx context.Context, req *SendInvoiceRequest) (*Message, error)
- func (b *TelegramBot) SendLivePhoto(ctx context.Context, req *SendLivePhotoRequest) (*Message, error)
- func (b *TelegramBot) SendLocation(ctx context.Context, req *SendLocationRequest) (*Message, error)
- func (b *TelegramBot) SendMediaGroup(ctx context.Context, req *SendMediaGroupRequest) ([]Message, error)
- func (b *TelegramBot) SendMessage(ctx context.Context, req *SendMessageRequest) (*Message, error)
- func (b *TelegramBot) SendMessageDraft(ctx context.Context, req *SendMessageDraftRequest) (bool, error)
- func (b *TelegramBot) SendPaidMedia(ctx context.Context, req *SendPaidMediaRequest) (*Message, error)
- func (b *TelegramBot) SendPhoto(ctx context.Context, req *SendPhotoRequest) (*Message, error)
- func (b *TelegramBot) SendPoll(ctx context.Context, req *SendPollRequest) (*Message, error)
- func (b *TelegramBot) SendRichMessage(ctx context.Context, req *SendRichMessageRequest) (*Message, error)
- func (b *TelegramBot) SendRichMessageDraft(ctx context.Context, req *SendRichMessageDraftRequest) (bool, error)
- func (b *TelegramBot) SendSticker(ctx context.Context, req *SendStickerRequest) (*Message, error)
- func (b *TelegramBot) SendVenue(ctx context.Context, req *SendVenueRequest) (*Message, error)
- func (b *TelegramBot) SendVideo(ctx context.Context, req *SendVideoRequest) (*Message, error)
- func (b *TelegramBot) SendVideoNote(ctx context.Context, req *SendVideoNoteRequest) (*Message, error)
- func (b *TelegramBot) SendVoice(ctx context.Context, req *SendVoiceRequest) (*Message, error)
- func (b *TelegramBot) SetBotCommands(commands []BotCommand) error
- func (b *TelegramBot) SetBusinessAccountBio(ctx context.Context, req *SetBusinessAccountBioRequest) (bool, error)
- func (b *TelegramBot) SetBusinessAccountGiftSettings(ctx context.Context, req *SetBusinessAccountGiftSettingsRequest) (bool, error)
- func (b *TelegramBot) SetBusinessAccountName(ctx context.Context, req *SetBusinessAccountNameRequest) (bool, error)
- func (b *TelegramBot) SetBusinessAccountProfilePhoto(ctx context.Context, req *SetBusinessAccountProfilePhotoRequest) (bool, error)
- func (b *TelegramBot) SetBusinessAccountUsername(ctx context.Context, req *SetBusinessAccountUsernameRequest) (bool, error)
- func (b *TelegramBot) SetChatAdministratorCustomTitle(ctx context.Context, req *SetChatAdministratorCustomTitleRequest) (bool, error)
- func (b *TelegramBot) SetChatDescription(ctx context.Context, req *SetChatDescriptionRequest) (bool, error)
- func (b *TelegramBot) SetChatMemberTag(ctx context.Context, req *SetChatMemberTagRequest) (bool, error)
- func (b *TelegramBot) SetChatMenuButton(ctx context.Context, req *SetChatMenuButtonRequest) (bool, error)
- func (b *TelegramBot) SetChatPermissions(ctx context.Context, req *SetChatPermissionsRequest) (bool, error)
- func (b *TelegramBot) SetChatPhoto(ctx context.Context, req *SetChatPhotoRequest) (bool, error)
- func (b *TelegramBot) SetChatStickerSet(ctx context.Context, req *SetChatStickerSetRequest) (bool, error)
- func (b *TelegramBot) SetChatTitle(ctx context.Context, req *SetChatTitleRequest) (bool, error)
- func (b *TelegramBot) SetCustomEmojiStickerSetThumbnail(ctx context.Context, req *SetCustomEmojiStickerSetThumbnailRequest) (bool, error)
- func (b *TelegramBot) SetFSMStorage(storage FSMStorage)
- func (b *TelegramBot) SetGameScore(ctx context.Context, req *SetGameScoreRequest) (*Message, error)
- func (b *TelegramBot) SetManagedBotAccessSettings(ctx context.Context, req *SetManagedBotAccessSettingsRequest) (bool, error)
- func (b *TelegramBot) SetMessageReaction(ctx context.Context, req *SetMessageReactionRequest) (bool, error)
- func (b *TelegramBot) SetMyCommands(ctx context.Context, req *SetMyCommandsRequest) (bool, error)
- func (b *TelegramBot) SetMyDefaultAdministratorRights(ctx context.Context, req *SetMyDefaultAdministratorRightsRequest) (bool, error)
- func (b *TelegramBot) SetMyDescription(ctx context.Context, req *SetMyDescriptionRequest) (bool, error)
- func (b *TelegramBot) SetMyName(ctx context.Context, req *SetMyNameRequest) (bool, error)
- func (b *TelegramBot) SetMyProfilePhoto(ctx context.Context, req *SetMyProfilePhotoRequest) (bool, error)
- func (b *TelegramBot) SetMyShortDescription(ctx context.Context, req *SetMyShortDescriptionRequest) (bool, error)
- func (b *TelegramBot) SetPassportDataErrors(ctx context.Context, req *SetPassportDataErrorsRequest) (bool, error)
- func (b *TelegramBot) SetStickerEmojiList(ctx context.Context, req *SetStickerEmojiListRequest) (bool, error)
- func (b *TelegramBot) SetStickerKeywords(ctx context.Context, req *SetStickerKeywordsRequest) (bool, error)
- func (b *TelegramBot) SetStickerMaskPosition(ctx context.Context, req *SetStickerMaskPositionRequest) (bool, error)
- func (b *TelegramBot) SetStickerPositionInSet(ctx context.Context, req *SetStickerPositionInSetRequest) (bool, error)
- func (b *TelegramBot) SetStickerSetThumbnail(ctx context.Context, req *SetStickerSetThumbnailRequest) (bool, error)
- func (b *TelegramBot) SetStickerSetTitle(ctx context.Context, req *SetStickerSetTitleRequest) (bool, error)
- func (b *TelegramBot) SetUserEmojiStatus(ctx context.Context, req *SetUserEmojiStatusRequest) (bool, error)
- func (b *TelegramBot) SetWebhook(ctx context.Context, req *SetWebhookRequest) (bool, error)
- func (b *TelegramBot) StartHealthServer(ctx context.Context, addr string, gate ...HealthGate)
- func (b *TelegramBot) StartWorkers(ctx context.Context)
- func (b *TelegramBot) StopMessageLiveLocation(ctx context.Context, req *StopMessageLiveLocationRequest) (*Message, error)
- func (b *TelegramBot) StopPoll(ctx context.Context, req *StopPollRequest) (*Poll, error)
- func (b *TelegramBot) StopWorkers()
- func (b *TelegramBot) TransferBusinessAccountStars(ctx context.Context, req *TransferBusinessAccountStarsRequest) (bool, error)
- func (b *TelegramBot) TransferGift(ctx context.Context, req *TransferGiftRequest) (bool, error)
- func (b *TelegramBot) UnbanChatMember(ctx context.Context, req *UnbanChatMemberRequest) (bool, error)
- func (b *TelegramBot) UnbanChatSenderChat(ctx context.Context, req *UnbanChatSenderChatRequest) (bool, error)
- func (b *TelegramBot) UnhideGeneralForumTopic(ctx context.Context, req *UnhideGeneralForumTopicRequest) (bool, error)
- func (b *TelegramBot) UnpinAllChatMessages(ctx context.Context, req *UnpinAllChatMessagesRequest) (bool, error)
- func (b *TelegramBot) UnpinAllForumTopicMessages(ctx context.Context, req *UnpinAllForumTopicMessagesRequest) (bool, error)
- func (b *TelegramBot) UnpinAllGeneralForumTopicMessages(ctx context.Context, req *UnpinAllGeneralForumTopicMessagesRequest) (bool, error)
- func (b *TelegramBot) UnpinChatMessage(ctx context.Context, req *UnpinChatMessageRequest) (bool, error)
- func (b *TelegramBot) UpgradeGift(ctx context.Context, req *UpgradeGiftRequest) (bool, error)
- func (b *TelegramBot) UploadStickerFile(ctx context.Context, req *UploadStickerFileRequest) (*File, error)
- func (b *TelegramBot) VerifyChat(ctx context.Context, req *VerifyChatRequest) (bool, error)
- func (b *TelegramBot) VerifyUser(ctx context.Context, req *VerifyUserRequest) (bool, error)
- type TextChunk
- type TextQuote
- type TransactionPartner
- type TransactionPartnerAffiliateProgram
- type TransactionPartnerChat
- type TransactionPartnerFragment
- type TransactionPartnerOther
- type TransactionPartnerTelegramAds
- type TransactionPartnerTelegramApi
- type TransactionPartnerUser
- type TransferBusinessAccountStarsRequest
- type TransferGiftRequest
- type Translator
- type UnbanChatMemberRequest
- type UnbanChatSenderChatRequest
- type UnhideGeneralForumTopicRequest
- type UniqueGift
- type UniqueGiftBackdrop
- type UniqueGiftBackdropColors
- type UniqueGiftColors
- type UniqueGiftInfo
- type UniqueGiftModel
- type UniqueGiftSymbol
- type UnpinAllChatMessagesRequest
- type UnpinAllForumTopicMessagesRequest
- type UnpinAllGeneralForumTopicMessagesRequest
- type UnpinChatMessageRequest
- type Update
- type UpgradeGiftRequest
- type UploadStickerFileRequest
- type User
- type UserChatBoosts
- type UserProfileAudios
- type UserProfilePhotos
- type UserRating
- type UsersShared
- type ValidationError
- type Venue
- type VerifyChatRequest
- type VerifyUserRequest
- type Video
- type VideoChatEnded
- type VideoChatParticipantsInvited
- type VideoChatScheduled
- type VideoChatStarted
- type VideoNote
- type VideoQuality
- type Voice
- type WebAppChat
- type WebAppData
- type WebAppEnvironment
- type WebAppInfo
- type WebAppInitData
- type WebAppUser
- type WebhookConfig
- type WebhookInfo
- type WebhookReply
- type Wizard
- type WizardCtx
- type WizardOption
- type WizardStepFunc
- type WriteAccessAllowed
Constants ¶
const ( ChatTypePrivate = "private" ChatTypeGroup = "group" ChatTypeSupergroup = "supergroup" ChatTypeChannel = "channel" )
ChatType values for Chat.Type, scraped from Chat.type's docs description.
const ( EntityMention = "mention" EntityHashtag = "hashtag" EntityCashtag = "cashtag" EntityBotCommand = "bot_command" EntityURL = "url" EntityEmail = "email" EntityPhoneNumber = "phone_number" EntityBold = "bold" EntityItalic = "italic" EntityUnderline = "underline" EntityStrikethrough = "strikethrough" EntitySpoiler = "spoiler" EntityBlockquote = "blockquote" EntityExpandableBlockquote = "expandable_blockquote" EntityCode = "code" EntityPre = "pre" EntityTextLink = "text_link" EntityTextMention = "text_mention" EntityCustomEmoji = "custom_emoji" EntityDateTime = "date_time" )
MessageEntity.Type values, scraped from MessageEntity.type's docs description. Formatting-only entities (Bold, Italic, ...) are included even though FilterHasEntity's doc comment steers callers toward the content-bearing ones (Mention, Hashtag, URL, ...) instead.
const ( ButtonStyleDanger = "danger" ButtonStyleSuccess = "success" ButtonStylePrimary = "primary" )
ButtonStyle values for InlineKeyboardButton.Style / KeyboardButton.Style, scraped from InlineKeyboardButton.style's docs description (KeyboardButton's field carries the identical wording). If omitted, Telegram clients use an app-specific default style.
const ( ParseModeHTML = "HTML" ParseModeMarkdownV2 = "MarkdownV2" ParseModeMarkdown = "Markdown" )
Parse mode for message text/caption formatting, e.g. SendMessageOptions.ParseMode. Not enumerated anywhere scrapable in the Bot API docs (sendMessage's parse_mode param just links out to "formatting options"), so hand-curated here instead of scraped from scripts/api.json.
const ( DiceEmojiDice = "🎲" DiceEmojiDarts = "🎯" DiceEmojiBasketball = "🏀" DiceEmojiFootball = "⚽" DiceEmojiBowling = "🎳" DiceEmojiSlotMachine = "🎰" )
Emoji accepted by SendDiceRequest.Emoji, selecting the dice animation. The docs prose lists the emoji themselves but never names them, so the Go names here are hand-curated.
const ( ChatActionTyping = "typing" ChatActionUploadPhoto = "upload_photo" ChatActionRecordVideo = "record_video" ChatActionUploadVideo = "upload_video" ChatActionRecordVoice = "record_voice" ChatActionUploadVoice = "upload_voice" ChatActionUploadDocument = "upload_document" ChatActionChooseSticker = "choose_sticker" ChatActionFindLocation = "find_location" ChatActionRecordVideoNote = "record_video_note" ChatActionUploadVideoNote = "upload_video_note" )
Chat action accepted by SendChatActionRequest.Action and KeepChatAction. sendChatAction's docs prose lists these inline ("typing for text messages, upload_photo for photos, ...") without a scrapable delimiter, so hand-curated here.
const ( MinMediaGroupSize = 2 MaxMediaGroupSize = 10 )
Media-group (album) limits enforced by NewMediaGroup before any network round-trip.
const ( // MaxTextLength is the maximum length of a message text, in characters. MaxTextLength = 4096 // MaxCallbackDataLength is the maximum size of a callback button's data, // in bytes. MaxCallbackDataLength = 64 )
Telegram Bot API hard limits enforced before any network round-trip.
const FlagChatAction = "chat_action"
FlagChatAction is the registration flag key ChatActionMiddleware reads — pair it with WithFlags to keep a chat action alive for one specific handler:
r.Message(gg.FilterPhoto()).WithFlags(map[string]any{gg.FlagChatAction: gg.ChatActionUploadPhoto}).Handle(processPhoto)
const MaxStartPayloadLength = 64
MaxStartPayloadLength is Telegram's limit on a deep-link start payload (the part after ?start= / ?startgroup=), counted after encoding.
const StarsCurrency = "XTR"
StarsCurrency is the currency code for Telegram Stars payments.
const Version = "1.0.0"
Version is the release this build is working toward — a shipped guarantee only once matched by a pushed git tag; see the README's Versioning section.
Variables ¶
var ErrCallbackDataTampered = errors.New("golagram: callback data failed HMAC verification")
ErrCallbackDataTampered is returned by CallbackData.Unpack (and anything built on it — CallbackData.FromCtx, CallbackData.FilterWhere) when a CallbackData.WithHMAC-signed payload's tag doesn't match its content: either genuinely tampered with, or forged via a client that isn't the real Telegram app relaying an actual button tap (Telegram's own callback mechanism doesn't cryptographically bind callback_data to "the button we sent" — see CallbackData.WithHMAC's doc).
var ErrSkipHandler = errors.New("golagram: skip to next handler")
ErrSkipHandler lets a handler decline after its filters already matched, so dispatch falls through to the next matching handler for this update instead of stopping. Return it from a handler that discovers mid-flight it isn't the right one after all.
Functions ¶
func ChatMemberIsMember ¶
func ChatMemberIsMember(m ChatMember) bool
ChatMemberIsMember reports whether a ChatMember union value represents someone currently in the chat (owner/admin/member, or restricted with is_member true).
func ChatMemberStatus ¶
func ChatMemberStatus(m ChatMember) string
ChatMemberStatus returns a ChatMember union value's status string ("creator", "administrator", "member", "restricted", "left", "kicked"), or "" for nil. ChatMember.GetStatus is generated (types.gen.go) from the fields every ChatMember member has in common, so this no longer hand-maintains a status string per member — it just can't drift from the spec the way a hand-written switch could.
func DecodeStartPayload ¶
DecodeStartPayload reverses EncodeStartPayload on the payload a deep link delivered (c.Command().Args in a /start handler). Padding is accepted and ignored, since some encoders include it.
func EncodeStartPayload ¶
EncodeStartPayload encodes arbitrary text into the URL-safe base64 form (no padding) that survives Telegram's deep-link charset restriction (A-Z a-z 0-9 _ -). Pair with DecodeStartPayload in the /start handler. 64 encoded characters fit 48 raw bytes — TelegramBot.CreateStartLink reports an error if the result is too long.
func EscapeHTML ¶
EscapeHTML escapes text for parse_mode "HTML": &, <, and > — the three characters Telegram's HTML dialect requires escaped outside tags.
c.Answer("<b>"+gg.EscapeHTML(userInput)+"</b>", &gg.SendMessageOptions{ParseMode: "HTML"})
func EscapeMarkdownV2 ¶
EscapeMarkdownV2 escapes text for parse_mode "MarkdownV2" — all 18 characters the spec reserves, plus backslash itself so a literal "\" in the input survives the round trip.
Only for regular text: inside an inline code/pre span use EscapeMarkdownV2Code; inside the parenthesized URL of a link or custom-emoji definition use EscapeMarkdownV2Link — the spec escapes fewer characters there, and over-escaping renders stray backslashes.
func EscapeMarkdownV2Code ¶
EscapeMarkdownV2Code escapes text for the inside of a MarkdownV2 inline code span or pre block, where only ` and \ are special.
func EscapeMarkdownV2Link ¶
EscapeMarkdownV2Link escapes text for the parenthesized URL of a MarkdownV2 link or custom-emoji definition, where only ) and \ are special.
func FSMGet ¶
func FSMGet[T any](f *FSMContext, key string) (T, bool, error)
FSMGet reads one typed value from a conversation's data map. The bool reports whether the key was present at all; the error reports a present value that can't be converted to T.
It first tries a direct type assertion (what MemoryStorage returns), then falls back to converting through JSON — so an int stored before a restart and read back from a persistent backend as float64 still comes out as an int, and a struct stored by value comes back as that struct rather than map[string]any. This is the reading half of FSMStorage's JSON round-trip contract.
func FSMSet ¶
func FSMSet(f *FSMContext, key string, value any) error
FSMSet writes one key into the conversation's data map, leaving the rest untouched — shorthand for FSMContext.UpdateData with a single-entry map.
func IsBlockedByUser ¶
IsBlockedByUser reports whether err means the user blocked the bot — the signal to stop messaging (and usually to drop them from broadcasts).
func IsChatNotFound ¶
IsChatNotFound reports whether err means the target chat doesn't exist (or the bot has never seen it).
func IsConflict ¶
IsConflict reports whether err is Telegram's 409 Conflict — another getUpdates long-poll (or a webhook) is already active for this bot token. TelegramBot.Run logs this distinctly from a generic getUpdates failure, since the fix (stop the other instance, or wait out a rolling deploy) is different from a transient network error.
func IsFlood ¶
IsFlood reports whether err is Telegram's 429 flood-control error. Use RetryAfter from AsAPIError for the wait duration.
func KeepChatAction ¶
KeepChatAction shows a chat action ("typing", "upload_photo", ...) and keeps it alive by re-sending it every ~4s — Telegram clears an action after 5 seconds, so a single Ctx.SendChatAction goes blank during any real work. It stops when the returned function is called or the Ctx is canceled, whichever comes first:
stop := gg.KeepChatAction(c, gg.ChatActionUploadPhoto) defer stop() // ... render the image, then send it ...
Sends are best-effort: a failed refresh (flood limit, chat gone) is dropped, not surfaced — the action is cosmetic, the handler's real sends will report anything that matters.
func Reply ¶
func Reply(req webhookMethodNamer) error
Reply wraps req (e.g. &gg.SendMessageRequest{...}) so a handler can return it from HandlerFunc instead of calling TelegramBot.SendMessage /etc. directly. What happens to it depends on how this update was dispatched:
- A registration that opted into AllowWebhookReply, which TelegramBot.RunWebhook's TelegramBot.Handler dispatches synchronously in the HTTP request goroutine because it matched this update: req is embedded directly in the webhook HTTP response body — Telegram's documented reply-in-response optimization, no follow-up HTTPS call.
- Anything else — polling, a registration that didn't opt in, or req itself carrying a local file upload (multipart can't ride in a JSON response body): req is sent as a normal, fire-and-forget API call instead. Either way, the call gets made.
In both cases the call's result is discarded — Reply trades the typed response value (the sent Message, its ID, ...) for behaving identically regardless of dispatch mode. If you need that value back, call TelegramBot.SendMessage /etc. directly instead of using Reply.
func RichBlockPlainText ¶
RichBlockPlainText flattens one RichBlock to plain text, recursing into nested blocks (list items, blockquotes, details) and delegating span-level content to RichTextPlainText. Every one of the 24 concrete RichBlock types is handled explicitly; the seven media types (no text to extract) render as a short bracketed tag instead of dropping silently.
func RichTextPlainText ¶
RichTextPlainText flattens one RichText to plain text — every one of the 24 named types plus the two primitive alternatives (RichPlainText, RichTextSequence) — dropping style entirely (there's no plain-text rendering of "bold") and returning the underlying words.
func SplitText ¶
SplitText splits text into chunks that each fit Telegram's message length limit, so a long text can be sent as consecutive messages:
for _, part := range gg.SplitText(long) {
if _, err := c.Answer(part); err != nil {
return err
}
}
Split points prefer a newline, then a space, and only cut mid-word when a single word exceeds the whole limit; separator whitespace at the seam is dropped. Lengths are measured in UTF-16 code units — what Telegram actually counts (an emoji counts as 2) — and a cut never lands inside a surrogate pair, so no chunk ever draws a 400 for length or breaks a character in half. Empty input yields nil. A custom limit (e.g. 1024 for captions) can be passed as the optional second argument.
For text that carries formatting entities, use SplitTextWithEntities — splitting the plain text alone would cut through them.
func Typing ¶
func Typing(c *Ctx) (stop func())
Typing is KeepChatAction with the "typing" action — the common case:
defer gg.Typing(c)()
func ValidateToken ¶
ValidateToken checks a bot token's format — "<bot_id>:<35-character secret>" — without making a network call. NewTelegramBot calls this before its first request (getMe), so a malformed token (empty string, a pasted secret missing the bot-ID prefix, a stray space) fails immediately with a message that says what's wrong, instead of a generic HTTP 404 from Telegram a few hundred milliseconds later.
Types ¶
type ACO ¶
type ACO = AnswerCallbackOptions
ACO is AnswerCallbackOptions' short alias — see AnswerCallbackOptions' doc.
type AIO ¶
type AIO = AnswerInlineOptions
AIO is AnswerInlineOptions' short alias — see AnswerInlineOptions' doc.
type APIError ¶
APIError is a typed Telegram Bot API error. Every failed API call returns one (wrapped or not), carrying the error code, Telegram's description, and the actionable parameters: RetryAfter on 429 flood control and MigrateToChatID when a group was upgraded to a supergroup.
func AsAPIError ¶
AsAPIError extracts the *APIError from err, if there is one.
type AcceptedGiftTypes ¶
type AcceptedGiftTypes struct {
// True, if unlimited regular gifts are accepted
UnlimitedGifts bool `json:"unlimited_gifts"`
// True, if limited regular gifts are accepted
LimitedGifts bool `json:"limited_gifts"`
// True, if unique gifts or gifts that can be upgraded to unique for free are accepted
UniqueGifts bool `json:"unique_gifts"`
// True, if a Telegram Premium subscription is accepted
PremiumSubscription bool `json:"premium_subscription"`
// True, if transfers of unique gifts from channels are accepted
GiftsFromChannels bool `json:"gifts_from_channels"`
}
This object describes the types of gifts that can be gifted to a user or a chat.
type AddStickerToSetRequest ¶
type AddStickerToSetRequest struct {
// User identifier of sticker set owner
UserID int64 `json:"user_id"`
// Sticker set name
Name string `json:"name"`
// A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed.
Sticker *InputSticker `json:"sticker"`
}
AddStickerToSetRequest holds the parameters for addStickerToSet.
type AdminCache ¶
type AdminCache struct {
// contains filtered or unexported fields
}
AdminCache caches TelegramBot.GetChatMember lookups per {chat, user} for AdminCache.FilterIsAdmin, so a busy chat's every single update doesn't round-trip the Bot API just to check who's an admin. Unlike RateLimiter / MemoryStorage's sliding TTL, an entry's expiry is fixed at write time — an admin promotion/demotion should become visible within one ttl window of continuous activity, not be pushed back indefinitely by it.
func NewAdminCache ¶
func NewAdminCache(ttl time.Duration) *AdminCache
NewAdminCache creates a cache that re-checks admin status via TelegramBot.GetChatMember at most once per ttl for a given {chat, user}. Call AdminCache.Close when done to stop the background sweep goroutine.
func (*AdminCache) Close ¶
func (a *AdminCache) Close()
Close stops the background eviction goroutine. Safe to call more than once.
func (*AdminCache) FilterIsAdmin ¶
func (a *AdminCache) FilterIsAdmin() Filter
FilterIsAdmin matches updates from a chat administrator or owner, checked via TelegramBot.GetChatMember and cached in a. A lookup failure (network error, or the bot itself lacking admin rights — GetChatMember only guarantees full detail on other members when the bot is one) matches false rather than erroring: an admin-only handler should fail closed, not open.
On a cache miss this makes a real getChatMember call — synchronously, inside the per-{chat,user} dispatch lock (see Filter's doc) — so a slow or hanging Telegram response here stalls every other queued update from the same user until it returns. Usually invisible (misses are rare once the cache is warm); worth knowing about under flood plus a cold cache. a.ttl controls how often a given {chat,user} pays for it again.
type AffiliateInfo ¶
type AffiliateInfo struct {
// Optional. The bot or the user that received an affiliate commission if it was received by a bot or a user
AffiliateUser *User `json:"affiliate_user,omitempty"`
// Optional. The chat that received an affiliate commission if it was received by a chat
AffiliateChat *Chat `json:"affiliate_chat,omitempty"`
// The number of Telegram Stars received by the affiliate for each 1000 Telegram Stars received by the bot from referred users
CommissionPerMille int64 `json:"commission_per_mille"`
// Integer amount of Telegram Stars received by the affiliate from the transaction, rounded to 0; can be negative for refunds
Amount int64 `json:"amount"`
// Optional. The number of 1/1000000000 shares of Telegram Stars received by the affiliate; from -999999999 to 999999999; can be negative for refunds
NanostarAmount int64 `json:"nanostar_amount,omitempty"`
}
Contains information about the affiliate that received a commission via this transaction.
type Animation ¶
type Animation struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Video width as defined by the sender
Width int64 `json:"width"`
// Video height as defined by the sender
Height int64 `json:"height"`
// Duration of the video in seconds as defined by the sender
Duration int64 `json:"duration"`
// Optional. Animation thumbnail as defined by the sender
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
// Optional. Original animation filename as defined by the sender
FileName string `json:"file_name,omitempty"`
// Optional. MIME type of the file as defined by the sender
MimeType string `json:"mime_type,omitempty"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
}
This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).
type AnswerCallbackOptions ¶
AnswerCallbackOptions carries the optional parameters of answerCallbackQuery.
type AnswerCallbackQueryRequest ¶
type AnswerCallbackQueryRequest struct {
// Unique identifier for the query to be answered
CallbackQueryID string `json:"callback_query_id"`
// Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.
Text string `json:"text,omitempty"`
// If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
ShowAlert bool `json:"show_alert,omitempty"`
// URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
URL string `json:"url,omitempty"`
// The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
CacheTime int64 `json:"cache_time,omitempty"`
}
AnswerCallbackQueryRequest holds the parameters for answerCallbackQuery.
type AnswerChatJoinRequestQueryRequest ¶
type AnswerChatJoinRequestQueryRequest struct {
// Unique identifier of the join request query
ChatJoinRequestQueryID string `json:"chat_join_request_query_id"`
// Result of the query. Must be either “approve” to allow the user to join the chat, “decline” to disallow the user to join the chat, or “queue” to leave the decision to other administrators.
Result string `json:"result"`
}
AnswerChatJoinRequestQueryRequest holds the parameters for answerChatJoinRequestQuery.
type AnswerGuestQueryRequest ¶
type AnswerGuestQueryRequest struct {
// Unique identifier for the query to be answered
GuestQueryID string `json:"guest_query_id"`
// A JSON-serialized object describing the message to be sent
Result InlineQueryResult `json:"result"`
}
AnswerGuestQueryRequest holds the parameters for answerGuestQuery.
type AnswerInlineOptions ¶
type AnswerInlineOptions struct {
CacheTime int64
IsPersonal bool
NextOffset string
Button *InlineQueryResultsButton
}
AnswerInlineOptions carries the optional parameters of answerInlineQuery.
type AnswerInlineQueryRequest ¶
type AnswerInlineQueryRequest struct {
// Unique identifier for the answered query
InlineQueryID string `json:"inline_query_id"`
// A JSON-serialized array of results for the inline query
Results []InlineQueryResult `json:"results"`
// The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.
CacheTime int64 `json:"cache_time,omitempty"`
// Pass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.
IsPersonal bool `json:"is_personal,omitempty"`
// Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes.
NextOffset string `json:"next_offset,omitempty"`
// A JSON-serialized object describing a button to be shown above inline query results
Button *InlineQueryResultsButton `json:"button,omitempty"`
}
AnswerInlineQueryRequest holds the parameters for answerInlineQuery.
type AnswerPreCheckoutQueryRequest ¶
type AnswerPreCheckoutQueryRequest struct {
// Unique identifier for the query to be answered
PreCheckoutQueryID string `json:"pre_checkout_query_id"`
// Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
Ok bool `json:"ok"`
// Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
ErrorMessage string `json:"error_message,omitempty"`
}
AnswerPreCheckoutQueryRequest holds the parameters for answerPreCheckoutQuery.
type AnswerShippingQueryRequest ¶
type AnswerShippingQueryRequest struct {
// Unique identifier for the query to be answered
ShippingQueryID string `json:"shipping_query_id"`
// Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
Ok bool `json:"ok"`
// Required if ok is True. A JSON-serialized array of available shipping options.
ShippingOptions []ShippingOption `json:"shipping_options,omitempty"`
// Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. “Sorry, delivery to your desired address is unavailable”). Telegram will display this message to the user.
ErrorMessage string `json:"error_message,omitempty"`
}
AnswerShippingQueryRequest holds the parameters for answerShippingQuery.
type AnswerWebAppQueryRequest ¶
type AnswerWebAppQueryRequest struct {
// Unique identifier for the query to be answered
WebAppQueryID string `json:"web_app_query_id"`
// A JSON-serialized object describing the message to be sent
Result InlineQueryResult `json:"result"`
}
AnswerWebAppQueryRequest holds the parameters for answerWebAppQuery.
type ApproveChatJoinRequestRequest ¶
type ApproveChatJoinRequestRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
}
ApproveChatJoinRequestRequest holds the parameters for approveChatJoinRequest.
type ApproveSuggestedPostRequest ¶
type ApproveSuggestedPostRequest struct {
// Unique identifier for the target direct messages chat
ChatID int64 `json:"chat_id"`
// Identifier of a suggested post message to approve
MessageID int64 `json:"message_id"`
// Point in time (Unix timestamp) when the post is expected to be published; omit if the date has already been specified when the suggested post was created. If specified, then the date must be not more than 2678400 seconds (30 days) in the future.
SendDate int64 `json:"send_date,omitempty"`
}
ApproveSuggestedPostRequest holds the parameters for approveSuggestedPost.
type Audio ¶
type Audio struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Duration of the audio in seconds as defined by the sender
Duration int64 `json:"duration"`
// Optional. Performer of the audio as defined by the sender or by audio tags
Performer string `json:"performer,omitempty"`
// Optional. Title of the audio as defined by the sender or by audio tags
Title string `json:"title,omitempty"`
// Optional. Original filename as defined by the sender
FileName string `json:"file_name,omitempty"`
// Optional. MIME type of the file as defined by the sender
MimeType string `json:"mime_type,omitempty"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
// Optional. Thumbnail of the album cover to which the music file belongs
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
}
This object represents an audio file to be treated as music by the Telegram clients.
type BackgroundFill ¶
type BackgroundFill interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the way a background is filled based on the selected colors. Currently, it can be one of
type BackgroundFillFreeformGradient ¶
type BackgroundFillFreeformGradient struct {
// Type of the background fill, always “freeform_gradient”
Type string `json:"type"`
// A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format
Colors []int64 `json:"colors"`
}
The background is a freeform gradient that rotates after every message in the chat.
func (*BackgroundFillFreeformGradient) GetType ¶
func (v *BackgroundFillFreeformGradient) GetType() string
type BackgroundFillGradient ¶
type BackgroundFillGradient struct {
// Type of the background fill, always “gradient”
Type string `json:"type"`
// Top color of the gradient in the RGB24 format
TopColor int64 `json:"top_color"`
// Bottom color of the gradient in the RGB24 format
BottomColor int64 `json:"bottom_color"`
// Clockwise rotation angle of the background fill in degrees; 0-359
RotationAngle int64 `json:"rotation_angle"`
}
The background is a gradient fill.
func (*BackgroundFillGradient) GetType ¶
func (v *BackgroundFillGradient) GetType() string
type BackgroundFillSolid ¶
type BackgroundFillSolid struct {
// Type of the background fill, always “solid”
Type string `json:"type"`
// The color of the background fill in the RGB24 format
Color int64 `json:"color"`
}
The background is filled using the selected color.
func (*BackgroundFillSolid) GetType ¶
func (v *BackgroundFillSolid) GetType() string
The Get* methods below implement BackgroundFill: fields shared by every member, callable on the interface value directly without a type switch.
type BackgroundType ¶
type BackgroundType interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the type of a background. Currently, it can be one of
type BackgroundTypeChatTheme ¶
type BackgroundTypeChatTheme struct {
// Type of the background, always “chat_theme”
Type string `json:"type"`
// Name of the chat theme, which is usually an emoji
ThemeName string `json:"theme_name"`
}
The background is taken directly from a built-in chat theme.
func (*BackgroundTypeChatTheme) GetType ¶
func (v *BackgroundTypeChatTheme) GetType() string
type BackgroundTypeFill ¶
type BackgroundTypeFill struct {
// Type of the background, always “fill”
Type string `json:"type"`
// The background fill
Fill BackgroundFill `json:"fill"`
// Dimming of the background in dark themes, as a percentage; 0-100
DarkThemeDimming int64 `json:"dark_theme_dimming"`
}
The background is automatically filled based on the selected colors.
func (*BackgroundTypeFill) GetType ¶
func (v *BackgroundTypeFill) GetType() string
The Get* methods below implement BackgroundType: fields shared by every member, callable on the interface value directly without a type switch.
func (*BackgroundTypeFill) UnmarshalJSON ¶
func (v *BackgroundTypeFill) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes BackgroundTypeFill's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type BackgroundTypePattern ¶
type BackgroundTypePattern struct {
// Type of the background, always “pattern”
Type string `json:"type"`
// Document with the pattern
Document *Document `json:"document"`
// The background fill that is combined with the pattern
Fill BackgroundFill `json:"fill"`
// Intensity of the pattern when it is shown above the filled background; 0-100
Intensity int64 `json:"intensity"`
// Optional. True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only.
IsInverted bool `json:"is_inverted,omitempty"`
// Optional. True, if the background moves slightly when the device is tilted
IsMoving bool `json:"is_moving,omitempty"`
}
The background is a .PNG or .TGV (gzipped subset of SVG with MIME type “application/x-tgwallpattern”) pattern to be combined with the background fill chosen by the user.
func (*BackgroundTypePattern) GetType ¶
func (v *BackgroundTypePattern) GetType() string
func (*BackgroundTypePattern) UnmarshalJSON ¶
func (v *BackgroundTypePattern) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes BackgroundTypePattern's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type BackgroundTypeWallpaper ¶
type BackgroundTypeWallpaper struct {
// Type of the background, always “wallpaper”
Type string `json:"type"`
// Document with the wallpaper
Document *Document `json:"document"`
// Dimming of the background in dark themes, as a percentage; 0-100
DarkThemeDimming int64 `json:"dark_theme_dimming"`
// Optional. True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12
IsBlurred bool `json:"is_blurred,omitempty"`
// Optional. True, if the background moves slightly when the device is tilted
IsMoving bool `json:"is_moving,omitempty"`
}
The background is a wallpaper in the JPEG format.
func (*BackgroundTypeWallpaper) GetType ¶
func (v *BackgroundTypeWallpaper) GetType() string
type Backoff ¶
type Backoff struct {
// contains filtered or unexported fields
}
Backoff is a stateful exponential backoff with a cap: the same "double, cap, reset on success" policy golagram's own polling runtime uses between failed getUpdates calls, exported so a user's own retry loop (a custom API poller, a health check, anything hitting an external service that wants to back off on failure) doesn't have to reimplement it. Not goroutine-safe — one Backoff per loop, like a time.Timer.
func NewBackoff ¶
NewBackoff creates a Backoff starting at min, doubling on every Backoff.Next call up to max.
type BanChatMemberRequest ¶
type BanChatMemberRequest struct {
// Unique identifier for the target group or username of the target supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only.
UntilDate int64 `json:"until_date,omitempty"`
// Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.
RevokeMessages bool `json:"revoke_messages,omitempty"`
}
BanChatMemberRequest holds the parameters for banChatMember.
type BanChatSenderChatRequest ¶
type BanChatSenderChatRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target sender chat
SenderChatID int64 `json:"sender_chat_id"`
}
BanChatSenderChatRequest holds the parameters for banChatSenderChat.
type Birthdate ¶
type Birthdate struct {
// Day of the user's birth; 1-31
Day int64 `json:"day"`
// Month of the user's birth; 1-12
Month int64 `json:"month"`
// Optional. Year of the user's birth
Year int64 `json:"year,omitempty"`
}
Describes the birthdate of a user.
type BotAccessSettings ¶
type BotAccessSettings struct {
// True, if only selected users can access the bot. The bot's owner can always access it.
IsAccessRestricted bool `json:"is_access_restricted"`
// Optional. The list of other users who have access to the bot if the access is restricted
AddedUsers []User `json:"added_users,omitempty"`
}
This object describes the access settings of a bot.
type BotCommand ¶
type BotCommand struct {
// Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores.
Command string `json:"command"`
// Description of the command; 1-256 characters
Description string `json:"description"`
}
This object represents a bot command.
type BotCommandScope ¶
type BotCommandScope interface {
GetType() string
// contains filtered or unexported methods
}
This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:
type BotCommandScopeAllChatAdministrators ¶
type BotCommandScopeAllChatAdministrators struct {
// Scope type, must be all_chat_administrators
Type string `json:"type"`
}
Represents the scope of bot commands, covering all group and supergroup chat administrators.
func (*BotCommandScopeAllChatAdministrators) GetType ¶
func (v *BotCommandScopeAllChatAdministrators) GetType() string
type BotCommandScopeAllGroupChats ¶
type BotCommandScopeAllGroupChats struct {
// Scope type, must be all_group_chats
Type string `json:"type"`
}
Represents the scope of bot commands, covering all group and supergroup chats.
func (*BotCommandScopeAllGroupChats) GetType ¶
func (v *BotCommandScopeAllGroupChats) GetType() string
type BotCommandScopeAllPrivateChats ¶
type BotCommandScopeAllPrivateChats struct {
// Scope type, must be all_private_chats
Type string `json:"type"`
}
Represents the scope of bot commands, covering all private chats.
func (*BotCommandScopeAllPrivateChats) GetType ¶
func (v *BotCommandScopeAllPrivateChats) GetType() string
type BotCommandScopeChat ¶
type BotCommandScopeChat struct {
// Scope type, must be chat
Type string `json:"type"`
// Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported.
ChatID ChatID `json:"chat_id"`
}
Represents the scope of bot commands, covering a specific chat.
func (*BotCommandScopeChat) GetType ¶
func (v *BotCommandScopeChat) GetType() string
type BotCommandScopeChatAdministrators ¶
type BotCommandScopeChatAdministrators struct {
// Scope type, must be chat_administrators
Type string `json:"type"`
// Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported.
ChatID ChatID `json:"chat_id"`
}
Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.
func (*BotCommandScopeChatAdministrators) GetType ¶
func (v *BotCommandScopeChatAdministrators) GetType() string
type BotCommandScopeChatMember ¶
type BotCommandScopeChatMember struct {
// Scope type, must be chat_member
Type string `json:"type"`
// Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported.
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
}
Represents the scope of bot commands, covering a specific member of a group or supergroup chat.
func (*BotCommandScopeChatMember) GetType ¶
func (v *BotCommandScopeChatMember) GetType() string
type BotCommandScopeDefault ¶
type BotCommandScopeDefault struct {
// Scope type, must be default
Type string `json:"type"`
}
Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user.
func (*BotCommandScopeDefault) GetType ¶
func (v *BotCommandScopeDefault) GetType() string
The Get* methods below implement BotCommandScope: fields shared by every member, callable on the interface value directly without a type switch.
type BotDescription ¶
type BotDescription struct {
// The bot's description
Description string `json:"description"`
}
This object represents the bot's description.
type BotName ¶
type BotName struct {
// The bot's name
Name string `json:"name"`
}
This object represents the bot's name.
type BotShortDescription ¶
type BotShortDescription struct {
// The bot's short description
ShortDescription string `json:"short_description"`
}
This object represents the bot's short description.
type BroadcastOption ¶
type BroadcastOption func(*broadcastConfig)
BroadcastOption configures a Broadcast call.
func WithBroadcastConcurrency ¶
func WithBroadcastConcurrency(n int) BroadcastOption
WithBroadcastConcurrency sets how many chats Broadcast sends to in parallel (default 10). Concurrency exists to hide per-call network latency, not to bypass the rate limit: every worker shares one pacer, so total throughput is still capped at the configured rate regardless of this setting. A purely serial send (concurrency 1) would top out well below that rate once round-trip latency is accounted for.
func WithBroadcastProgress ¶
func WithBroadcastProgress(fn func(BroadcastProgress)) BroadcastOption
WithBroadcastProgress registers fn to run after every chat resolves (success or failure). Calls are serialized — fn never needs its own synchronization even though sends happen concurrently.
func WithBroadcastRate ¶
func WithBroadcastRate(perSecond float64) BroadcastOption
WithBroadcastRate caps the send rate in messages/second (default 25 — a safety margin under Telegram's ~30 msg/s bot-wide limit).
type BroadcastProgress ¶
type BroadcastProgress struct {
Total int
Sent int
Failed int // includes Blocked
Blocked int
Remaining int
}
BroadcastProgress is passed to a WithBroadcastProgress callback after every chat resolves.
type BroadcastResult ¶
type BroadcastResult struct {
Sent int
Failed int
Blocked []int64 // chat IDs where [IsBlockedByUser] was true
Errors map[int64]error // failed, non-blocked chat IDs -> the last error seen
}
BroadcastResult summarizes a finished (or canceled) Broadcast call.
func Broadcast ¶
func Broadcast(ctx context.Context, chatIDs []int64, send BroadcastSendFunc, opts ...BroadcastOption) (*BroadcastResult, error)
Broadcast sends to every chat in chatIDs via send, paced against Telegram's rate limits (see WithBroadcastRate/WithBroadcastConcurrency). An IsBlockedByUser failure is permanent and recorded in BroadcastResult.Blocked; a IsFlood (429) failure pauses the shared pacer for the error's RetryAfter (or 1s if Telegram didn't set one) and retries that one chat exactly once — a second failure on the retry is recorded normally, bounding the worst-case per-chat delay instead of retrying forever. Any other error is recorded in BroadcastResult.Errors with no retry.
Scope limit: Broadcast only paces the aggregate send rate, not per-chat (~1 msg/s) or per-group (~20 msg/min) limits — those matter when the same chat receives multiple messages in quick succession, which a broadcast over distinct chat IDs doesn't naturally trigger. The aggregate rate is the binding constraint for the common case (announcing to many distinct subscribers).
If ctx is canceled before every chat resolves, Broadcast returns immediately with a partial BroadcastResult and ctx.Err(); chats that hadn't started sending yet are simply absent from the result. A broadcast that runs to completion returns (result, nil) — per-chat failures never surface as the returned error, only through the result.
type BroadcastSendFunc ¶
BroadcastSendFunc sends to one chat. Broadcast paces when this is called; the closure itself calls whatever generated method fits (bot.SendMessage, bot.SendPhoto, ...).
type BusinessBotRights ¶
type BusinessBotRights struct {
// Optional. True, if the bot can send and edit messages in the private chats that had incoming messages in the last 24 hours
CanReply bool `json:"can_reply,omitempty"`
// Optional. True, if the bot can mark incoming private messages as read
CanReadMessages bool `json:"can_read_messages,omitempty"`
// Optional. True, if the bot can delete messages sent by the bot
CanDeleteSentMessages bool `json:"can_delete_sent_messages,omitempty"`
// Optional. True, if the bot can delete all private messages in managed chats
CanDeleteAllMessages bool `json:"can_delete_all_messages,omitempty"`
// Optional. True, if the bot can edit the first and last name of the business account
CanEditName bool `json:"can_edit_name,omitempty"`
// Optional. True, if the bot can edit the bio of the business account
CanEditBio bool `json:"can_edit_bio,omitempty"`
// Optional. True, if the bot can edit the profile photo of the business account
CanEditProfilePhoto bool `json:"can_edit_profile_photo,omitempty"`
// Optional. True, if the bot can edit the username of the business account
CanEditUsername bool `json:"can_edit_username,omitempty"`
// Optional. True, if the bot can change the privacy settings pertaining to gifts for the business account
CanChangeGiftSettings bool `json:"can_change_gift_settings,omitempty"`
// Optional. True, if the bot can view gifts and the amount of Telegram Stars owned by the business account
CanViewGiftsAndStars bool `json:"can_view_gifts_and_stars,omitempty"`
// Optional. True, if the bot can convert regular gifts owned by the business account to Telegram Stars
CanConvertGiftsToStars bool `json:"can_convert_gifts_to_stars,omitempty"`
// Optional. True, if the bot can transfer and upgrade gifts owned by the business account
CanTransferAndUpgradeGifts bool `json:"can_transfer_and_upgrade_gifts,omitempty"`
// Optional. True, if the bot can transfer Telegram Stars received by the business account to its own account, or use them to upgrade and transfer gifts
CanTransferStars bool `json:"can_transfer_stars,omitempty"`
// Optional. True, if the bot can post, edit and delete stories on behalf of the business account
CanManageStories bool `json:"can_manage_stories,omitempty"`
}
Represents the rights of a business bot.
type BusinessConnection ¶
type BusinessConnection struct {
// Unique identifier of the business connection
ID string `json:"id"`
// Business account user that created the business connection
User *User `json:"user"`
// Identifier of a private chat with the user who created the business connection. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
UserChatID int64 `json:"user_chat_id"`
// Date the connection was established in Unix time
Date int64 `json:"date"`
// Optional. Rights of the business bot
Rights *BusinessBotRights `json:"rights,omitempty"`
// True, if the connection is active
IsEnabled bool `json:"is_enabled"`
}
Describes the connection of the bot with a business account.
type BusinessIntro ¶
type BusinessIntro struct {
// Optional. Title text of the business intro
Title string `json:"title,omitempty"`
// Optional. Message text of the business intro
Message string `json:"message,omitempty"`
// Optional. Sticker of the business intro
Sticker *Sticker `json:"sticker,omitempty"`
}
Contains information about the start page settings of a Telegram Business account.
type BusinessLocation ¶
type BusinessLocation struct {
// Address of the business
Address string `json:"address"`
// Optional. Location of the business
Location *Location `json:"location,omitempty"`
}
Contains information about the location of a Telegram Business account.
type BusinessMessagesDeleted ¶
type BusinessMessagesDeleted struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Information about a chat in the business account. The bot may not have access to the chat or the corresponding user.
Chat *Chat `json:"chat"`
// The list of identifiers of deleted messages in the chat of the business account
MessageIds []int64 `json:"message_ids"`
}
This object is received when messages are deleted from a connected business account.
type BusinessOpeningHours ¶
type BusinessOpeningHours struct {
// Unique name of the time zone for which the opening hours are defined
TimeZoneName string `json:"time_zone_name"`
// List of time intervals describing business opening hours
OpeningHours []BusinessOpeningHoursInterval `json:"opening_hours"`
}
Describes the opening hours of a business.
type BusinessOpeningHoursInterval ¶
type BusinessOpeningHoursInterval struct {
// The minute's sequence number in a week, starting on Monday, marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60
OpeningMinute int64 `json:"opening_minute"`
// The minute's sequence number in a week, starting on Monday, marking the end of the time interval during which the business is open; 0 - 8 * 24 * 60
ClosingMinute int64 `json:"closing_minute"`
}
Describes an interval of time during which a business is open.
type CallbackData ¶
type CallbackData[T any] struct { // contains filtered or unexported fields }
CallbackData packs and unpacks a typed struct into callback_data strings. Declare the payload once, get type-safe buttons and filters with the 64-byte limit enforced at pack time instead of buttons silently not sending:
type BuyItem struct {
ItemID int64
Qty int
}
var buyCB = golagram.NewCallbackData[BuyItem]("buy")
kb.Add(buyCB.Button("Buy now", BuyItem{ItemID: 42, Qty: 1})) // data: "buy:42:1"
r.CallbackQuery(buyCB.Filter()).Handle(func(c *gg.Ctx) error {
item, _ := buyCB.Unpack(c.CallbackQuery.Data)
...
})
func NewCallbackData ¶
func NewCallbackData[T any](prefix string) *CallbackData[T]
NewCallbackData declares a callback-data schema: prefix identifies the button family, T's exported fields (in declaration order) are the payload. Supported field types: string, bool, all int/uint sizes, float64. Panics at wiring time on an unsupported schema — same rationale as Router.Include's cycle panic: fail at startup, not on the first click.
func (*CallbackData[T]) Button ¶
func (cd *CallbackData[T]) Button(text string, v T) InlineKeyboardButton
Button builds an inline keyboard button carrying the packed payload. Panics on a payload that fails Pack (over 64 bytes / separator in a string field) — a button that Telegram would silently refuse to send is a wiring bug, surface it at build time.
func (*CallbackData[T]) Filter ¶
func (cd *CallbackData[T]) Filter() Filter
Filter matches callback queries whose data carries this schema's prefix.
func (*CallbackData[T]) FilterWhere ¶
func (cd *CallbackData[T]) FilterWhere(pred func(T) bool) Filter
FilterWhere matches callback queries whose data unpacks into this schema AND satisfies pred — a typed predicate over the payload:
buyCB.FilterWhere(func(b BuyItem) bool { return b.Qty > 1 })
func (*CallbackData[T]) FromCtx ¶
func (cd *CallbackData[T]) FromCtx(c *Ctx) (T, error)
FromCtx unpacks the current callback query's data. Errors if the update isn't a callback query or its data doesn't match this schema — pair with CallbackData.Filter on the registration so it can't be.
func (*CallbackData[T]) MustPack ¶
func (cd *CallbackData[T]) MustPack(v T) string
MustPack is Pack for values known valid at compile/wiring time; panics on error.
func (*CallbackData[T]) Pack ¶
func (cd *CallbackData[T]) Pack(v T) (string, error)
Pack encodes v as "prefix:field1:field2:...". Returns a *ValidationError when the result would exceed Telegram's 64-byte callback_data limit, or when a string field contains the ":" separator (which would corrupt the encoding).
func (*CallbackData[T]) Unpack ¶
func (cd *CallbackData[T]) Unpack(data string) (T, error)
Unpack decodes a callback_data string produced by Pack. If this schema was built with CallbackData.WithHMAC, the trailing tag is verified first — ErrCallbackDataTampered on any mismatch — before the payload is decoded.
func (*CallbackData[T]) WithHMAC ¶
func (cd *CallbackData[T]) WithHMAC(secret []byte) *CallbackData[T]
WithHMAC enables tamper detection on this schema: Pack appends a secret- keyed, truncated HMAC-SHA256 tag to the packed payload, and Unpack verifies it before decoding, returning ErrCallbackDataTampered on any mismatch instead of silently decoding forged or corrupted data. Use it for callback payloads that carry something an attacker forging callback_data shouldn't be able to alter or replay unmodified into meaning something else — e.g. a price, a discount, or an approval decision — not for payloads where a bad Unpack is merely a harmless no-op.
secret should be a fixed, private, high-entropy value the bot process holds (e.g. derived from the bot token or a dedicated config secret) — not per-user or per-payload. Returns cd for chaining:
var buyCB = golagram.NewCallbackData[BuyItem]("buy").WithHMAC(secretKey)
type CallbackGame ¶
type CallbackGame struct {
}
A placeholder, currently holds no information. Use BotFather to set up your game.
type CallbackQuery ¶
type CallbackQuery struct {
// Unique identifier for this query
ID string `json:"id"`
// Sender
From *User `json:"from"`
// Optional. Message sent by the bot with the callback button that originated the query
Message *Message `json:"message,omitempty"`
// Optional. Identifier of the message sent via the bot in inline mode, that originated the query
InlineMessageID string `json:"inline_message_id,omitempty"`
// Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.
ChatInstance string `json:"chat_instance"`
// Optional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data.
Data string `json:"data,omitempty"`
// Optional. Short name of a Game to be returned, serves as the unique identifier for the game
GameShortName string `json:"game_short_name,omitempty"`
// contains filtered or unexported fields
}
This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.
func (*CallbackQuery) Answer ¶
func (e *CallbackQuery) Answer(text string, options ...*AnswerCallbackOptions) error
Answer acknowledges the callback query via answerCallbackQuery — this is what stops the client-side loading spinner on the pressed button. Call it in every callback handler. Empty text just dismisses the spinner; non-empty text shows a toast, or an alert box with &AnswerCallbackOptions{ShowAlert: true}.
func (*CallbackQuery) Answered ¶
func (e *CallbackQuery) Answered() bool
Answered reports whether Answer has already been called on this callback query — CallbackAnswerMiddleware reads this to avoid double-answering one that a handler already dismissed itself.
func (*CallbackQuery) ChatID ¶
func (e *CallbackQuery) ChatID() int64
ChatID returns the chat the callback's message lives in. When the original message is missing entirely (inline mode), it falls back to the clicking user's ID — the private chat with them.
func (*CallbackQuery) FSM ¶
func (e *CallbackQuery) FSM() *FSMContext
FSM returns the conversation state context for the user who clicked this button, scoped per the bot's FSMKeyStrategy (by default: this user in the chat the original message lives in).
func (*CallbackQuery) FromID ¶
func (e *CallbackQuery) FromID() int64
FromID returns the ID of the user who pressed the button.
func (*CallbackQuery) Reply ¶
func (e *CallbackQuery) Reply(text string, options ...*SendMessageOptions) (*Message, error)
Reply replies to the message the callback was attached to and returns the sent message.
func (*CallbackQuery) SendMessage ¶
func (e *CallbackQuery) SendMessage(text string, options ...*SendMessageOptions) (*Message, error)
SendMessage sends a new message into the chat the callback's message came from and returns the sent message.
type Chat ¶
type Chat struct {
// Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
ID int64 `json:"id"`
// Type of the chat, can be either “private”, “group”, “supergroup” or “channel”
Type string `json:"type"`
// Optional. Title, for supergroups, channels and group chats
Title string `json:"title,omitempty"`
// Optional. Username, for private chats, supergroups and channels if available
Username string `json:"username,omitempty"`
// Optional. First name of the other party in a private chat
FirstName string `json:"first_name,omitempty"`
// Optional. Last name of the other party in a private chat
LastName string `json:"last_name,omitempty"`
// Optional. True, if the supergroup chat is a forum (has topics enabled)
IsForum bool `json:"is_forum,omitempty"`
// Optional. True, if the chat is the direct messages chat of a channel
IsDirectMessages bool `json:"is_direct_messages,omitempty"`
}
This object represents a chat.
type ChatAdministratorRights ¶
type ChatAdministratorRights struct {
// True, if the user's presence in the chat is hidden
IsAnonymous bool `json:"is_anonymous"`
// True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege.
CanManageChat bool `json:"can_manage_chat"`
// True, if the administrator can delete messages of other users
CanDeleteMessages bool `json:"can_delete_messages"`
// True, if the administrator can manage video chats
CanManageVideoChats bool `json:"can_manage_video_chats"`
// True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics
CanRestrictMembers bool `json:"can_restrict_members"`
// True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)
CanPromoteMembers bool `json:"can_promote_members"`
// True, if the user is allowed to change the chat title, photo and other settings
CanChangeInfo bool `json:"can_change_info"`
// True, if the user is allowed to invite new users to the chat
CanInviteUsers bool `json:"can_invite_users"`
// True, if the administrator can post stories to the chat
CanPostStories bool `json:"can_post_stories"`
// True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive
CanEditStories bool `json:"can_edit_stories"`
// True, if the administrator can delete stories posted by other users
CanDeleteStories bool `json:"can_delete_stories"`
// Optional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only
CanPostMessages bool `json:"can_post_messages,omitempty"`
// Optional. True, if the administrator can edit messages of other users and can pin messages; for channels only
CanEditMessages bool `json:"can_edit_messages,omitempty"`
// Optional. True, if the user is allowed to pin messages; for groups and supergroups only
CanPinMessages bool `json:"can_pin_messages,omitempty"`
// Optional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only
CanManageTopics bool `json:"can_manage_topics,omitempty"`
// Optional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only
CanManageDirectMessages bool `json:"can_manage_direct_messages,omitempty"`
// Optional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages.
CanManageTags bool `json:"can_manage_tags,omitempty"`
}
Represents the rights of an administrator in a chat.
type ChatBackground ¶
type ChatBackground struct {
// Type of the background
Type BackgroundType `json:"type"`
}
This object represents a chat background.
func (*ChatBackground) UnmarshalJSON ¶
func (v *ChatBackground) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes ChatBackground's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type ChatBoost ¶
type ChatBoost struct {
// Unique identifier of the boost
BoostID string `json:"boost_id"`
// Point in time (Unix timestamp) when the chat was boosted
AddDate int64 `json:"add_date"`
// Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged
ExpirationDate int64 `json:"expiration_date"`
// Source of the added boost
Source ChatBoostSource `json:"source"`
}
This object contains information about a chat boost.
func (*ChatBoost) UnmarshalJSON ¶
UnmarshalJSON decodes ChatBoost's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type ChatBoostAdded ¶
type ChatBoostAdded struct {
// Number of boosts added by the user
BoostCount int64 `json:"boost_count"`
}
This object represents a service message about a user boosting a chat.
type ChatBoostRemoved ¶
type ChatBoostRemoved struct {
// Chat which was boosted
Chat *Chat `json:"chat"`
// Unique identifier of the boost
BoostID string `json:"boost_id"`
// Point in time (Unix timestamp) when the boost was removed
RemoveDate int64 `json:"remove_date"`
// Source of the removed boost
Source ChatBoostSource `json:"source"`
}
This object represents a boost removed from a chat.
func (*ChatBoostRemoved) UnmarshalJSON ¶
func (v *ChatBoostRemoved) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes ChatBoostRemoved's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type ChatBoostSource ¶
type ChatBoostSource interface {
GetSource() string
GetUser() *User
// contains filtered or unexported methods
}
This object describes the source of a chat boost. It can be one of
type ChatBoostSourceGiftCode ¶
type ChatBoostSourceGiftCode struct {
// Source of the boost, always “gift_code”
Source string `json:"source"`
// User for which the gift code was created
User *User `json:"user"`
}
The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription.
func (*ChatBoostSourceGiftCode) GetSource ¶
func (v *ChatBoostSourceGiftCode) GetSource() string
func (*ChatBoostSourceGiftCode) GetUser ¶
func (v *ChatBoostSourceGiftCode) GetUser() *User
type ChatBoostSourceGiveaway ¶
type ChatBoostSourceGiveaway struct {
// Source of the boost, always “giveaway”
Source string `json:"source"`
// Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet.
GiveawayMessageID int64 `json:"giveaway_message_id"`
// Optional. User that won the prize in the giveaway if any; for Telegram Premium giveaways only
User *User `json:"user,omitempty"`
// Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
PrizeStarCount int64 `json:"prize_star_count,omitempty"`
// Optional. True, if the giveaway was completed, but there was no user to win the prize
IsUnclaimed bool `json:"is_unclaimed,omitempty"`
}
The boost was obtained by the creation of a Telegram Premium or a Telegram Star giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription for Telegram Premium giveaways and prize_star_count / 500 times for one year for Telegram Star giveaways.
func (*ChatBoostSourceGiveaway) GetSource ¶
func (v *ChatBoostSourceGiveaway) GetSource() string
func (*ChatBoostSourceGiveaway) GetUser ¶
func (v *ChatBoostSourceGiveaway) GetUser() *User
type ChatBoostSourcePremium ¶
type ChatBoostSourcePremium struct {
// Source of the boost, always “premium”
Source string `json:"source"`
// User that boosted the chat
User *User `json:"user"`
}
The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user.
func (*ChatBoostSourcePremium) GetSource ¶
func (v *ChatBoostSourcePremium) GetSource() string
The Get* methods below implement ChatBoostSource: fields shared by every member, callable on the interface value directly without a type switch.
func (*ChatBoostSourcePremium) GetUser ¶
func (v *ChatBoostSourcePremium) GetUser() *User
type ChatBoostUpdated ¶
type ChatBoostUpdated struct {
// Chat which was boosted
Chat *Chat `json:"chat"`
// Information about the chat boost
Boost *ChatBoost `json:"boost"`
}
This object represents a boost added to a chat or changed.
type ChatFullInfo ¶
type ChatFullInfo struct {
// Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
ID int64 `json:"id"`
// Type of the chat, can be either “private”, “group”, “supergroup” or “channel”
Type string `json:"type"`
// Optional. Title, for supergroups, channels and group chats
Title string `json:"title,omitempty"`
// Optional. Username, for private chats, supergroups and channels if available
Username string `json:"username,omitempty"`
// Optional. First name of the other party in a private chat
FirstName string `json:"first_name,omitempty"`
// Optional. Last name of the other party in a private chat
LastName string `json:"last_name,omitempty"`
// Optional. True, if the supergroup chat is a forum (has topics enabled)
IsForum bool `json:"is_forum,omitempty"`
// Optional. True, if the chat is the direct messages chat of a channel
IsDirectMessages bool `json:"is_direct_messages,omitempty"`
// Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details.
AccentColorID int64 `json:"accent_color_id"`
// The maximum number of reactions that can be set on a message in the chat
MaxReactionCount int64 `json:"max_reaction_count"`
// Optional. Chat photo
Photo *ChatPhoto `json:"photo,omitempty"`
// Optional. If non-empty, the list of all active chat usernames; for private chats, supergroups and channels
ActiveUsernames []string `json:"active_usernames,omitempty"`
// Optional. For private chats, the date of birth of the user
Birthdate *Birthdate `json:"birthdate,omitempty"`
// Optional. For private chats with business accounts, the intro of the business
BusinessIntro *BusinessIntro `json:"business_intro,omitempty"`
// Optional. For private chats with business accounts, the location of the business
BusinessLocation *BusinessLocation `json:"business_location,omitempty"`
// Optional. For private chats with business accounts, the opening hours of the business
BusinessOpeningHours *BusinessOpeningHours `json:"business_opening_hours,omitempty"`
// Optional. For private chats, the personal channel of the user
PersonalChat *Chat `json:"personal_chat,omitempty"`
// Optional. Information about the corresponding channel chat; for direct messages chats only
ParentChat *Chat `json:"parent_chat,omitempty"`
// Optional. List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed.
AvailableReactions []ReactionType `json:"available_reactions,omitempty"`
// Optional. Custom emoji identifier of the emoji chosen by the chat for the reply header and link preview background
BackgroundCustomEmojiID string `json:"background_custom_emoji_id,omitempty"`
// Optional. Identifier of the accent color for the chat's profile background. See profile accent colors for more details.
ProfileAccentColorID int64 `json:"profile_accent_color_id,omitempty"`
// Optional. Custom emoji identifier of the emoji chosen by the chat for its profile background
ProfileBackgroundCustomEmojiID string `json:"profile_background_custom_emoji_id,omitempty"`
// Optional. Custom emoji identifier of the emoji status of the chat or the other party in a private chat
EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"`
// Optional. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any
EmojiStatusExpirationDate int64 `json:"emoji_status_expiration_date,omitempty"`
// Optional. Bio of the other party in a private chat
Bio string `json:"bio,omitempty"`
// Optional. True, if privacy settings of the other party in the private chat allows to use tg://user?id=<user_id> links only in chats with the user
HasPrivateForwards bool `json:"has_private_forwards,omitempty"`
// Optional. True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat
HasRestrictedVoiceAndVideoMessages bool `json:"has_restricted_voice_and_video_messages,omitempty"`
// Optional. True, if users need to join the supergroup before they can send messages
JoinToSendMessages bool `json:"join_to_send_messages,omitempty"`
// Optional. True, if all users directly joining the supergroup without using an invite link need to be approved by supergroup administrators
JoinByRequest bool `json:"join_by_request,omitempty"`
// Optional. Description, for groups, supergroups and channel chats
Description string `json:"description,omitempty"`
// Optional. Primary invite link, for groups, supergroups and channel chats
InviteLink string `json:"invite_link,omitempty"`
// Optional. The most recent pinned message (by sending date)
PinnedMessage *Message `json:"pinned_message,omitempty"`
// Optional. Default chat member permissions, for groups and supergroups
Permissions *ChatPermissions `json:"permissions,omitempty"`
// Information about types of gifts that are accepted by the chat or by the corresponding user for private chats
AcceptedGiftTypes *AcceptedGiftTypes `json:"accepted_gift_types"`
// Optional. True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats.
CanSendPaidMedia bool `json:"can_send_paid_media,omitempty"`
// Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds
SlowModeDelay int64 `json:"slow_mode_delay,omitempty"`
// Optional. For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions
UnrestrictBoostCount int64 `json:"unrestrict_boost_count,omitempty"`
// Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds
MessageAutoDeleteTime int64 `json:"message_auto_delete_time,omitempty"`
// Optional. True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators.
HasAggressiveAntiSpamEnabled bool `json:"has_aggressive_anti_spam_enabled,omitempty"`
// Optional. True, if non-administrators can only get the list of bots and administrators in the chat
HasHiddenMembers bool `json:"has_hidden_members,omitempty"`
// Optional. True, if messages from the chat can't be forwarded to other chats
HasProtectedContent bool `json:"has_protected_content,omitempty"`
// Optional. True, if new chat members will have access to old messages; available only to chat administrators
HasVisibleHistory bool `json:"has_visible_history,omitempty"`
// Optional. For supergroups, name of the group sticker set
StickerSetName string `json:"sticker_set_name,omitempty"`
// Optional. True, if the bot can change the group sticker set
CanSetStickerSet bool `json:"can_set_sticker_set,omitempty"`
// Optional. For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group.
CustomEmojiStickerSetName string `json:"custom_emoji_sticker_set_name,omitempty"`
// Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
LinkedChatID int64 `json:"linked_chat_id,omitempty"`
// Optional. For supergroups, the location to which the supergroup is connected
Location *ChatLocation `json:"location,omitempty"`
// Optional. For private chats, the rating of the user if any
Rating *UserRating `json:"rating,omitempty"`
// Optional. For private chats, the first audio added to the profile of the user
FirstProfileAudio *Audio `json:"first_profile_audio,omitempty"`
// Optional. The color scheme based on a unique gift that must be used for the chat's name, message replies and link previews
UniqueGiftColors *UniqueGiftColors `json:"unique_gift_colors,omitempty"`
// Optional. The number of Telegram Stars a general user has to pay to send a message to the chat
PaidMessageStarCount int64 `json:"paid_message_star_count,omitempty"`
// Optional. The bot that processes join request queries in the chat. The field is only available to chat administrators.
GuardBot *User `json:"guard_bot,omitempty"`
}
This object contains full information about a chat.
func (*ChatFullInfo) UnmarshalJSON ¶
func (v *ChatFullInfo) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes ChatFullInfo's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type ChatID ¶
type ChatID struct {
// contains filtered or unexported fields
}
ChatID identifies a chat either by its numeric ID or by the @username of a public channel/supergroup. Construct with ChatIDFromInt or ChatIDFromUsername; the zero value marshals as 0, which Telegram will reject, so always use one of the constructors.
func ChatIDFromInt ¶
ChatIDFromInt targets a chat by its numeric ID.
func ChatIDFromUsername ¶
ChatIDFromUsername targets a public channel or supergroup by @username (with or without the leading @).
func (ChatID) IsZero ¶
IsZero reports whether c is the zero value (neither constructor called) — used by encoding/json's `omitzero` tag on optional ChatID fields, since the zero value's MarshalJSON output (0) is a real, rejectable chat_id rather than something Telegram treats as absent, unlike `omitempty` (never true for a non-pointer struct, whatever its contents).
func (ChatID) MarshalJSON ¶
type ChatInviteLink ¶
type ChatInviteLink struct {
// The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”.
InviteLink string `json:"invite_link"`
// Creator of the link
Creator *User `json:"creator"`
// True, if users joining the chat via the link need to be approved by chat administrators
CreatesJoinRequest bool `json:"creates_join_request"`
// True, if the link is primary
IsPrimary bool `json:"is_primary"`
// True, if the link is revoked
IsRevoked bool `json:"is_revoked"`
// Optional. Invite link name
Name string `json:"name,omitempty"`
// Optional. Point in time (Unix timestamp) when the link will expire or has been expired
ExpireDate int64 `json:"expire_date,omitempty"`
// Optional. The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
MemberLimit int64 `json:"member_limit,omitempty"`
// Optional. Number of pending join requests created using this link
PendingJoinRequestCount int64 `json:"pending_join_request_count,omitempty"`
// Optional. The number of seconds the subscription will be active for before the next payment
SubscriptionPeriod int64 `json:"subscription_period,omitempty"`
// Optional. The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat using the link
SubscriptionPrice int64 `json:"subscription_price,omitempty"`
}
Represents an invite link for a chat.
type ChatJoinRequest ¶
type ChatJoinRequest struct {
// Chat to which the request was sent
Chat *Chat `json:"chat"`
// User that sent the join request
From *User `json:"from"`
// Identifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 5 minutes to send messages until the join request is processed, assuming no other administrator contacted the user.
UserChatID int64 `json:"user_chat_id"`
// Date the request was sent in Unix time
Date int64 `json:"date"`
// Optional. Bio of the user
Bio string `json:"bio,omitempty"`
// Optional. Chat invite link that was used by the user to send the join request
InviteLink *ChatInviteLink `json:"invite_link,omitempty"`
// Optional. Identifier of the join request query; for bots assigned to process join request only. If present, then the bot must call sendChatJoinRequestWebApp or directly call answerChatJoinRequestQuery within 10 seconds.
QueryID string `json:"query_id,omitempty"`
}
Represents a join request sent to a chat.
type ChatLocation ¶
type ChatLocation struct {
// The location to which the supergroup is connected. Can't be a live location.
Location *Location `json:"location"`
// Location address; 1-64 characters, as defined by the chat owner
Address string `json:"address"`
}
Represents a location to which a chat is connected.
type ChatMember ¶
type ChatMember interface {
GetStatus() string
GetUser() *User
// contains filtered or unexported methods
}
This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:
type ChatMemberAdministrator ¶
type ChatMemberAdministrator struct {
// The member's status in the chat, always “administrator”
Status string `json:"status"`
// Information about the user
User *User `json:"user"`
// True, if the bot is allowed to edit administrator privileges of that user
CanBeEdited bool `json:"can_be_edited"`
// True, if the user's presence in the chat is hidden
IsAnonymous bool `json:"is_anonymous"`
// True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege.
CanManageChat bool `json:"can_manage_chat"`
// True, if the administrator can delete messages of other users
CanDeleteMessages bool `json:"can_delete_messages"`
// True, if the administrator can manage video chats
CanManageVideoChats bool `json:"can_manage_video_chats"`
// True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics
CanRestrictMembers bool `json:"can_restrict_members"`
// True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)
CanPromoteMembers bool `json:"can_promote_members"`
// True, if the user is allowed to change the chat title, photo and other settings
CanChangeInfo bool `json:"can_change_info"`
// True, if the user is allowed to invite new users to the chat
CanInviteUsers bool `json:"can_invite_users"`
// True, if the administrator can post stories to the chat
CanPostStories bool `json:"can_post_stories"`
// True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive
CanEditStories bool `json:"can_edit_stories"`
// True, if the administrator can delete stories posted by other users
CanDeleteStories bool `json:"can_delete_stories"`
// Optional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only
CanPostMessages bool `json:"can_post_messages,omitempty"`
// Optional. True, if the administrator can edit messages of other users and can pin messages; for channels only
CanEditMessages bool `json:"can_edit_messages,omitempty"`
// Optional. True, if the user is allowed to pin messages; for groups and supergroups only
CanPinMessages bool `json:"can_pin_messages,omitempty"`
// Optional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only
CanManageTopics bool `json:"can_manage_topics,omitempty"`
// Optional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only
CanManageDirectMessages bool `json:"can_manage_direct_messages,omitempty"`
// Optional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages.
CanManageTags bool `json:"can_manage_tags,omitempty"`
// Optional. Custom title for this user
CustomTitle string `json:"custom_title,omitempty"`
}
Represents a chat member that has some additional privileges.
func (*ChatMemberAdministrator) GetStatus ¶
func (v *ChatMemberAdministrator) GetStatus() string
func (*ChatMemberAdministrator) GetUser ¶
func (v *ChatMemberAdministrator) GetUser() *User
type ChatMemberBanned ¶
type ChatMemberBanned struct {
// The member's status in the chat, always “kicked”
Status string `json:"status"`
// Information about the user
User *User `json:"user"`
// Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever.
UntilDate int64 `json:"until_date"`
}
Represents a chat member that was banned in the chat and can't return to the chat or view chat messages.
func (*ChatMemberBanned) GetStatus ¶
func (v *ChatMemberBanned) GetStatus() string
func (*ChatMemberBanned) GetUser ¶
func (v *ChatMemberBanned) GetUser() *User
type ChatMemberLeft ¶
type ChatMemberLeft struct {
// The member's status in the chat, always “left”
Status string `json:"status"`
// Information about the user
User *User `json:"user"`
}
Represents a chat member that isn't currently a member of the chat, but may join it themselves.
func (*ChatMemberLeft) GetStatus ¶
func (v *ChatMemberLeft) GetStatus() string
func (*ChatMemberLeft) GetUser ¶
func (v *ChatMemberLeft) GetUser() *User
type ChatMemberMember ¶
type ChatMemberMember struct {
// The member's status in the chat, always “member”
Status string `json:"status"`
// Optional. Tag of the member
Tag string `json:"tag,omitempty"`
// Information about the user
User *User `json:"user"`
// Optional. Date when the user's subscription will expire; Unix time
UntilDate int64 `json:"until_date,omitempty"`
}
Represents a chat member that has no additional privileges or restrictions.
func (*ChatMemberMember) GetStatus ¶
func (v *ChatMemberMember) GetStatus() string
func (*ChatMemberMember) GetUser ¶
func (v *ChatMemberMember) GetUser() *User
type ChatMemberOwner ¶
type ChatMemberOwner struct {
// The member's status in the chat, always “creator”
Status string `json:"status"`
// Information about the user
User *User `json:"user"`
// True, if the user's presence in the chat is hidden
IsAnonymous bool `json:"is_anonymous"`
// Optional. Custom title for this user
CustomTitle string `json:"custom_title,omitempty"`
}
Represents a chat member that owns the chat and has all administrator privileges.
func (*ChatMemberOwner) GetStatus ¶
func (v *ChatMemberOwner) GetStatus() string
The Get* methods below implement ChatMember: fields shared by every member, callable on the interface value directly without a type switch.
func (*ChatMemberOwner) GetUser ¶
func (v *ChatMemberOwner) GetUser() *User
type ChatMemberRestricted ¶
type ChatMemberRestricted struct {
// The member's status in the chat, always “restricted”
Status string `json:"status"`
// Optional. Tag of the member
Tag string `json:"tag,omitempty"`
// Information about the user
User *User `json:"user"`
// True, if the user is a member of the chat at the moment of the request
IsMember bool `json:"is_member"`
// True, if the user is allowed to send text messages, rich messages, contacts, giveaways, giveaway winners, invoices, locations and venues
CanSendMessages bool `json:"can_send_messages"`
// True, if the user is allowed to send audios
CanSendAudios bool `json:"can_send_audios"`
// True, if the user is allowed to send documents
CanSendDocuments bool `json:"can_send_documents"`
// True, if the user is allowed to send photos
CanSendPhotos bool `json:"can_send_photos"`
// True, if the user is allowed to send videos
CanSendVideos bool `json:"can_send_videos"`
// True, if the user is allowed to send video notes
CanSendVideoNotes bool `json:"can_send_video_notes"`
// True, if the user is allowed to send voice notes
CanSendVoiceNotes bool `json:"can_send_voice_notes"`
// True, if the user is allowed to send polls and checklists
CanSendPolls bool `json:"can_send_polls"`
// True, if the user is allowed to send animations, games, stickers and use inline bots
CanSendOtherMessages bool `json:"can_send_other_messages"`
// True, if the user is allowed to add web page previews to their messages
CanAddWebPagePreviews bool `json:"can_add_web_page_previews"`
// True, if the user is allowed to react to messages
CanReactToMessages bool `json:"can_react_to_messages"`
// True, if the user is allowed to edit their own tag
CanEditTag bool `json:"can_edit_tag"`
// True, if the user is allowed to change the chat title, photo and other settings
CanChangeInfo bool `json:"can_change_info"`
// True, if the user is allowed to invite new users to the chat
CanInviteUsers bool `json:"can_invite_users"`
// True, if the user is allowed to pin messages
CanPinMessages bool `json:"can_pin_messages"`
// True, if the user is allowed to create forum topics
CanManageTopics bool `json:"can_manage_topics"`
// Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever.
UntilDate int64 `json:"until_date"`
}
Represents a chat member that is under certain restrictions in the chat. Supergroups only.
func (*ChatMemberRestricted) GetStatus ¶
func (v *ChatMemberRestricted) GetStatus() string
func (*ChatMemberRestricted) GetUser ¶
func (v *ChatMemberRestricted) GetUser() *User
type ChatMemberUpdated ¶
type ChatMemberUpdated struct {
// Chat the user belongs to
Chat *Chat `json:"chat"`
// Performer of the action, which resulted in the change
From *User `json:"from"`
// Date the change was done in Unix time
Date int64 `json:"date"`
// Previous information about the chat member
OldChatMember ChatMember `json:"old_chat_member"`
// New information about the chat member
NewChatMember ChatMember `json:"new_chat_member"`
// Optional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only
InviteLink *ChatInviteLink `json:"invite_link,omitempty"`
// Optional. True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator
ViaJoinRequest bool `json:"via_join_request,omitempty"`
// Optional. True, if the user joined the chat via a chat folder invite link
ViaChatFolderInviteLink bool `json:"via_chat_folder_invite_link,omitempty"`
}
This object represents changes in the status of a chat member.
func (*ChatMemberUpdated) UnmarshalJSON ¶
func (v *ChatMemberUpdated) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes ChatMemberUpdated's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type ChatOwnerChanged ¶
type ChatOwnerChanged struct {
// The new owner of the chat
NewOwner *User `json:"new_owner"`
}
Describes a service message about an ownership change in the chat.
type ChatOwnerLeft ¶
type ChatOwnerLeft struct {
// Optional. The user who will become the new owner of the chat if the previous owner does not return to the chat
NewOwner *User `json:"new_owner,omitempty"`
}
Describes a service message about the chat owner leaving the chat.
type ChatPermissions ¶
type ChatPermissions struct {
// Optional. True, if the user is allowed to send text messages, rich messages, contacts, giveaways, giveaway winners, invoices, locations and venues
CanSendMessages bool `json:"can_send_messages,omitempty"`
// Optional. True, if the user is allowed to send audios
CanSendAudios bool `json:"can_send_audios,omitempty"`
// Optional. True, if the user is allowed to send documents
CanSendDocuments bool `json:"can_send_documents,omitempty"`
// Optional. True, if the user is allowed to send photos
CanSendPhotos bool `json:"can_send_photos,omitempty"`
// Optional. True, if the user is allowed to send videos
CanSendVideos bool `json:"can_send_videos,omitempty"`
// Optional. True, if the user is allowed to send video notes
CanSendVideoNotes bool `json:"can_send_video_notes,omitempty"`
// Optional. True, if the user is allowed to send voice notes
CanSendVoiceNotes bool `json:"can_send_voice_notes,omitempty"`
// Optional. True, if the user is allowed to send polls and checklists
CanSendPolls bool `json:"can_send_polls,omitempty"`
// Optional. True, if the user is allowed to send animations, games, stickers and use inline bots
CanSendOtherMessages bool `json:"can_send_other_messages,omitempty"`
// Optional. True, if the user is allowed to add web page previews to their messages
CanAddWebPagePreviews bool `json:"can_add_web_page_previews,omitempty"`
// Optional. True, if the user is allowed to react to messages. If omitted, defaults to the value of can_send_messages.
CanReactToMessages bool `json:"can_react_to_messages,omitempty"`
// Optional. True, if the user is allowed to edit their own tag. If omitted, defaults to the value of can_pin_messages.
CanEditTag bool `json:"can_edit_tag,omitempty"`
// Optional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups.
CanChangeInfo bool `json:"can_change_info,omitempty"`
// Optional. True, if the user is allowed to invite new users to the chat
CanInviteUsers bool `json:"can_invite_users,omitempty"`
// Optional. True, if the user is allowed to pin messages. Ignored in public supergroups.
CanPinMessages bool `json:"can_pin_messages,omitempty"`
// Optional. True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages.
CanManageTopics bool `json:"can_manage_topics,omitempty"`
}
Describes actions that a non-administrator user is allowed to take in a chat.
type ChatPhoto ¶
type ChatPhoto struct {
// File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
SmallFileID string `json:"small_file_id"`
// Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
SmallFileUniqueID string `json:"small_file_unique_id"`
// File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
BigFileID string `json:"big_file_id"`
// Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
BigFileUniqueID string `json:"big_file_unique_id"`
}
This object represents a chat photo.
type ChatShared ¶
type ChatShared struct {
RequestID int64 `json:"request_id"`
ChatID int64 `json:"chat_id"`
Title string `json:"title,omitempty"`
Username string `json:"username,omitempty"`
Photo []PhotoSize `json:"photo,omitempty"`
}
This object contains information about a chat that was shared with the bot using a KeyboardButtonRequestChat button.
type Checklist ¶
type Checklist struct {
// Title of the checklist
Title string `json:"title"`
// Optional. Special entities that appear in the checklist title
TitleEntities []MessageEntity `json:"title_entities,omitempty"`
// List of tasks in the checklist
Tasks []ChecklistTask `json:"tasks"`
// Optional. True, if users other than the creator of the list can add tasks to the list
OthersCanAddTasks bool `json:"others_can_add_tasks,omitempty"`
// Optional. True, if users other than the creator of the list can mark tasks as done or not done
OthersCanMarkTasksAsDone bool `json:"others_can_mark_tasks_as_done,omitempty"`
}
Describes a checklist.
type ChecklistTask ¶
type ChecklistTask struct {
// Unique identifier of the task
ID int64 `json:"id"`
// Text of the task
Text string `json:"text"`
// Optional. Special entities that appear in the task text
TextEntities []MessageEntity `json:"text_entities,omitempty"`
// Optional. User that completed the task; omitted if the task wasn't completed by a user
CompletedByUser *User `json:"completed_by_user,omitempty"`
// Optional. Chat that completed the task; omitted if the task wasn't completed by a chat
CompletedByChat *Chat `json:"completed_by_chat,omitempty"`
// Optional. Point in time (Unix timestamp) when the task was completed; 0 if the task wasn't completed
CompletionDate int64 `json:"completion_date,omitempty"`
}
Describes a task in a checklist.
type ChecklistTasksAdded ¶
type ChecklistTasksAdded struct {
// Optional. Message containing the checklist to which the tasks were added. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
ChecklistMessage *Message `json:"checklist_message,omitempty"`
// List of tasks added to the checklist
Tasks []ChecklistTask `json:"tasks"`
}
Describes a service message about tasks added to a checklist.
type ChecklistTasksDone ¶
type ChecklistTasksDone struct {
// Optional. Message containing the checklist whose tasks were marked as done or not done. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
ChecklistMessage *Message `json:"checklist_message,omitempty"`
// Optional. Identifiers of the tasks that were marked as done
MarkedAsDoneTaskIds []int64 `json:"marked_as_done_task_ids,omitempty"`
// Optional. Identifiers of the tasks that were marked as not done
MarkedAsNotDoneTaskIds []int64 `json:"marked_as_not_done_task_ids,omitempty"`
}
Describes a service message about checklist tasks marked as done or not done.
type ChosenInlineResult ¶
type ChosenInlineResult struct {
// The unique identifier for the result that was chosen
ResultID string `json:"result_id"`
// The user that chose the result
From *User `json:"from"`
// Optional. Sender location, only for bots that require user location
Location *Location `json:"location,omitempty"`
// Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// The query that was used to obtain the result
Query string `json:"query"`
}
Represents a result of an inline query that was chosen by the user and sent to their chat partner.
type CloseForumTopicRequest ¶
type CloseForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the target message thread of the forum topic
MessageThreadID int64 `json:"message_thread_id"`
}
CloseForumTopicRequest holds the parameters for closeForumTopic.
type CloseGeneralForumTopicRequest ¶
type CloseGeneralForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
}
CloseGeneralForumTopicRequest holds the parameters for closeGeneralForumTopic.
type CommandObject ¶
type CommandObject struct {
Command string // "start" from "/start ..."
Mention string // "my_bot" from "/start@my_bot" ("" if none)
Args string // everything after the first space ("" if none)
}
CommandObject is a parsed bot command. For the text "/start@my_bot ref_12345" it is {Command: "start", Mention: "my_bot", Args: "ref_12345"} — which makes deep-link/referral flows one field access.
func ParseCommand ¶
func ParseCommand(text string) (*CommandObject, bool)
ParseCommand parses a message text as a bot command. It returns false when the text is not a command (doesn't start with "/", or has an empty name).
type Contact ¶
type Contact struct {
// Contact's phone number
PhoneNumber string `json:"phone_number"`
// Contact's first name
FirstName string `json:"first_name"`
// Optional. Contact's last name
LastName string `json:"last_name,omitempty"`
// Optional. Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
UserID int64 `json:"user_id,omitempty"`
// Optional. Additional data about the contact in the form of a vCard
Vcard string `json:"vcard,omitempty"`
}
This object represents a phone contact.
type ConvertGiftToStarsRequest ¶
type ConvertGiftToStarsRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the regular gift that should be converted to Telegram Stars
OwnedGiftID string `json:"owned_gift_id"`
}
ConvertGiftToStarsRequest holds the parameters for convertGiftToStars.
type CopyMessageRequest ¶
type CopyMessageRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username)
FromChatID ChatID `json:"from_chat_id"`
// Message identifier in the chat specified in from_chat_id
MessageID int64 `json:"message_id"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// New start timestamp for the copied video in the message
VideoStartTimestamp int64 `json:"video_start_timestamp,omitempty"`
// New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept.
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the new caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media. Ignored if a new caption isn't specified.
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; only available when copying to private chats
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
CopyMessageRequest holds the parameters for copyMessage.
type CopyMessagesRequest ¶
type CopyMessagesRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username)
FromChatID ChatID `json:"from_chat_id"`
// A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order.
MessageIds []int64 `json:"message_ids"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Sends the messages silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent messages from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to copy the messages without their captions
RemoveCaption bool `json:"remove_caption,omitempty"`
}
CopyMessagesRequest holds the parameters for copyMessages.
type CopyTextButton ¶
type CopyTextButton struct {
// The text to be copied to the clipboard; 1-256 characters
Text string `json:"text"`
}
This object represents an inline keyboard button that copies specified text to the clipboard.
type CreateChatInviteLinkRequest ¶
type CreateChatInviteLinkRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Invite link name; 0-32 characters
Name string `json:"name,omitempty"`
// Point in time (Unix timestamp) when the link will expire
ExpireDate int64 `json:"expire_date,omitempty"`
// The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
MemberLimit int64 `json:"member_limit,omitempty"`
// True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified.
CreatesJoinRequest bool `json:"creates_join_request,omitempty"`
}
CreateChatInviteLinkRequest holds the parameters for createChatInviteLink.
type CreateChatSubscriptionInviteLinkRequest ¶
type CreateChatSubscriptionInviteLinkRequest struct {
// Unique identifier for the target channel chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days).
SubscriptionPeriod int64 `json:"subscription_period"`
// The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-10000
SubscriptionPrice int64 `json:"subscription_price"`
// Invite link name; 0-32 characters
Name string `json:"name,omitempty"`
}
CreateChatSubscriptionInviteLinkRequest holds the parameters for createChatSubscriptionInviteLink.
type CreateForumTopicRequest ¶
type CreateForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Topic name, 1-128 characters
Name string `json:"name"`
// Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F).
IconColor int64 `json:"icon_color,omitempty"`
// Unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers.
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
}
CreateForumTopicRequest holds the parameters for createForumTopic.
type CreateInvoiceLinkRequest ¶
type CreateInvoiceLinkRequest struct {
// Product name, 1-32 characters
Title string `json:"title"`
// Product description, 1-255 characters
Description string `json:"description"`
// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes.
Payload string `json:"payload"`
// Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
Currency string `json:"currency"`
// Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
Prices []LabeledPrice `json:"prices"`
// Unique identifier of the business connection on behalf of which the link will be created. For payments in Telegram Stars only.
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
ProviderToken string `json:"provider_token,omitempty"`
// The number of seconds the subscription will be active for before the next payment. The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified. Any number of subscriptions can be active for a given bot at the same time, including multiple concurrent subscriptions from the same user. Subscription price must no exceed 10000 Telegram Stars.
SubscriptionPeriod int64 `json:"subscription_period,omitempty"`
// The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
MaxTipAmount int64 `json:"max_tip_amount,omitempty"`
// A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
SuggestedTipAmounts []int64 `json:"suggested_tip_amounts,omitempty"`
// JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
ProviderData string `json:"provider_data,omitempty"`
// URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.
PhotoURL string `json:"photo_url,omitempty"`
// Photo size in bytes
PhotoSize int64 `json:"photo_size,omitempty"`
// Photo width
PhotoWidth int64 `json:"photo_width,omitempty"`
// Photo height
PhotoHeight int64 `json:"photo_height,omitempty"`
// Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
NeedName bool `json:"need_name,omitempty"`
// Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
NeedPhoneNumber bool `json:"need_phone_number,omitempty"`
// Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
NeedEmail bool `json:"need_email,omitempty"`
// Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
NeedShippingAddress bool `json:"need_shipping_address,omitempty"`
// Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
SendPhoneNumberToProvider bool `json:"send_phone_number_to_provider,omitempty"`
// Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
SendEmailToProvider bool `json:"send_email_to_provider,omitempty"`
// Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
IsFlexible bool `json:"is_flexible,omitempty"`
}
CreateInvoiceLinkRequest holds the parameters for createInvoiceLink.
type CreateNewStickerSetRequest ¶
type CreateNewStickerSetRequest struct {
// User identifier of created sticker set owner
UserID int64 `json:"user_id"`
// Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "_by_<bot_username>". <bot_username> is case insensitive. 1-64 characters.
Name string `json:"name"`
// Sticker set title, 1-64 characters
Title string `json:"title"`
// A JSON-serialized list of 1-50 initial stickers to be added to the sticker set
Stickers []InputSticker `json:"stickers"`
// Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created.
StickerType string `json:"sticker_type,omitempty"`
// Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only
NeedsRepainting bool `json:"needs_repainting,omitempty"`
}
CreateNewStickerSetRequest holds the parameters for createNewStickerSet.
type Ctx ¶
Ctx is what handlers receive, regardless of update kind: it carries the context.Context for cancellation, the raw Update (embedded, so c.Message, c.CallbackQuery, c.InlineQuery, ... all resolve directly), and sugar for the common actions (Ctx.Answer, Ctx.AnswerCallback, Ctx.FSM). Message, CallbackQuery, and friends stay pure data types; this is where the ergonomics live.
func (*Ctx) Answer ¶
func (c *Ctx) Answer(text string, options ...*SendMessageOptions) (*Message, error)
Answer sends a message into whichever chat this update relates to — whichever message-shaped payload is present, or the chat a callback query's message lives in — propagating the source message's business connection and forum topic like Message.Answer does. Returns an error if the update carries neither (e.g. inline_query, poll_answer).
func (*Ctx) AnswerCallback ¶
func (c *Ctx) AnswerCallback(text string, options ...*AnswerCallbackOptions) error
AnswerCallback acknowledges the callback query via answerCallbackQuery — dismissing the client-side loading spinner. Returns an error if this update isn't a callback query.
func (*Ctx) AnswerInline ¶
func (c *Ctx) AnswerInline(results []InlineQueryResult, options ...*AnswerInlineOptions) error
AnswerInline answers an inline query via answerInlineQuery. Returns an error if this update isn't an inline query.
func (*Ctx) AnswerPreCheckout ¶
AnswerPreCheckout approves this update's pre-checkout query, letting the payment complete. Telegram requires an answer within 10 seconds of the query — do stock checks fast or approve optimistically and refund.
func (*Ctx) AnswerPreCheckoutError ¶
AnswerPreCheckoutError declines this update's pre-checkout query with a human-readable reason Telegram shows to the user (e.g. "Sorry, we just sold out").
func (*Ctx) AnswerShipping ¶
func (c *Ctx) AnswerShipping(options []ShippingOption) error
AnswerShipping approves this update's shipping query with the available shipping options (for invoices sent with is_flexible).
func (*Ctx) AnswerShippingError ¶
AnswerShippingError declines this update's shipping query with a human-readable reason Telegram shows to the user (e.g. "Sorry, we don't deliver to your region").
func (*Ctx) Bot ¶
func (c *Ctx) Bot() *TelegramBot
Bot returns the bot that received this update, giving handlers access to the full generated Bot API surface (TelegramBot.SendPhoto, TelegramBot.BanChatMember, ...) — not just the Ctx.Answer / Ctx.AnswerCallback sugar available directly on Ctx.
func (*Ctx) Chat ¶
Chat returns the chat this update relates to, resolved per update kind (a message's chat, a callback's message's chat, a chat_member update's chat, ...), or nil for kinds with no chat (inline_query, poll, ...).
func (*Ctx) Command ¶
func (c *Ctx) Command() *CommandObject
Command returns the parsed command of whichever message-shaped payload this update carries, or nil if it isn't a command (or there's no message).
func (*Ctx) Delete ¶
Delete deletes whichever message-shaped payload this update carries (or a callback query's attached message). Returns an error if the update carries neither.
func (*Ctx) EditCaption ¶
func (c *Ctx) EditCaption(caption string, options ...*EditCaptionOptions) (*Message, error)
EditCaption edits the caption of whichever message-shaped payload this update carries (or a callback query's attached message). Returns an error if the update carries neither.
func (*Ctx) EditReplyMarkup ¶
func (c *Ctx) EditReplyMarkup(markup *InlineKeyboardMarkup) (*Message, error)
EditReplyMarkup edits only the inline keyboard of whichever message-shaped payload this update carries (or a callback query's attached message). Returns an error if the update carries neither.
func (*Ctx) EditText ¶
func (c *Ctx) EditText(text string, options ...*EditMessageOptions) (*Message, error)
EditText edits the text of whichever message-shaped payload this update carries (or a callback query's attached message) and returns the edited message. Returns an error if the update carries neither.
func (*Ctx) FSM ¶
func (c *Ctx) FSM() *FSMContext
FSM returns the conversation state context scoped to whoever this update is "from" — the message sender, the callback clicker, the poll voter, etc. — per the bot's FSMKeyStrategy. Update kinds with no natural per-user/chat identity (Poll) share one global key. The Ctx itself is the bound context, so FSM storage calls are canceled with the handler.
func (*Ctx) Flags ¶
Flags returns the metadata attached to the specific registration that matched this update via WithFlags, or nil if it wasn't used. Unlike Ctx.Set / Ctx.Get (a general value bag any handler/middleware can write to), flags are read-only from a handler's perspective — they're fixed at registration time — and scoped to exactly the one route that matched, not shared across the whole dispatch chain.
func (*Ctx) From ¶
From returns the user this update is "from" — the message sender, the callback clicker, the inline querier, the poll voter, ... — or nil for kinds with no user (poll, message_reaction_count, channel posts).
func (*Ctx) Locale ¶
Locale returns the locale I18nMiddleware resolved for this update ("" if the middleware isn't installed).
func (*Ctx) Reply ¶
func (c *Ctx) Reply(text string, options ...*SendMessageOptions) (*Message, error)
Reply replies to whichever message-shaped payload this update carries (or a callback query's attached message) and returns the sent message — like Answer, but sets the reply target to the original message. Returns an error if the update carries neither.
func (*Ctx) SendChatAction ¶
SendChatAction broadcasts a chat action (e.g. "typing") into whichever chat this update relates to. Returns an error if the update carries no message-shaped payload to resolve a chat from.
func (*Ctx) SendStarsInvoice ¶
SendStarsInvoice sends a Telegram Stars invoice into whichever chat this update relates to. For anything beyond the required fields, build the request with NewStarsInvoice and send it via TelegramBot.SendInvoice.
func (*Ctx) Sender ¶
Sender resolves the real identity behind this update — a message's sender, a reaction's actor, or a poll answer's voter — following through to the anonymous chat identity where Telegram provides one, instead of stopping at its dummy user. Returns nil for update kinds with no sender concept at all.
func (*Ctx) Set ¶
Set stores a value on the Ctx, visible to every middleware/handler further down the chain for this update.
func (*Ctx) SetLocale ¶
SetLocale saves a locale override in conversation data — from a /lang command or settings button — and applies it to this Ctx immediately, so even the confirmation message can already be translated.
func (*Ctx) T ¶
T translates key for this update's resolved locale — the gettext-style shorthand. Without I18nMiddleware installed it returns the key itself, so a missing middleware shows up as visible untranslated keys, not a crash.
func (*Ctx) TN ¶
TN translates the plural form of key selected by n (see Translator.TranslateN — pass n in args too if the template renders it).
func (*Ctx) Text ¶
Text returns the text of whichever message-shaped payload this update carries, falling back to its caption for a captioned media message ("" if there's neither — e.g. a poll_answer or chat_member update). Agrees with FilterText and friends, so a handler matched on a caption still gets it back here instead of "".
type DeclineChatJoinRequestRequest ¶
type DeclineChatJoinRequestRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
}
DeclineChatJoinRequestRequest holds the parameters for declineChatJoinRequest.
type DeclineSuggestedPostRequest ¶
type DeclineSuggestedPostRequest struct {
// Unique identifier for the target direct messages chat
ChatID int64 `json:"chat_id"`
// Identifier of a suggested post message to decline
MessageID int64 `json:"message_id"`
// Comment for the creator of the suggested post; 0-128 characters
Comment string `json:"comment,omitempty"`
}
DeclineSuggestedPostRequest holds the parameters for declineSuggestedPost.
type DeleteAllMessageReactionsRequest ¶
type DeleteAllMessageReactionsRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Identifier of the user whose reactions will be removed, if the reactions were added by a user
UserID int64 `json:"user_id,omitempty"`
// Identifier of the chat whose reactions will be removed, if the reactions were added by a chat
ActorChatID int64 `json:"actor_chat_id,omitempty"`
}
DeleteAllMessageReactionsRequest holds the parameters for deleteAllMessageReactions.
type DeleteBusinessMessagesRequest ¶
type DeleteBusinessMessagesRequest struct {
// Unique identifier of the business connection on behalf of which to delete the messages
BusinessConnectionID string `json:"business_connection_id"`
// A JSON-serialized list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted.
MessageIds []int64 `json:"message_ids"`
}
DeleteBusinessMessagesRequest holds the parameters for deleteBusinessMessages.
type DeleteChatPhotoRequest ¶
type DeleteChatPhotoRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
}
DeleteChatPhotoRequest holds the parameters for deleteChatPhoto.
type DeleteChatStickerSetRequest ¶
type DeleteChatStickerSetRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
}
DeleteChatStickerSetRequest holds the parameters for deleteChatStickerSet.
type DeleteForumTopicRequest ¶
type DeleteForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the target message thread of the forum topic
MessageThreadID int64 `json:"message_thread_id"`
}
DeleteForumTopicRequest holds the parameters for deleteForumTopic.
type DeleteMessageReactionRequest ¶
type DeleteMessageReactionRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Identifier of the target message
MessageID int64 `json:"message_id"`
// Identifier of the user whose reaction will be removed, if the reaction was added by a user
UserID int64 `json:"user_id,omitempty"`
// Identifier of the chat whose reaction will be removed, if the reaction was added by a chat
ActorChatID int64 `json:"actor_chat_id,omitempty"`
}
DeleteMessageReactionRequest holds the parameters for deleteMessageReaction.
type DeleteMessageRequest ¶
type DeleteMessageRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Identifier of the message to delete
MessageID int64 `json:"message_id"`
}
DeleteMessageRequest holds the parameters for deleteMessage.
type DeleteMessagesRequest ¶
type DeleteMessagesRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// A JSON-serialized list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted.
MessageIds []int64 `json:"message_ids"`
}
DeleteMessagesRequest holds the parameters for deleteMessages.
type DeleteMyCommandsRequest ¶
type DeleteMyCommandsRequest struct {
// A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
Scope BotCommandScope `json:"scope,omitempty"`
// A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands.
LanguageCode string `json:"language_code,omitempty"`
}
DeleteMyCommandsRequest holds the parameters for deleteMyCommands.
type DeleteStickerFromSetRequest ¶
type DeleteStickerFromSetRequest struct {
// File identifier of the sticker
Sticker string `json:"sticker"`
}
DeleteStickerFromSetRequest holds the parameters for deleteStickerFromSet.
type DeleteStickerSetRequest ¶
type DeleteStickerSetRequest struct {
// Sticker set name
Name string `json:"name"`
}
DeleteStickerSetRequest holds the parameters for deleteStickerSet.
type DeleteStoryRequest ¶
type DeleteStoryRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the story to delete
StoryID int64 `json:"story_id"`
}
DeleteStoryRequest holds the parameters for deleteStory.
type DeleteWebhookRequest ¶
type DeleteWebhookRequest struct {
// Pass True to drop all pending updates
DropPendingUpdates bool `json:"drop_pending_updates,omitempty"`
}
DeleteWebhookRequest holds the parameters for deleteWebhook.
type Dice ¶
type Dice struct {
// Emoji on which the dice throw animation is based
Emoji string `json:"emoji"`
// Value of the dice, 1-6 for “🎲”, “🎯” and “🎳” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji
Value int64 `json:"value"`
}
This object represents an animated emoji that displays a random value.
type DirectMessagePriceChanged ¶
type DirectMessagePriceChanged struct {
// True, if direct messages are enabled for the channel chat; false otherwise
AreDirectMessagesEnabled bool `json:"are_direct_messages_enabled"`
// Optional. The new number of Telegram Stars that must be paid by users for each direct message sent to the channel. Does not apply to users who have been exempted by administrators. Defaults to 0.
DirectMessageStarCount int64 `json:"direct_message_star_count,omitempty"`
}
Describes a service message about a change in the price of direct messages sent to a channel chat.
type DirectMessagesTopic ¶
type DirectMessagesTopic struct {
// Unique identifier of the topic. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
TopicID int64 `json:"topic_id"`
// Optional. Information about the user that created the topic. Currently, it is always present.
User *User `json:"user,omitempty"`
}
Describes a topic of a direct messages chat.
type Document ¶
type Document struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Optional. Document thumbnail as defined by the sender
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
// Optional. Original filename as defined by the sender
FileName string `json:"file_name,omitempty"`
// Optional. MIME type of the file as defined by the sender
MimeType string `json:"mime_type,omitempty"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a general file (as opposed to photos, voice messages and audio files).
type ECO ¶
type ECO = EditCaptionOptions
ECO is EditCaptionOptions' short alias — see EditCaptionOptions' doc.
type EMO ¶
type EMO = EditMessageOptions
EMO is EditMessageOptions' short alias — see EditMessageOptions' doc.
type EditCaptionOptions ¶
type EditCaptionOptions struct {
ParseMode string
CaptionEntities []Entity
ShowCaptionAboveMedia bool
ReplyMarkup *InlineKeyboardMarkup
// BusinessConnectionID is normally left unset — [Message.EditCaption]
// auto-propagates the source message's own BusinessConnectionID, so
// this only needs setting explicitly to override that.
BusinessConnectionID string
}
EditCaptionOptions carries the optional parameters of editMessageCaption.
type EditChatInviteLinkRequest ¶
type EditChatInviteLinkRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// The invite link to edit
InviteLink string `json:"invite_link"`
// Invite link name; 0-32 characters
Name string `json:"name,omitempty"`
// Point in time (Unix timestamp) when the link will expire
ExpireDate int64 `json:"expire_date,omitempty"`
// The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
MemberLimit int64 `json:"member_limit,omitempty"`
// True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified.
CreatesJoinRequest bool `json:"creates_join_request,omitempty"`
}
EditChatInviteLinkRequest holds the parameters for editChatInviteLink.
type EditChatSubscriptionInviteLinkRequest ¶
type EditChatSubscriptionInviteLinkRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// The invite link to edit
InviteLink string `json:"invite_link"`
// Invite link name; 0-32 characters
Name string `json:"name,omitempty"`
}
EditChatSubscriptionInviteLinkRequest holds the parameters for editChatSubscriptionInviteLink.
type EditForumTopicRequest ¶
type EditForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the target message thread of the forum topic
MessageThreadID int64 `json:"message_thread_id"`
// New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept.
Name string `json:"name,omitempty"`
// New unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept.
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
}
EditForumTopicRequest holds the parameters for editForumTopic.
type EditGeneralForumTopicRequest ¶
type EditGeneralForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// New topic name, 1-128 characters
Name string `json:"name"`
}
EditGeneralForumTopicRequest holds the parameters for editGeneralForumTopic.
type EditMessageCaptionRequest ¶
type EditMessageCaptionRequest struct {
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
ChatID ChatID `json:"chat_id,omitzero"`
// Required if inline_message_id is not specified. Identifier of the message to edit.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// New caption of the message, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the message caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media. Supported only for animation, photo and video messages.
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// A JSON-serialized object for an inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
EditMessageCaptionRequest holds the parameters for editMessageCaption.
type EditMessageChecklistRequest ¶
type EditMessageChecklistRequest struct {
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier for the target chat or username of the target bot in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the target message
MessageID int64 `json:"message_id"`
// A JSON-serialized object for the new checklist
Checklist *InputChecklist `json:"checklist"`
// A JSON-serialized object for the new inline keyboard for the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
EditMessageChecklistRequest holds the parameters for editMessageChecklist.
type EditMessageLiveLocationRequest ¶
type EditMessageLiveLocationRequest struct {
// Latitude of new location
Latitude float64 `json:"latitude"`
// Longitude of new location
Longitude float64 `json:"longitude"`
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
ChatID ChatID `json:"chat_id,omitzero"`
// Required if inline_message_id is not specified. Identifier of the message to edit.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current live_period by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then live_period remains unchanged.
LivePeriod int64 `json:"live_period,omitempty"`
// The radius of uncertainty for the location, measured in meters; 0-1500
HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"`
// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
Heading int64 `json:"heading,omitempty"`
// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
ProximityAlertRadius int64 `json:"proximity_alert_radius,omitempty"`
// A JSON-serialized object for a new inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
EditMessageLiveLocationRequest holds the parameters for editMessageLiveLocation.
type EditMessageMediaRequest ¶
type EditMessageMediaRequest struct {
// A JSON-serialized object for a new media content of the message
Media InputMedia `json:"media"`
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
ChatID ChatID `json:"chat_id,omitzero"`
// Required if inline_message_id is not specified. Identifier of the message to edit.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// A JSON-serialized object for a new inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
EditMessageMediaRequest holds the parameters for editMessageMedia.
type EditMessageOptions ¶
type EditMessageOptions struct {
ParseMode string
Entities []Entity
LinkPreviewOptions *LinkPreviewOptions
ReplyMarkup *InlineKeyboardMarkup
// BusinessConnectionID is normally left unset — [Message.EditText]
// auto-propagates the source message's own BusinessConnectionID, so
// this only needs setting explicitly to override that.
BusinessConnectionID string
}
EditMessageOptions carries the optional parameters of editMessageText for Message.EditText / Ctx.EditText.
type EditMessageReplyMarkupRequest ¶
type EditMessageReplyMarkupRequest struct {
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
ChatID ChatID `json:"chat_id,omitzero"`
// Required if inline_message_id is not specified. Identifier of the message to edit.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// A JSON-serialized object for an inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
EditMessageReplyMarkupRequest holds the parameters for editMessageReplyMarkup.
type EditMessageTextRequest ¶
type EditMessageTextRequest struct {
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
ChatID ChatID `json:"chat_id,omitzero"`
// Required if inline_message_id is not specified. Identifier of the message to edit.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// New text of the message, 1-4096 characters after entity parsing; required if rich_message isn't specified
Text string `json:"text,omitempty"`
// Mode for parsing entities in the message text. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
Entities []MessageEntity `json:"entities,omitempty"`
// Link preview generation options for the message
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
// New rich content of the message; required if text isn't specified
RichMessage *InputRichMessage `json:"rich_message,omitempty"`
// A JSON-serialized object for an inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
EditMessageTextRequest holds the parameters for editMessageText.
type EditStoryRequest ¶
type EditStoryRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the story to edit
StoryID int64 `json:"story_id"`
// Content of the story
Content InputStoryContent `json:"content"`
// Caption of the story, 0-2048 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the story caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// A JSON-serialized list of clickable areas to be shown on the story
Areas []StoryArea `json:"areas,omitempty"`
}
EditStoryRequest holds the parameters for editStory.
type EditUserStarSubscriptionRequest ¶
type EditUserStarSubscriptionRequest struct {
// Identifier of the user whose subscription will be edited
UserID int64 `json:"user_id"`
// Telegram payment identifier for the subscription
TelegramPaymentChargeID string `json:"telegram_payment_charge_id"`
// Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot.
IsCanceled bool `json:"is_canceled"`
}
EditUserStarSubscriptionRequest holds the parameters for editUserStarSubscription.
type EncryptedCredentials ¶
type EncryptedCredentials struct {
// Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication
Data string `json:"data"`
// Base64-encoded data hash for data authentication
Hash string `json:"hash"`
// Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption
Secret string `json:"secret"`
}
Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.
type EncryptedPassportElement ¶
type EncryptedPassportElement struct {
// Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”.
Type string `json:"type"`
// Optional. Base64-encoded encrypted Telegram Passport element data provided by the user; available only for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials.
Data string `json:"data,omitempty"`
// Optional. User's verified phone number; available only for “phone_number” type
PhoneNumber string `json:"phone_number,omitempty"`
// Optional. User's verified email address; available only for “email” type
Email string `json:"email,omitempty"`
// Optional. Array of encrypted files with documents provided by the user; available only for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
Files []PassportFile `json:"files,omitempty"`
// Optional. Encrypted file with the front side of the document, provided by the user; available only for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
FrontSide *PassportFile `json:"front_side,omitempty"`
// Optional. Encrypted file with the reverse side of the document, provided by the user; available only for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
ReverseSide *PassportFile `json:"reverse_side,omitempty"`
// Optional. Encrypted file with the selfie of the user holding a document, provided by the user; available if requested for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
Selfie *PassportFile `json:"selfie,omitempty"`
// Optional. Array of encrypted files with translated versions of documents provided by the user; available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
Translation []PassportFile `json:"translation,omitempty"`
// Base64-encoded element hash for using in PassportElementErrorUnspecified
Hash string `json:"hash"`
}
Describes documents or other Telegram Passport elements shared with the bot by the user.
type Entity ¶
type Entity = MessageEntity
Entity is golagram's historical name for MessageEntity — a special entity in a message's text (mention, hashtag, command, URL, formatting, ...). The struct itself is generated (types.gen.go) with the full spec field set: Type, Offset, Length, URL, User, Language, CustomEmojiID, ... — the old hand-written 3-field version silently dropped text_link URLs and text_mention users.
type EntitySegment ¶
EntitySegment is one contiguous run of text annotated with every entity that covers it in full.
func EntitySegments ¶
func EntitySegments(text string, entities []Entity) []EntitySegment
EntitySegments splits text at every entity boundary — the reverse of the Node formatting builder: instead of building text+entities from a tree, this walks existing text+entities into segments a caller can render or re-process (re-emit as Markdown/HTML, strip one entity type, ...). Each segment's Entities is exactly the set covering it in full; a segment covered by two overlapping entities (Bot API 6.0+ allows entities to nest) carries both, one covered by none is plain text with a nil slice. Offsets/lengths are UTF-16 code units, matching entities themselves; out-of-range entities are clipped to text's bounds rather than dropped or causing a panic.
type ErrorHandlerFunc ¶
ErrorHandlerFunc is called with a handler's error and the Ctx it failed on.
type ExportChatInviteLinkRequest ¶
type ExportChatInviteLinkRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
}
ExportChatInviteLinkRequest holds the parameters for exportChatInviteLink.
type ExternalReplyInfo ¶
type ExternalReplyInfo struct {
// Origin of the message replied to by the given message
Origin MessageOrigin `json:"origin"`
// Optional. Chat the original message belongs to. Available only if the chat is a supergroup or a channel.
Chat *Chat `json:"chat,omitempty"`
// Optional. Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel.
MessageID int64 `json:"message_id,omitempty"`
// Optional. Options used for link preview generation for the original message, if it is a text message
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
// Optional. Message is an animation, information about the animation
Animation *Animation `json:"animation,omitempty"`
// Optional. Message is an audio file, information about the file
Audio *Audio `json:"audio,omitempty"`
// Optional. Message is a general file, information about the file
Document *Document `json:"document,omitempty"`
// Optional. Message is a live photo, information about the live photo
LivePhoto *LivePhoto `json:"live_photo,omitempty"`
// Optional. Message contains paid media; information about the paid media
PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"`
// Optional. Message is a photo, available sizes of the photo
Photo []PhotoSize `json:"photo,omitempty"`
// Optional. Message is a sticker, information about the sticker
Sticker *Sticker `json:"sticker,omitempty"`
// Optional. Message is a forwarded story
Story *Story `json:"story,omitempty"`
// Optional. Message is a video, information about the video
Video *Video `json:"video,omitempty"`
// Optional. Message is a video note, information about the video message
VideoNote *VideoNote `json:"video_note,omitempty"`
// Optional. Message is a voice message, information about the file
Voice *Voice `json:"voice,omitempty"`
// Optional. True, if the message media is covered by a spoiler animation
HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"`
// Optional. Message is a checklist
Checklist *Checklist `json:"checklist,omitempty"`
// Optional. Message is a shared contact, information about the contact
Contact *Contact `json:"contact,omitempty"`
// Optional. Message is a dice with random value
Dice *Dice `json:"dice,omitempty"`
// Optional. Message is a game, information about the game. More about games »
Game *Game `json:"game,omitempty"`
// Optional. Message is a scheduled giveaway, information about the giveaway
Giveaway *Giveaway `json:"giveaway,omitempty"`
// Optional. A giveaway with public winners was completed
GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"`
// Optional. Message is an invoice for a payment, information about the invoice. More about payments »
Invoice *Invoice `json:"invoice,omitempty"`
// Optional. Message is a shared location, information about the location
Location *Location `json:"location,omitempty"`
// Optional. Message is a native poll, information about the poll
Poll *Poll `json:"poll,omitempty"`
// Optional. Message is a venue, information about the venue
Venue *Venue `json:"venue,omitempty"`
}
This object contains information about a message that is being replied to, which may come from another chat or forum topic.
func (*ExternalReplyInfo) UnmarshalJSON ¶
func (v *ExternalReplyInfo) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes ExternalReplyInfo's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type FSMContext ¶
type FSMContext struct {
// contains filtered or unexported fields
}
FSMContext is a handle bound to one conversation. Get it via Ctx.FSM, Message.FSM, or CallbackQuery.FSM — handlers don't construct it directly. It carries the context it was created under, so storage calls are canceled with the handler/bot without threading a ctx through every call site.
func NewFSMContext ¶
func NewFSMContext(ctx context.Context, storage FSMStorage, key StorageKey) *FSMContext
NewFSMContext builds a handle for an arbitrary conversation. Handlers get theirs from Ctx.FSM — this is for reaching *someone else's* state (an admin command inspecting or resetting another user's conversation) and for exercising an FSMStorage implementation directly (fsmtest does this).
func (*FSMContext) Clear ¶
func (f *FSMContext) Clear() error
Clear resets state and data, ending the conversation.
func (*FSMContext) Data ¶
func (f *FSMContext) Data() (map[string]any, error)
Data returns the conversation's stored data map, or an empty map if nothing has been stored yet. See FSMGet to read one key with a concrete type instead of handling the map directly.
func (*FSMContext) Key ¶
func (f *FSMContext) Key() StorageKey
Key returns the StorageKey this handle is scoped to — useful for logging and for storage implementations' own diagnostics.
func (*FSMContext) SetData ¶
func (f *FSMContext) SetData(data map[string]any) error
SetData replaces the conversation's entire data map. Use FSMContext.UpdateData (or FSMSet) instead to change one key without discarding the rest.
func (*FSMContext) SetState ¶
func (f *FSMContext) SetState(state State) error
SetState sets the conversation state, advancing (or resetting) which step the conversation is on.
func (*FSMContext) State ¶
func (f *FSMContext) State() (State, error)
State returns the current conversation state, or NoState if none is set.
func (*FSMContext) UpdateData ¶
UpdateData merges partial into the conversation's stored data (adding or overwriting only the given keys) and returns the resulting full map.
type FSMKeyStrategy ¶
type FSMKeyStrategy int
FSMKeyStrategy controls how conversation state is scoped — which updates share one FSM key. The default, FSMKeyChatUser, gives each user independent state in each chat.
const ( // FSMKeyChatUser scopes state per {chat, user}: the same user talking // to the bot in two different groups is in two independent // conversations. The default. FSMKeyChatUser FSMKeyStrategy = iota // FSMKeyChat scopes state per chat: everyone in a group shares one // conversation state (collaborative flows, group games). FSMKeyChat // FSMKeyGlobalUser scopes state per user across all chats: a user // mid-conversation in private continues that same conversation if they // message the bot from a group. FSMKeyGlobalUser // FSMKeyUserInTopic scopes state per {chat, user, forum topic}: in a // forum supergroup, the same user gets independent state per topic. // Outside forum topics it behaves exactly like FSMKeyChatUser. FSMKeyUserInTopic )
type FSMStorage ¶
type FSMStorage interface {
SetState(ctx context.Context, key StorageKey, state State) error
GetState(ctx context.Context, key StorageKey) (State, error)
SetData(ctx context.Context, key StorageKey, data map[string]any) error
GetData(ctx context.Context, key StorageKey) (map[string]any, error)
UpdateData(ctx context.Context, key StorageKey, partial map[string]any) (map[string]any, error)
Clear(ctx context.Context, key StorageKey) error
}
FSMStorage persists conversation state and data per StorageKey. MemoryStorage is the only built-in implementation — implement this interface for a persistent backend, and verify it with fsmtest.Run.
The ctx is the handler's context (or the bot's run context for sugar calls) — a backend doing real I/O must respect its cancellation.
JSON round-trip contract: every value put into the data map must be marshalable with encoding/json, and a storage is allowed to persist the map as JSON. That means a value read back is only guaranteed to be the *JSON image* of what was stored: numbers may come back as float64, structs as map[string]any. Read through FSMGet — it converts the JSON image back to T — instead of type-asserting raw Data() values, and the same handler code works on every backend.
type File ¶
type File struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
// Optional. File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file.
FilePath string `json:"file_path,omitempty"`
}
This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile. The maximum file size to download is 20 MB
type Filter ¶
Filter is the single filter shape for every update kind: a predicate over the full Ctx, so filters can read the payload (c.Message, c.CallbackQuery, ...), the resolved chat/user (Ctx.Chat, Ctx.From), and — crucially — FSM state (StateIs works on callback queries, not just messages). A filter is only invoked after the registration's own kind check passed, so a filter passed to Router.Message can rely on c.Message being non-nil.
Naming rule: payload predicates carry the Filter prefix (FilterPhoto, FilterCommand, ...) — the bare nouns belong to the generated Bot API types and always will. Combinators (And, Or, Not) and FSM predicates (StateIs) are not payload checks and stay unprefixed.
Keep filters cheap. A filter runs inside TelegramBot's per-{chat,user} dispatch lock (the same one that keeps two updates from the same user from racing each other's FSM state), so a slow filter — one doing I/O, most commonly — stalls every other queued update for that user until it returns. AdminCache.FilterIsAdmin does exactly this on a cache miss; its own doc says so.
func And ¶
And combines filters so all of them must match. Rarely needed directly — multiple filters passed to a registration already AND — but useful inside Or.
func FilterAnimation ¶
func FilterAnimation() Filter
FilterAnimation matches a message carrying an animation (a GIF, or an H.264/MPEG-4 AVC video without sound).
func FilterBotBlocked ¶
func FilterBotBlocked() Filter
FilterBotBlocked matches a my_chat_member update in a private chat where the user blocked the bot — the signal to stop messaging them.
func FilterBotUnblocked ¶
func FilterBotUnblocked() Filter
FilterBotUnblocked matches a my_chat_member update in a private chat where the user unblocked the bot.
func FilterCallbackData ¶
FilterCallbackData matches a callback query whose data equals data exactly.
func FilterCallbackPrefix ¶
FilterCallbackPrefix matches callback data by prefix — the standard pattern for parameterized buttons like "buy:42". For typed payloads see NewCallbackData.
func FilterChatType ¶
FilterChatType matches updates whose resolved chat (c.Chat()) is one of the given types: "private", "group", "supergroup", "channel". The first thing every group bot needs.
func FilterCommand ¶
FilterCommand matches a bot command the way Telegram clients actually send them: "/start", "/start args...", and — in groups — "/start@my_bot". A mention addressed to a different bot does not match, so two bots in one group don't answer each other's commands. The command name itself is matched case-insensitively (clients happily send "/Start"); read arguments in the handler via c.Command().Args.
Reads text-or-caption, same as Ctx.Command — a photo captioned "/report spam" matches FilterCommand("report") exactly like a plain text "/report spam" message, which is how media-heavy bots (channel reposts, user reports on a photo) actually receive commands.
func FilterCommandStart ¶
func FilterCommandStart() Filter
FilterCommandStart matches the /start command — including deep links, where t.me/your_bot?start=ref_12345 arrives as "/start ref_12345". Read the payload in the handler via c.Command().Args:
r.Message(gg.FilterCommandStart()).Handle(func(c *gg.Ctx) error {
payload := c.Command().Args // "ref_12345", or "" for a plain /start
...
})
func FilterCommandStartDeepLink ¶
func FilterCommandStartDeepLink() Filter
FilterCommandStartDeepLink matches only a /start carrying a deep-link payload (t.me/your_bot?start=...), letting referral/deep-link flows route separately from a plain /start.
func FilterDice ¶
func FilterDice() Filter
FilterDice matches a message carrying a dice-style roll (dice, dart, basketball, ...) — see FilterDiceValue to match a specific outcome.
func FilterDiceValue ¶
FilterDiceValue matches a dice roll landing on any of the given values — e.g. FilterDiceValue(6) for a 🎲/🎯/🎳 six, or FilterDiceValue(1) for a "you lose" 🎰. Value ranges depend on the emoji (1-6 for dice/darts/bowling, 1-5 for basketball/football, 1-64 for the slot machine) — see Dice.Emoji to distinguish them if a handler cares which.
func FilterDocument ¶
func FilterDocument() Filter
FilterDocument matches a message carrying a document (a generic file).
func FilterFromSender ¶
FilterFromSender matches updates whose Ctx.Sender identity is any of the given IDs. Unlike FilterFromUser (which reads c.From() — Telegram's shared dummy user for an anonymous group admin or channel post, so no real ID ever matches one), this resolves through Sender() first: an anonymous admin matches by their group's chat ID and a channel post matches by the channel's ID, the only identity Telegram gives either of them. Use it to allow-list "posts from channel X" or "any anonymous admin of chat Y" the way FilterFromUser allow-lists real users — it is not a substitute for FilterFromUser when you specifically need a real person (an anonymous admin's actual account is never recoverable).
func FilterFromUser ¶
FilterFromUser matches updates from any of the given user IDs — admin commands, owner-only handlers.
func FilterFromUsername ¶
FilterFromUsername matches updates from any of the given @usernames — a leading "@" is accepted and ignored either side, and the comparison is case-insensitive, matching how Telegram itself treats usernames. Prefer FilterFromUser by numeric ID where possible: a username can be changed or dropped, a user ID never changes.
func FilterHasEntity ¶
FilterHasEntity matches a message (or the caption of a media message) carrying at least one entity of any of the given types — e.g. FilterHasEntity(gg.EntityURL) for "this message contains a link". The Entity* constants are in consts.gen.go; formatting-only ones (EntityBold, EntityItalic, ...) are about rendering, not content, and are what the Node formatting builder produces instead.
func FilterIsForwarded ¶
func FilterIsForwarded() Filter
FilterIsForwarded matches a message forwarded from somewhere else (forward_origin is set).
func FilterIsReply ¶
func FilterIsReply() Filter
FilterIsReply matches a message that replies to another message.
func FilterIsTopicMessage ¶
func FilterIsTopicMessage() Filter
FilterIsTopicMessage matches a message sent inside a forum topic.
func FilterJoined ¶
func FilterJoined() Filter
FilterJoined matches a chat_member/my_chat_member update where the user went from not-in-the-chat to in-the-chat — the "welcome new member" trigger.
func FilterLeft ¶
func FilterLeft() Filter
FilterLeft matches a chat_member/my_chat_member update where the user went from in-the-chat to not-in-the-chat (left or was banned).
func FilterLeftChatMember ¶
func FilterLeftChatMember() Filter
FilterLeftChatMember matches the service message announcing a user removed from (or leaving) a group.
func FilterLocation ¶
func FilterLocation() Filter
FilterLocation matches a message sharing a location.
func FilterMediaGroup ¶
func FilterMediaGroup() Filter
FilterMediaGroup matches a message that is part of an album (media group).
func FilterNewChatMembers ¶
func FilterNewChatMembers() Filter
FilterNewChatMembers matches the service message announcing users added to a group.
func FilterPhoto ¶
func FilterPhoto() Filter
FilterPhoto matches a message carrying at least one photo size.
func FilterPoll ¶
func FilterPoll() Filter
FilterPoll matches a message carrying a poll (the message announcing it, not a poll_answer or poll update — see Router.Poll).
func FilterPromotedToAdmin ¶
func FilterPromotedToAdmin() Filter
FilterPromotedToAdmin matches a chat_member/my_chat_member update where the user gained admin rights (member/restricted → administrator/creator).
func FilterRegexp ¶
FilterRegexp matches a message whose text (or caption, for media messages without text) matches re. Compile the pattern once at registration time — regexp.MustCompile(`^\d+$`) — not inside a handler.
func FilterSticker ¶
func FilterSticker() Filter
FilterSticker matches a message carrying a sticker.
func FilterSuccessfulPayment ¶
func FilterSuccessfulPayment() Filter
FilterSuccessfulPayment matches the service message confirming a completed payment — the message a payments bot fulfills orders from.
func FilterText ¶
FilterText matches a message whose text (or caption, for media messages without text) equals text exactly.
func FilterTextContains ¶
FilterTextContains matches a message whose text (or caption) contains substr.
func FilterTextEqualFold ¶
FilterTextEqualFold matches a message whose text (or caption) equals text, ignoring case. For prefix/suffix/contains, case-insensitivity is rare enough in practice that callers can fold both sides themselves: FilterRegexp(regexp.MustCompile(`(?i)^hi\b`)).
func FilterTextPrefix ¶
FilterTextPrefix matches a message whose text (or caption) starts with prefix.
func FilterTextSuffix ¶
FilterTextSuffix matches a message whose text (or caption) ends with suffix.
func FilterViaBot ¶
func FilterViaBot() Filter
FilterViaBot matches a message sent via an inline bot (via_bot is set).
func FilterVideoNote ¶
func FilterVideoNote() Filter
FilterVideoNote matches a message carrying a round video note.
func FilterWebAppData ¶
func FilterWebAppData() Filter
FilterWebAppData matches the service message carrying data sent from a Web App back to the bot.
func StateIn ¶
func StateIn(group StateGroup) Filter
StateIn matches if the current FSM state belongs to the given StateGroup — the whole conversation at once, without listing every step.
A storage error also matches false, logged the same way StateIs logs one.
func StateIs ¶
StateIs matches if the FSM state of whoever this update is from is one of the given states — on any update kind, so a conversational flow can route its callback-query steps by state exactly like its message steps. Pass AnyState to match any state other than NoState.
A storage error (the FSM backend is down) also matches false — an operator would otherwise see "bot ignores users mid-wizard" with no clue why, so the error is logged (via the bot's WithLogger, falling back to the standard logger) before returning false.
type ForceReply ¶
type ForceReply struct {
// Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply'
ForceReply bool `json:"force_reply"`
// Optional. The placeholder to be shown in the input field when the reply is active; 1-64 characters
InputFieldPlaceholder string `json:"input_field_placeholder,omitempty"`
// Optional. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.
Selective bool `json:"selective,omitempty"`
}
Upon 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'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode. Not supported in channels and for messages sent on behalf of a user account.
func NewForceReply ¶
func NewForceReply(placeholder string, selective bool) *ForceReply
NewForceReply builds a ForceReply markup. placeholder ("" for none) is shown in the input field while the reply is active; selective limits it to the mentioned/replied-to users.
type ForumTopic ¶
type ForumTopic struct {
// Unique identifier of the forum topic
MessageThreadID int64 `json:"message_thread_id"`
// Name of the topic
Name string `json:"name"`
// Color of the topic icon in RGB format
IconColor int64 `json:"icon_color"`
// Optional. Unique identifier of the custom emoji shown as the topic icon
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
// Optional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot
IsNameImplicit bool `json:"is_name_implicit,omitempty"`
}
This object represents a forum topic.
type ForumTopicClosed ¶
type ForumTopicClosed struct {
}
This object represents a service message about a forum topic closed in the chat. Currently holds no information.
type ForumTopicCreated ¶
type ForumTopicCreated struct {
// Name of the topic
Name string `json:"name"`
// Color of the topic icon in RGB format
IconColor int64 `json:"icon_color"`
// Optional. Unique identifier of the custom emoji shown as the topic icon
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
// Optional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot
IsNameImplicit bool `json:"is_name_implicit,omitempty"`
}
This object represents a service message about a new forum topic created in the chat.
type ForumTopicEdited ¶
type ForumTopicEdited struct {
// Optional. New name of the topic, if it was edited
Name string `json:"name,omitempty"`
// Optional. New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
}
This object represents a service message about an edited forum topic.
type ForumTopicReopened ¶
type ForumTopicReopened struct {
}
This object represents a service message about a forum topic reopened in the chat. Currently holds no information.
type ForwardMessageRequest ¶
type ForwardMessageRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username)
FromChatID ChatID `json:"from_chat_id"`
// Message identifier in the chat specified in from_chat_id
MessageID int64 `json:"message_id"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be forwarded; required if the message is forwarded to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// New start timestamp for the forwarded video in the message
VideoStartTimestamp int64 `json:"video_start_timestamp,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the forwarded message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Unique identifier of the message effect to be added to the message; only available when forwarding to private chats
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
}
ForwardMessageRequest holds the parameters for forwardMessage.
type ForwardMessagesRequest ¶
type ForwardMessagesRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username)
FromChatID ChatID `json:"from_chat_id"`
// A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order.
MessageIds []int64 `json:"message_ids"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the messages will be forwarded; required if the messages are forwarded to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Sends the messages silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the forwarded messages from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
}
ForwardMessagesRequest holds the parameters for forwardMessages.
type Game ¶
type Game struct {
// Title of the game
Title string `json:"title"`
// Description of the game
Description string `json:"description"`
// Photo that will be displayed in the game message in chats
Photo []PhotoSize `json:"photo"`
// Optional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters.
Text string `json:"text,omitempty"`
// Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc.
TextEntities []MessageEntity `json:"text_entities,omitempty"`
// Optional. Animation that will be displayed in the game message in chats. Upload via BotFather.
Animation *Animation `json:"animation,omitempty"`
}
This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.
type GameHighScore ¶
type GameHighScore struct {
// Position in high score table for the game
Position int64 `json:"position"`
// User
User *User `json:"user"`
// Score
Score int64 `json:"score"`
}
This object represents one row of the high scores table for a game.
type GeneralForumTopicHidden ¶
type GeneralForumTopicHidden struct {
}
This object represents a service message about General forum topic hidden in the chat. Currently holds no information.
type GeneralForumTopicUnhidden ¶
type GeneralForumTopicUnhidden struct {
}
This object represents a service message about General forum topic unhidden in the chat. Currently holds no information.
type GetBusinessAccountGiftsRequest ¶
type GetBusinessAccountGiftsRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Pass True to exclude gifts that aren't saved to the account's profile page
ExcludeUnsaved bool `json:"exclude_unsaved,omitempty"`
// Pass True to exclude gifts that are saved to the account's profile page
ExcludeSaved bool `json:"exclude_saved,omitempty"`
// Pass True to exclude gifts that can be purchased an unlimited number of times
ExcludeUnlimited bool `json:"exclude_unlimited,omitempty"`
// Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique
ExcludeLimitedUpgradable bool `json:"exclude_limited_upgradable,omitempty"`
// Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique
ExcludeLimitedNonUpgradable bool `json:"exclude_limited_non_upgradable,omitempty"`
// Pass True to exclude unique gifts
ExcludeUnique bool `json:"exclude_unique,omitempty"`
// Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram
ExcludeFromBlockchain bool `json:"exclude_from_blockchain,omitempty"`
// Pass True to sort results by gift price instead of send date. Sorting is applied before pagination.
SortByPrice bool `json:"sort_by_price,omitempty"`
// Offset of the first entry to return as received from the previous request; use empty string to get the first chunk of results
Offset string `json:"offset,omitempty"`
// The maximum number of gifts to be returned; 1-100. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
}
GetBusinessAccountGiftsRequest holds the parameters for getBusinessAccountGifts.
type GetBusinessAccountStarBalanceRequest ¶
type GetBusinessAccountStarBalanceRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
}
GetBusinessAccountStarBalanceRequest holds the parameters for getBusinessAccountStarBalance.
type GetBusinessConnectionRequest ¶
type GetBusinessConnectionRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
}
GetBusinessConnectionRequest holds the parameters for getBusinessConnection.
type GetChatAdministratorsRequest ¶
type GetChatAdministratorsRequest struct {
// Unique identifier for the target chat or username of the target supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Pass True to additionally receive all bots that are administrators of the chat. By default, bots other than the current bot are omitted.
ReturnBots bool `json:"return_bots,omitempty"`
}
GetChatAdministratorsRequest holds the parameters for getChatAdministrators.
type GetChatGiftsRequest ¶
type GetChatGiftsRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Pass True to exclude gifts that aren't saved to the chat's profile page. Always True, unless the bot has the can_post_messages administrator right in the channel.
ExcludeUnsaved bool `json:"exclude_unsaved,omitempty"`
// Pass True to exclude gifts that are saved to the chat's profile page. Always False, unless the bot has the can_post_messages administrator right in the channel.
ExcludeSaved bool `json:"exclude_saved,omitempty"`
// Pass True to exclude gifts that can be purchased an unlimited number of times
ExcludeUnlimited bool `json:"exclude_unlimited,omitempty"`
// Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique
ExcludeLimitedUpgradable bool `json:"exclude_limited_upgradable,omitempty"`
// Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique
ExcludeLimitedNonUpgradable bool `json:"exclude_limited_non_upgradable,omitempty"`
// Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram
ExcludeFromBlockchain bool `json:"exclude_from_blockchain,omitempty"`
// Pass True to exclude unique gifts
ExcludeUnique bool `json:"exclude_unique,omitempty"`
// Pass True to sort results by gift price instead of send date. Sorting is applied before pagination.
SortByPrice bool `json:"sort_by_price,omitempty"`
// Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results
Offset string `json:"offset,omitempty"`
// The maximum number of gifts to be returned; 1-100. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
}
GetChatGiftsRequest holds the parameters for getChatGifts.
type GetChatMemberCountRequest ¶
type GetChatMemberCountRequest struct {
// Unique identifier for the target chat or username of the target supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
}
GetChatMemberCountRequest holds the parameters for getChatMemberCount.
type GetChatMemberRequest ¶
type GetChatMemberRequest struct {
// Unique identifier for the target chat or username of the target supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
}
GetChatMemberRequest holds the parameters for getChatMember.
type GetChatMenuButtonRequest ¶
type GetChatMenuButtonRequest struct {
// Unique identifier for the target private chat. If not specified, the bot's default menu button will be returned.
ChatID int64 `json:"chat_id,omitempty"`
}
GetChatMenuButtonRequest holds the parameters for getChatMenuButton.
type GetChatRequest ¶
type GetChatRequest struct {
// Unique identifier for the target chat or username of the target supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
}
GetChatRequest holds the parameters for getChat.
type GetCustomEmojiStickersRequest ¶
type GetCustomEmojiStickersRequest struct {
// A JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.
CustomEmojiIds []string `json:"custom_emoji_ids"`
}
GetCustomEmojiStickersRequest holds the parameters for getCustomEmojiStickers.
type GetFileRequest ¶
type GetFileRequest struct {
// File identifier to get information about
FileID string `json:"file_id"`
}
GetFileRequest holds the parameters for getFile.
type GetGameHighScoresRequest ¶
type GetGameHighScoresRequest struct {
// Target user id
UserID int64 `json:"user_id"`
// Required if inline_message_id is not specified. Unique identifier for the target chat.
ChatID int64 `json:"chat_id,omitempty"`
// Required if inline_message_id is not specified. Identifier of the sent message.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
}
GetGameHighScoresRequest holds the parameters for getGameHighScores.
type GetManagedBotAccessSettingsRequest ¶
type GetManagedBotAccessSettingsRequest struct {
// User identifier of the managed bot whose access settings will be returned
UserID int64 `json:"user_id"`
}
GetManagedBotAccessSettingsRequest holds the parameters for getManagedBotAccessSettings.
type GetManagedBotTokenRequest ¶
type GetManagedBotTokenRequest struct {
// User identifier of the managed bot whose token will be returned
UserID int64 `json:"user_id"`
}
GetManagedBotTokenRequest holds the parameters for getManagedBotToken.
type GetMyCommandsRequest ¶
type GetMyCommandsRequest struct {
// A JSON-serialized object, describing scope of users. Defaults to BotCommandScopeDefault.
Scope BotCommandScope `json:"scope,omitempty"`
// A two-letter ISO 639-1 language code or an empty string
LanguageCode string `json:"language_code,omitempty"`
}
GetMyCommandsRequest holds the parameters for getMyCommands.
type GetMyDefaultAdministratorRightsRequest ¶
type GetMyDefaultAdministratorRightsRequest struct {
// Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned.
ForChannels bool `json:"for_channels,omitempty"`
}
GetMyDefaultAdministratorRightsRequest holds the parameters for getMyDefaultAdministratorRights.
type GetMyDescriptionRequest ¶
type GetMyDescriptionRequest struct {
// A two-letter ISO 639-1 language code or an empty string
LanguageCode string `json:"language_code,omitempty"`
}
GetMyDescriptionRequest holds the parameters for getMyDescription.
type GetMyNameRequest ¶
type GetMyNameRequest struct {
// A two-letter ISO 639-1 language code or an empty string
LanguageCode string `json:"language_code,omitempty"`
}
GetMyNameRequest holds the parameters for getMyName.
type GetMyShortDescriptionRequest ¶
type GetMyShortDescriptionRequest struct {
// A two-letter ISO 639-1 language code or an empty string
LanguageCode string `json:"language_code,omitempty"`
}
GetMyShortDescriptionRequest holds the parameters for getMyShortDescription.
type GetStarTransactionsRequest ¶
type GetStarTransactionsRequest struct {
// Number of transactions to skip in the response
Offset int64 `json:"offset,omitempty"`
// The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
}
GetStarTransactionsRequest holds the parameters for getStarTransactions.
type GetStickerSetRequest ¶
type GetStickerSetRequest struct {
// Name of the sticker set
Name string `json:"name"`
}
GetStickerSetRequest holds the parameters for getStickerSet.
type GetUpdatesRequest ¶
type GetUpdatesRequest struct {
// Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten.
Offset int64 `json:"offset,omitempty"`
// Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
// Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
Timeout int64 `json:"timeout,omitempty"`
// A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to getUpdates, so unwanted updates may be received for a short period of time.
AllowedUpdates []string `json:"allowed_updates,omitempty"`
}
GetUpdatesRequest holds the parameters for getUpdates.
type GetUserChatBoostsRequest ¶
type GetUserChatBoostsRequest struct {
// Unique identifier for the chat or username of the channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
}
GetUserChatBoostsRequest holds the parameters for getUserChatBoosts.
type GetUserGiftsRequest ¶
type GetUserGiftsRequest struct {
// Unique identifier of the user
UserID int64 `json:"user_id"`
// Pass True to exclude gifts that can be purchased an unlimited number of times
ExcludeUnlimited bool `json:"exclude_unlimited,omitempty"`
// Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique
ExcludeLimitedUpgradable bool `json:"exclude_limited_upgradable,omitempty"`
// Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique
ExcludeLimitedNonUpgradable bool `json:"exclude_limited_non_upgradable,omitempty"`
// Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram
ExcludeFromBlockchain bool `json:"exclude_from_blockchain,omitempty"`
// Pass True to exclude unique gifts
ExcludeUnique bool `json:"exclude_unique,omitempty"`
// Pass True to sort results by gift price instead of send date. Sorting is applied before pagination.
SortByPrice bool `json:"sort_by_price,omitempty"`
// Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results
Offset string `json:"offset,omitempty"`
// The maximum number of gifts to be returned; 1-100. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
}
GetUserGiftsRequest holds the parameters for getUserGifts.
type GetUserPersonalChatMessagesRequest ¶
type GetUserPersonalChatMessagesRequest struct {
// Unique identifier for the target user
UserID int64 `json:"user_id"`
// The maximum number of messages to return; 1-20
Limit int64 `json:"limit"`
}
GetUserPersonalChatMessagesRequest holds the parameters for getUserPersonalChatMessages.
type GetUserProfileAudiosRequest ¶
type GetUserProfileAudiosRequest struct {
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Sequential number of the first audio to be returned. By default, all audios are returned.
Offset int64 `json:"offset,omitempty"`
// Limits the number of audios to be retrieved. Values between 1-100 are accepted. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
}
GetUserProfileAudiosRequest holds the parameters for getUserProfileAudios.
type GetUserProfilePhotosRequest ¶
type GetUserProfilePhotosRequest struct {
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Sequential number of the first photo to be returned. By default, all photos are returned.
Offset int64 `json:"offset,omitempty"`
// Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100.
Limit int64 `json:"limit,omitempty"`
}
GetUserProfilePhotosRequest holds the parameters for getUserProfilePhotos.
type Gift ¶
type Gift struct {
// Unique identifier of the gift
ID string `json:"id"`
// The sticker that represents the gift
Sticker *Sticker `json:"sticker"`
// The number of Telegram Stars that must be paid to send the sticker
StarCount int64 `json:"star_count"`
// Optional. The number of Telegram Stars that must be paid to upgrade the gift to a unique one
UpgradeStarCount int64 `json:"upgrade_star_count,omitempty"`
// Optional. True, if the gift can only be purchased by Telegram Premium subscribers
IsPremium bool `json:"is_premium,omitempty"`
// Optional. True, if the gift can be used (after being upgraded) to customize a user's appearance
HasColors bool `json:"has_colors,omitempty"`
// Optional. The total number of gifts of this type that can be sent by all users; for limited gifts only
TotalCount int64 `json:"total_count,omitempty"`
// Optional. The number of remaining gifts of this type that can be sent by all users; for limited gifts only
RemainingCount int64 `json:"remaining_count,omitempty"`
// Optional. The total number of gifts of this type that can be sent by the bot; for limited gifts only
PersonalTotalCount int64 `json:"personal_total_count,omitempty"`
// Optional. The number of remaining gifts of this type that can be sent by the bot; for limited gifts only
PersonalRemainingCount int64 `json:"personal_remaining_count,omitempty"`
// Optional. Background of the gift
Background *GiftBackground `json:"background,omitempty"`
// Optional. The total number of different unique gifts that can be obtained by upgrading the gift
UniqueGiftVariantCount int64 `json:"unique_gift_variant_count,omitempty"`
// Optional. Information about the chat that published the gift
PublisherChat *Chat `json:"publisher_chat,omitempty"`
}
This object represents a gift that can be sent by the bot.
type GiftBackground ¶
type GiftBackground struct {
// Center color of the background in RGB format
CenterColor int64 `json:"center_color"`
// Edge color of the background in RGB format
EdgeColor int64 `json:"edge_color"`
// Text color of the background in RGB format
TextColor int64 `json:"text_color"`
}
This object describes the background of a gift.
type GiftInfo ¶
type GiftInfo struct {
// Information about the gift
Gift *Gift `json:"gift"`
// Optional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts
OwnedGiftID string `json:"owned_gift_id,omitempty"`
// Optional. Number of Telegram Stars that can be claimed by the receiver by converting the gift; omitted if conversion to Telegram Stars is impossible
ConvertStarCount int64 `json:"convert_star_count,omitempty"`
// Optional. Number of Telegram Stars that were prepaid for the ability to upgrade the gift
PrepaidUpgradeStarCount int64 `json:"prepaid_upgrade_star_count,omitempty"`
// Optional. True, if the gift's upgrade was purchased after the gift was sent
IsUpgradeSeparate bool `json:"is_upgrade_separate,omitempty"`
// Optional. True, if the gift can be upgraded to a unique gift
CanBeUpgraded bool `json:"can_be_upgraded,omitempty"`
// Optional. Text of the message that was added to the gift
Text string `json:"text,omitempty"`
// Optional. Special entities that appear in the text
Entities []MessageEntity `json:"entities,omitempty"`
// Optional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them
IsPrivate bool `json:"is_private,omitempty"`
// Optional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift.
UniqueGiftNumber int64 `json:"unique_gift_number,omitempty"`
}
Describes a service message about a regular gift that was sent or received.
type GiftPremiumSubscriptionRequest ¶
type GiftPremiumSubscriptionRequest struct {
// Unique identifier of the target user who will receive a Telegram Premium subscription
UserID int64 `json:"user_id"`
// Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12
MonthCount int64 `json:"month_count"`
// Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months
StarCount int64 `json:"star_count"`
// Text that will be shown along with the service message about the subscription; 0-128 characters
Text string `json:"text,omitempty"`
// Mode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
TextParseMode string `json:"text_parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
TextEntities []MessageEntity `json:"text_entities,omitempty"`
}
GiftPremiumSubscriptionRequest holds the parameters for giftPremiumSubscription.
type Gifts ¶
type Gifts struct {
// The list of gifts
Gifts []Gift `json:"gifts"`
}
This object represent a list of gifts.
type Giveaway ¶
type Giveaway struct {
// The list of chats which the user must join to participate in the giveaway
Chats []Chat `json:"chats"`
// Point in time (Unix timestamp) when winners of the giveaway will be selected
WinnersSelectionDate int64 `json:"winners_selection_date"`
// The number of users which are supposed to be selected as winners of the giveaway
WinnerCount int64 `json:"winner_count"`
// Optional. True, if only users who join the chats after the giveaway started should be eligible to win
OnlyNewMembers bool `json:"only_new_members,omitempty"`
// Optional. True, if the list of giveaway winners will be visible to everyone
HasPublicWinners bool `json:"has_public_winners,omitempty"`
// Optional. Description of additional giveaway prize
PrizeDescription string `json:"prize_description,omitempty"`
// Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways.
CountryCodes []string `json:"country_codes,omitempty"`
// Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
PrizeStarCount int64 `json:"prize_star_count,omitempty"`
// Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only
PremiumSubscriptionMonthCount int64 `json:"premium_subscription_month_count,omitempty"`
}
This object represents a message about a scheduled giveaway.
type GiveawayCompleted ¶
type GiveawayCompleted struct {
// Number of winners in the giveaway
WinnerCount int64 `json:"winner_count"`
// Optional. Number of undistributed prizes
UnclaimedPrizeCount int64 `json:"unclaimed_prize_count,omitempty"`
// Optional. Message with the giveaway that was completed, if it wasn't deleted
GiveawayMessage *Message `json:"giveaway_message,omitempty"`
// Optional. True, if the giveaway is a Telegram Star giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway.
IsStarGiveaway bool `json:"is_star_giveaway,omitempty"`
}
This object represents a service message about the completion of a giveaway without public winners.
type GiveawayCreated ¶
type GiveawayCreated struct {
// Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
PrizeStarCount int64 `json:"prize_star_count,omitempty"`
}
This object represents a service message about the creation of a scheduled giveaway.
type GiveawayWinners ¶
type GiveawayWinners struct {
// The chat that created the giveaway
Chat *Chat `json:"chat"`
// Identifier of the message with the giveaway in the chat
GiveawayMessageID int64 `json:"giveaway_message_id"`
// Point in time (Unix timestamp) when winners of the giveaway were selected
WinnersSelectionDate int64 `json:"winners_selection_date"`
// Total number of winners in the giveaway
WinnerCount int64 `json:"winner_count"`
// List of up to 100 winners of the giveaway
Winners []User `json:"winners"`
// Optional. The number of other chats the user had to join in order to be eligible for the giveaway
AdditionalChatCount int64 `json:"additional_chat_count,omitempty"`
// Optional. The number of Telegram Stars that were split between giveaway winners; for Telegram Star giveaways only
PrizeStarCount int64 `json:"prize_star_count,omitempty"`
// Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only
PremiumSubscriptionMonthCount int64 `json:"premium_subscription_month_count,omitempty"`
// Optional. Number of undistributed prizes
UnclaimedPrizeCount int64 `json:"unclaimed_prize_count,omitempty"`
// Optional. True, if only users who had joined the chats after the giveaway started were eligible to win
OnlyNewMembers bool `json:"only_new_members,omitempty"`
// Optional. True, if the giveaway was canceled because the payment for it was refunded
WasRefunded bool `json:"was_refunded,omitempty"`
// Optional. Description of additional giveaway prize
PrizeDescription string `json:"prize_description,omitempty"`
}
This object represents a message about the completion of a giveaway with public winners.
type HandlerFunc ¶
HandlerFunc is what every handler looks like, regardless of update kind. Ctx exposes whichever payload this update carries (c.Message, c.CallbackQuery, c.InlineQuery, ...) plus sugar (Ctx.Answer, Ctx.FSM, ...).
type HealthGate ¶
HealthGate reports whether an incoming /health or /healthz request should be served. Return false to reject it — HealthMonitor.StartHealthServer responds 403 instead of serving the status. Passing none (the default) serves every request unauthenticated.
type HealthMonitor ¶
type HealthMonitor struct {
// contains filtered or unexported fields
}
HealthMonitor tracks the bot's dispatch and error counters.
func NewHealthMonitor ¶
func NewHealthMonitor() *HealthMonitor
NewHealthMonitor creates a health monitor with all counters at zero and its start time set to now.
func (*HealthMonitor) GetStatus ¶
func (hm *HealthMonitor) GetStatus() HealthStatus
GetStatus returns the current counters.
func (*HealthMonitor) HealthCheckHandler ¶
func (hm *HealthMonitor) HealthCheckHandler() http.HandlerFunc
HealthCheckHandler returns an HTTP handler for health checks, open to any request that can reach it — no auth of its own. LastError frequently contains chat IDs, user IDs, or upstream error text (whatever a handler returned), so bind this to localhost, put auth in front, or pass a HealthGate to HealthMonitor.StartHealthServer before exposing it on a public address.
func (*HealthMonitor) IncrementDispatched ¶
func (hm *HealthMonitor) IncrementDispatched(kind string)
IncrementDispatched counts an update entering dispatch, whether or not any handler ends up matching it, broken down by kind (e.g. "message", "callback_query" — see Update.Kind).
func (*HealthMonitor) IncrementMatched ¶
func (hm *HealthMonitor) IncrementMatched(kind string)
IncrementMatched counts an update a handler matched, broken down by kind.
func (*HealthMonitor) IncrementUnmatched ¶
func (hm *HealthMonitor) IncrementUnmatched(kind string)
IncrementUnmatched counts an update that no registered handler matched, broken down by kind.
func (*HealthMonitor) RecordError ¶
func (hm *HealthMonitor) RecordError(err error)
RecordError records a handler error.
func (*HealthMonitor) StartHealthServer ¶
func (hm *HealthMonitor) StartHealthServer(ctx context.Context, addr string, gate ...HealthGate) error
StartHealthServer serves /health and /healthz on addr until ctx is canceled, then shuts down gracefully. It blocks; run it in a goroutine (TelegramBot.StartHealthServer does).
gate, if given, is checked on every request; a false return responds 403 instead of serving the status — a lightweight alternative to a reverse proxy or auth middleware when addr is reachable from outside a trusted network. Without one, /health and /healthz serve unauthenticated to anyone who can reach addr — see [HealthCheckHandler]'s doc for what that exposes.
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status"` // always "ok" while the process serves
Uptime string `json:"uptime"`
UptimeSeconds int64 `json:"uptime_seconds"`
StartTime time.Time `json:"start_time"`
UpdatesDispatched int64 `json:"updates_dispatched"` // updates that entered dispatch
HandlersMatched int64 `json:"handlers_matched"` // updates a handler matched
UpdatesUnmatched int64 `json:"updates_unmatched"` // updates no handler matched
ErrorsCount int64 `json:"errors_count"` // handler errors
LastError string `json:"last_error"`
LastErrorTime string `json:"last_error_time"`
// DispatchedByKind/MatchedByKind/UnmatchedByKind break the three
// aggregate counters above down by update kind (e.g. "message",
// "callback_query") — e.g. spotting that inline_query updates are
// arriving but never matching, when the aggregate counters alone
// wouldn't show which kind that is.
DispatchedByKind map[string]int64 `json:"dispatched_by_kind,omitempty"`
MatchedByKind map[string]int64 `json:"matched_by_kind,omitempty"`
UnmatchedByKind map[string]int64 `json:"unmatched_by_kind,omitempty"`
}
HealthStatus is a raw-numbers health report. golagram reports what happened and lets operators decide what "unhealthy" means for their bot — invented thresholds in a library are a lie waiting to page someone.
type HideGeneralForumTopicRequest ¶
type HideGeneralForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
}
HideGeneralForumTopicRequest holds the parameters for hideGeneralForumTopic.
type I18n ¶
type I18n struct {
// contains filtered or unexported fields
}
I18n is the built-in Translator: locale → key → template maps with per-key fallback (exact locale → base language → default locale → the key itself, so a missing translation stays visible instead of blank) and CLDR-style plural selection.
Configure it fully before the bot starts — I18n.Add / I18n.SetPluralRule are not safe to call concurrently with dispatch.
func NewI18n ¶
NewI18n creates a translator that falls back to defaultLocale for updates whose locale is unknown or untranslated.
func (*I18n) Add ¶
Add registers (or extends) a locale's messages. Plural variants use key suffixes: "apples.one", "apples.few", "apples.many", "apples.other".
func (*I18n) AddJSON ¶
AddJSON is Add for a JSON object ({"key": "template", ...}) — the shape a per-locale file naturally holds.
func (*I18n) DefaultLocale ¶
DefaultLocale implements Translator.
func (*I18n) SetPluralRule ¶
func (t *I18n) SetPluralRule(locale string, rule PluralRule) *I18n
SetPluralRule overrides the plural rule for a base language. Built-in rules cover the Germanic/Turkic one/other split (the default: n==1 → one) and the Slavic one/few/many system (ru, uk, be, sr, hr, bs) — anything else needs a rule set here.
type InaccessibleMessage ¶
type InaccessibleMessage struct {
// Chat the message belonged to
Chat *Chat `json:"chat"`
// Unique message identifier inside the chat
MessageID int64 `json:"message_id"`
// Always 0. The field can be used to differentiate regular and inaccessible messages.
Date int64 `json:"date"`
}
This object describes a message that was deleted or is otherwise inaccessible to the bot.
type InlineKeyboard ¶
type InlineKeyboard struct {
// contains filtered or unexported fields
}
InlineKeyboard is a stepwise builder for an InlineKeyboardMarkup: add buttons via Row, Add, and/or Insert in any combination, then call Build.
func NewInlineKeyboard ¶
func NewInlineKeyboard() *InlineKeyboard
NewInlineKeyboard creates an empty inline keyboard builder.
func (*InlineKeyboard) Add ¶
func (kb *InlineKeyboard) Add(buttons ...InlineKeyboardButton) *InlineKeyboard
Add appends buttons to the keyboard, each on its own row — for a simple single-column list of buttons. See Row to group buttons onto one row instead.
func (*InlineKeyboard) Adjust ¶
func (kb *InlineKeyboard) Adjust(sizes ...int) *InlineKeyboard
Adjust re-flows every button added so far into rows of the given sizes: sizes apply in order and the last one repeats for the remaining buttons. Adjust(2) lays everything out two per row; Adjust(1, 2) puts one button on the first row and two on each row after. Call it last, before Build — it replaces whatever row structure InlineKeyboard.Row / InlineKeyboard.Add / InlineKeyboard.Insert created:
kb := gg.NewInlineKeyboard()
for _, item := range items {
kb.Insert(gg.NewInlineButton(item.Name, item.ID))
}
markup := kb.Adjust(2).Build()
func (*InlineKeyboard) Build ¶
func (kb *InlineKeyboard) Build() *InlineKeyboardMarkup
Build finishes any row still under construction (see Insert) and returns the resulting InlineKeyboardMarkup.
func (*InlineKeyboard) Insert ¶
func (kb *InlineKeyboard) Insert(button InlineKeyboardButton) *InlineKeyboard
Insert appends button to the row currently under construction; the next call to Row (with no arguments) or to Build finishes it.
func (*InlineKeyboard) Row ¶
func (kb *InlineKeyboard) Row(buttons ...InlineKeyboardButton) *InlineKeyboard
Row appends buttons together as one new row, first finishing off any row already under construction via Insert.
type InlineKeyboardButton ¶
type InlineKeyboardButton struct {
// Label text on the button
Text string `json:"text"`
// Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
// Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used.
Style string `json:"style,omitempty"`
// Optional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings.
URL string `json:"url,omitempty"`
// Optional. Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes
CallbackData string `json:"callback_data,omitempty"`
// Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account.
WebApp *WebAppInfo `json:"web_app,omitempty"`
// Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.
LoginURL *LoginURL `json:"login_url,omitempty"`
// Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account.
SwitchInlineQuery string `json:"switch_inline_query,omitempty"`
// Optional. If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted. This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account.
SwitchInlineQueryCurrentChat string `json:"switch_inline_query_current_chat,omitempty"`
// Optional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent in channel direct messages chats and on behalf of a business account.
SwitchInlineQueryChosenChat *SwitchInlineQueryChosenChat `json:"switch_inline_query_chosen_chat,omitempty"`
// Optional. Description of the button that copies the specified text to the clipboard
CopyText *CopyTextButton `json:"copy_text,omitempty"`
// Optional. Description of the game that will be launched when the user presses the button. NOTE: This type of button must always be the first button in the first row.
CallbackGame *CallbackGame `json:"callback_game,omitempty"`
// Optional. Specify True, to send a Pay button. Substrings “⭐” and “XTR” in the buttons's text will be replaced with a Telegram Star icon. NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages.
Pay bool `json:"pay,omitempty"`
}
This object represents one button of an inline keyboard. Exactly one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button.
func NewInlineButton ¶
func NewInlineButton(text, callbackData string) InlineKeyboardButton
NewInlineButton creates a callback-query button: pressing it delivers callbackData back to the bot as CallbackQuery.Data.
func NewInlineButtonSwitchInline ¶
func NewInlineButtonSwitchInline(text, query string) InlineKeyboardButton
NewInlineButtonSwitchInline creates a button that lets the user pick any chat and starts an inline query there, pre-filled with query.
func NewInlineButtonSwitchInlineCurrent ¶
func NewInlineButtonSwitchInlineCurrent(text, query string) InlineKeyboardButton
NewInlineButtonSwitchInlineCurrent creates a button that starts an inline query pre-filled with query in the current chat.
func NewInlineButtonURL ¶
func NewInlineButtonURL(text, url string) InlineKeyboardButton
NewInlineButtonURL creates a button that opens url when pressed.
func NewInlineButtonWebApp ¶
func NewInlineButtonWebApp(text, webAppURL string) InlineKeyboardButton
NewInlineButtonWebApp creates a button that launches the Telegram Web App at webAppURL — only valid in private chats.
type InlineKeyboardMarkup ¶
type InlineKeyboardMarkup struct {
// Array of button rows, each represented by an Array of InlineKeyboardButton objects
InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
}
This object represents an inline keyboard that appears right next to the message it belongs to.
func NewInlineKeyboardMarkup ¶
func NewInlineKeyboardMarkup(keyboard [][]InlineKeyboardButton) *InlineKeyboardMarkup
NewInlineKeyboardMarkup builds an InlineKeyboardMarkup directly from a 2D button array, for callers who already have their buttons laid out and don't need the Row/Add/Insert builder:
markup := gg.NewInlineKeyboardMarkup([][]gg.InlineKeyboardButton{{btn1, btn2}, {btn3}})
func QuickInlineKeyboard ¶
func QuickInlineKeyboard(buttons [][]string) *InlineKeyboardMarkup
QuickInlineKeyboard builds a full inline keyboard of callback buttons from parallel {text, callback_data} pairs, one row per inner slice — a shortcut for the common case that needs no other options:
kb := gg.QuickInlineKeyboard([][]string{{"Text1", "data1"}, {"Text2", "data2"}})
func QuickInlineRow ¶
func QuickInlineRow(buttons ...struct{ text, data string }) *InlineKeyboardMarkup
QuickInlineRow builds a single-row inline keyboard of callback buttons from {text, data} pairs.
type InlineQuery ¶
type InlineQuery struct {
// Unique identifier for this query
ID string `json:"id"`
// Sender
From *User `json:"from"`
// Text of the query (up to 256 characters)
Query string `json:"query"`
// Offset of the results to be returned, can be controlled by the bot
Offset string `json:"offset"`
// Optional. Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat.
ChatType string `json:"chat_type,omitempty"`
// Optional. Sender location, only for bots that request user location
Location *Location `json:"location,omitempty"`
}
This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
type InlineQueryResult ¶
type InlineQueryResult interface {
GetID() string
GetReplyMarkup() *InlineKeyboardMarkup
GetType() string
// contains filtered or unexported methods
}
This object represents one result of an inline query. Telegram clients currently support results of the following 20 types: Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public.
type InlineQueryResultArticle ¶
type InlineQueryResultArticle struct {
// Type of the result, must be article
Type string `json:"type"`
// Unique identifier for this result, 1-64 Bytes
ID string `json:"id"`
// Title of the result
Title string `json:"title"`
// Content of the message to be sent
InputMessageContent InputMessageContent `json:"input_message_content"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. URL of the result
URL string `json:"url,omitempty"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Url of the thumbnail for the result
ThumbnailURL string `json:"thumbnail_url,omitempty"`
// Optional. Thumbnail width
ThumbnailWidth int64 `json:"thumbnail_width,omitempty"`
// Optional. Thumbnail height
ThumbnailHeight int64 `json:"thumbnail_height,omitempty"`
}
Represents a link to an article or web page.
func (*InlineQueryResultArticle) GetID ¶
func (v *InlineQueryResultArticle) GetID() string
func (*InlineQueryResultArticle) GetReplyMarkup ¶
func (v *InlineQueryResultArticle) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultArticle) GetType ¶
func (v *InlineQueryResultArticle) GetType() string
type InlineQueryResultAudio ¶
type InlineQueryResultAudio struct {
// Type of the result, must be audio
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid URL for the audio file
AudioURL string `json:"audio_url"`
// Title
Title string `json:"title"`
// Optional. Caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the audio caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Performer
Performer string `json:"performer,omitempty"`
// Optional. Audio duration in seconds
AudioDuration int64 `json:"audio_duration,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the audio
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
func (*InlineQueryResultAudio) GetID ¶
func (v *InlineQueryResultAudio) GetID() string
func (*InlineQueryResultAudio) GetReplyMarkup ¶
func (v *InlineQueryResultAudio) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultAudio) GetType ¶
func (v *InlineQueryResultAudio) GetType() string
type InlineQueryResultCachedAudio ¶
type InlineQueryResultCachedAudio struct {
// Type of the result, must be audio
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier for the audio file
AudioFileID string `json:"audio_file_id"`
// Optional. Caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the audio caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the audio
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
func (*InlineQueryResultCachedAudio) GetID ¶
func (v *InlineQueryResultCachedAudio) GetID() string
The Get* methods below implement InlineQueryResult: fields shared by every member, callable on the interface value directly without a type switch.
func (*InlineQueryResultCachedAudio) GetReplyMarkup ¶
func (v *InlineQueryResultCachedAudio) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedAudio) GetType ¶
func (v *InlineQueryResultCachedAudio) GetType() string
type InlineQueryResultCachedDocument ¶
type InlineQueryResultCachedDocument struct {
// Type of the result, must be document
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// Title for the result
Title string `json:"title"`
// A valid file identifier for the file
DocumentFileID string `json:"document_file_id"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Caption of the document to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the document caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the file
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.
func (*InlineQueryResultCachedDocument) GetID ¶
func (v *InlineQueryResultCachedDocument) GetID() string
func (*InlineQueryResultCachedDocument) GetReplyMarkup ¶
func (v *InlineQueryResultCachedDocument) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedDocument) GetType ¶
func (v *InlineQueryResultCachedDocument) GetType() string
type InlineQueryResultCachedGif ¶
type InlineQueryResultCachedGif struct {
// Type of the result, must be gif
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier for the GIF file
GifFileID string `json:"gif_file_id"`
// Optional. Title for the result
Title string `json:"title,omitempty"`
// Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the GIF animation
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation.
func (*InlineQueryResultCachedGif) GetID ¶
func (v *InlineQueryResultCachedGif) GetID() string
func (*InlineQueryResultCachedGif) GetReplyMarkup ¶
func (v *InlineQueryResultCachedGif) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedGif) GetType ¶
func (v *InlineQueryResultCachedGif) GetType() string
type InlineQueryResultCachedMpeg4Gif ¶
type InlineQueryResultCachedMpeg4Gif struct {
// Type of the result, must be mpeg4_gif
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier for the MPEG4 file
Mpeg4FileID string `json:"mpeg4_file_id"`
// Optional. Title for the result
Title string `json:"title,omitempty"`
// Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the video animation
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.
func (*InlineQueryResultCachedMpeg4Gif) GetID ¶
func (v *InlineQueryResultCachedMpeg4Gif) GetID() string
func (*InlineQueryResultCachedMpeg4Gif) GetReplyMarkup ¶
func (v *InlineQueryResultCachedMpeg4Gif) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedMpeg4Gif) GetType ¶
func (v *InlineQueryResultCachedMpeg4Gif) GetType() string
type InlineQueryResultCachedPhoto ¶
type InlineQueryResultCachedPhoto struct {
// Type of the result, must be photo
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier of the photo
PhotoFileID string `json:"photo_file_id"`
// Optional. Title for the result
Title string `json:"title,omitempty"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the photo caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the photo
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.
func (*InlineQueryResultCachedPhoto) GetID ¶
func (v *InlineQueryResultCachedPhoto) GetID() string
func (*InlineQueryResultCachedPhoto) GetReplyMarkup ¶
func (v *InlineQueryResultCachedPhoto) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedPhoto) GetType ¶
func (v *InlineQueryResultCachedPhoto) GetType() string
type InlineQueryResultCachedSticker ¶
type InlineQueryResultCachedSticker struct {
// Type of the result, must be sticker
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier of the sticker
StickerFileID string `json:"sticker_file_id"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the sticker
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.
func (*InlineQueryResultCachedSticker) GetID ¶
func (v *InlineQueryResultCachedSticker) GetID() string
func (*InlineQueryResultCachedSticker) GetReplyMarkup ¶
func (v *InlineQueryResultCachedSticker) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedSticker) GetType ¶
func (v *InlineQueryResultCachedSticker) GetType() string
type InlineQueryResultCachedVideo ¶
type InlineQueryResultCachedVideo struct {
// Type of the result, must be video
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier for the video file
VideoFileID string `json:"video_file_id"`
// Title for the result
Title string `json:"title"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Caption of the video to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the video caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the video
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.
func (*InlineQueryResultCachedVideo) GetID ¶
func (v *InlineQueryResultCachedVideo) GetID() string
func (*InlineQueryResultCachedVideo) GetReplyMarkup ¶
func (v *InlineQueryResultCachedVideo) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedVideo) GetType ¶
func (v *InlineQueryResultCachedVideo) GetType() string
type InlineQueryResultCachedVoice ¶
type InlineQueryResultCachedVoice struct {
// Type of the result, must be voice
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid file identifier for the voice message
VoiceFileID string `json:"voice_file_id"`
// Voice message title
Title string `json:"title"`
// Optional. Caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the voice message caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the voice message
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.
func (*InlineQueryResultCachedVoice) GetID ¶
func (v *InlineQueryResultCachedVoice) GetID() string
func (*InlineQueryResultCachedVoice) GetReplyMarkup ¶
func (v *InlineQueryResultCachedVoice) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultCachedVoice) GetType ¶
func (v *InlineQueryResultCachedVoice) GetType() string
type InlineQueryResultContact ¶
type InlineQueryResultContact struct {
// Type of the result, must be contact
Type string `json:"type"`
// Unique identifier for this result, 1-64 Bytes
ID string `json:"id"`
// Contact's phone number
PhoneNumber string `json:"phone_number"`
// Contact's first name
FirstName string `json:"first_name"`
// Optional. Contact's last name
LastName string `json:"last_name,omitempty"`
// Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
Vcard string `json:"vcard,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the contact
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
// Optional. Url of the thumbnail for the result
ThumbnailURL string `json:"thumbnail_url,omitempty"`
// Optional. Thumbnail width
ThumbnailWidth int64 `json:"thumbnail_width,omitempty"`
// Optional. Thumbnail height
ThumbnailHeight int64 `json:"thumbnail_height,omitempty"`
}
Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.
func (*InlineQueryResultContact) GetID ¶
func (v *InlineQueryResultContact) GetID() string
func (*InlineQueryResultContact) GetReplyMarkup ¶
func (v *InlineQueryResultContact) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultContact) GetType ¶
func (v *InlineQueryResultContact) GetType() string
type InlineQueryResultDocument ¶
type InlineQueryResultDocument struct {
// Type of the result, must be document
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// Title for the result
Title string `json:"title"`
// Optional. Caption of the document to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the document caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// A valid URL for the file
DocumentURL string `json:"document_url"`
// MIME type of the content of the file, either “application/pdf” or “application/zip”
MimeType string `json:"mime_type"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the file
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
// Optional. URL of the thumbnail (JPEG only) for the file
ThumbnailURL string `json:"thumbnail_url,omitempty"`
// Optional. Thumbnail width
ThumbnailWidth int64 `json:"thumbnail_width,omitempty"`
// Optional. Thumbnail height
ThumbnailHeight int64 `json:"thumbnail_height,omitempty"`
}
Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.
func (*InlineQueryResultDocument) GetID ¶
func (v *InlineQueryResultDocument) GetID() string
func (*InlineQueryResultDocument) GetReplyMarkup ¶
func (v *InlineQueryResultDocument) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultDocument) GetType ¶
func (v *InlineQueryResultDocument) GetType() string
type InlineQueryResultGame ¶
type InlineQueryResultGame struct {
// Type of the result, must be game
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// Short name of the game
GameShortName string `json:"game_short_name"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
Represents a Game.
func (*InlineQueryResultGame) GetID ¶
func (v *InlineQueryResultGame) GetID() string
func (*InlineQueryResultGame) GetReplyMarkup ¶
func (v *InlineQueryResultGame) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultGame) GetType ¶
func (v *InlineQueryResultGame) GetType() string
type InlineQueryResultGif ¶
type InlineQueryResultGif struct {
// Type of the result, must be gif
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid URL for the GIF file
GifURL string `json:"gif_url"`
// Optional. Width of the GIF
GifWidth int64 `json:"gif_width,omitempty"`
// Optional. Height of the GIF
GifHeight int64 `json:"gif_height,omitempty"`
// Optional. Duration of the GIF in seconds
GifDuration int64 `json:"gif_duration,omitempty"`
// URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
ThumbnailURL string `json:"thumbnail_url"`
// Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”.
ThumbnailMimeType string `json:"thumbnail_mime_type,omitempty"`
// Optional. Title for the result
Title string `json:"title,omitempty"`
// Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the GIF animation
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.
func (*InlineQueryResultGif) GetID ¶
func (v *InlineQueryResultGif) GetID() string
func (*InlineQueryResultGif) GetReplyMarkup ¶
func (v *InlineQueryResultGif) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultGif) GetType ¶
func (v *InlineQueryResultGif) GetType() string
type InlineQueryResultLocation ¶
type InlineQueryResultLocation struct {
// Type of the result, must be location
Type string `json:"type"`
// Unique identifier for this result, 1-64 Bytes
ID string `json:"id"`
// Location latitude in degrees
Latitude float64 `json:"latitude"`
// Location longitude in degrees
Longitude float64 `json:"longitude"`
// Location title
Title string `json:"title"`
// Optional. The radius of uncertainty for the location, measured in meters; 0-1500
HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"`
// Optional. Period in seconds during which the location can be updated, must be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely
LivePeriod int64 `json:"live_period,omitempty"`
// Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
Heading int64 `json:"heading,omitempty"`
// Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
ProximityAlertRadius int64 `json:"proximity_alert_radius,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the location
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
// Optional. Url of the thumbnail for the result
ThumbnailURL string `json:"thumbnail_url,omitempty"`
// Optional. Thumbnail width
ThumbnailWidth int64 `json:"thumbnail_width,omitempty"`
// Optional. Thumbnail height
ThumbnailHeight int64 `json:"thumbnail_height,omitempty"`
}
Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.
func (*InlineQueryResultLocation) GetID ¶
func (v *InlineQueryResultLocation) GetID() string
func (*InlineQueryResultLocation) GetReplyMarkup ¶
func (v *InlineQueryResultLocation) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultLocation) GetType ¶
func (v *InlineQueryResultLocation) GetType() string
type InlineQueryResultMpeg4Gif ¶
type InlineQueryResultMpeg4Gif struct {
// Type of the result, must be mpeg4_gif
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid URL for the MPEG4 file
Mpeg4URL string `json:"mpeg4_url"`
// Optional. Video width
Mpeg4Width int64 `json:"mpeg4_width,omitempty"`
// Optional. Video height
Mpeg4Height int64 `json:"mpeg4_height,omitempty"`
// Optional. Video duration in seconds
Mpeg4Duration int64 `json:"mpeg4_duration,omitempty"`
// URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
ThumbnailURL string `json:"thumbnail_url"`
// Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”.
ThumbnailMimeType string `json:"thumbnail_mime_type,omitempty"`
// Optional. Title for the result
Title string `json:"title,omitempty"`
// Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the video animation
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.
func (*InlineQueryResultMpeg4Gif) GetID ¶
func (v *InlineQueryResultMpeg4Gif) GetID() string
func (*InlineQueryResultMpeg4Gif) GetReplyMarkup ¶
func (v *InlineQueryResultMpeg4Gif) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultMpeg4Gif) GetType ¶
func (v *InlineQueryResultMpeg4Gif) GetType() string
type InlineQueryResultPhoto ¶
type InlineQueryResultPhoto struct {
// Type of the result, must be photo
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB.
PhotoURL string `json:"photo_url"`
// URL of the thumbnail for the photo
ThumbnailURL string `json:"thumbnail_url"`
// Optional. Width of the photo
PhotoWidth int64 `json:"photo_width,omitempty"`
// Optional. Height of the photo
PhotoHeight int64 `json:"photo_height,omitempty"`
// Optional. Title for the result
Title string `json:"title,omitempty"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the photo caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the photo
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.
func (*InlineQueryResultPhoto) GetID ¶
func (v *InlineQueryResultPhoto) GetID() string
func (*InlineQueryResultPhoto) GetReplyMarkup ¶
func (v *InlineQueryResultPhoto) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultPhoto) GetType ¶
func (v *InlineQueryResultPhoto) GetType() string
type InlineQueryResultVenue ¶
type InlineQueryResultVenue struct {
// Type of the result, must be venue
Type string `json:"type"`
// Unique identifier for this result, 1-64 Bytes
ID string `json:"id"`
// Latitude of the venue location in degrees
Latitude float64 `json:"latitude"`
// Longitude of the venue location in degrees
Longitude float64 `json:"longitude"`
// Title of the venue
Title string `json:"title"`
// Address of the venue
Address string `json:"address"`
// Optional. Foursquare identifier of the venue if known
FoursquareID string `json:"foursquare_id,omitempty"`
// Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
FoursquareType string `json:"foursquare_type,omitempty"`
// Optional. Google Places identifier of the venue
GooglePlaceID string `json:"google_place_id,omitempty"`
// Optional. Google Places type of the venue. (See supported types.)
GooglePlaceType string `json:"google_place_type,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the venue
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
// Optional. Url of the thumbnail for the result
ThumbnailURL string `json:"thumbnail_url,omitempty"`
// Optional. Thumbnail width
ThumbnailWidth int64 `json:"thumbnail_width,omitempty"`
// Optional. Thumbnail height
ThumbnailHeight int64 `json:"thumbnail_height,omitempty"`
}
Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.
func (*InlineQueryResultVenue) GetID ¶
func (v *InlineQueryResultVenue) GetID() string
func (*InlineQueryResultVenue) GetReplyMarkup ¶
func (v *InlineQueryResultVenue) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultVenue) GetType ¶
func (v *InlineQueryResultVenue) GetType() string
type InlineQueryResultVideo ¶
type InlineQueryResultVideo struct {
// Type of the result, must be video
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid URL for the embedded video player or video file
VideoURL string `json:"video_url"`
// MIME type of the content of the video URL, “text/html” or “video/mp4”
MimeType string `json:"mime_type"`
// URL of the thumbnail (JPEG only) for the video
ThumbnailURL string `json:"thumbnail_url"`
// Title for the result
Title string `json:"title"`
// Optional. Caption of the video to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the video caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Video width
VideoWidth int64 `json:"video_width,omitempty"`
// Optional. Video height
VideoHeight int64 `json:"video_height,omitempty"`
// Optional. Video duration in seconds
VideoDuration int64 `json:"video_duration,omitempty"`
// Optional. Short description of the result
Description string `json:"description,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content.
func (*InlineQueryResultVideo) GetID ¶
func (v *InlineQueryResultVideo) GetID() string
func (*InlineQueryResultVideo) GetReplyMarkup ¶
func (v *InlineQueryResultVideo) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultVideo) GetType ¶
func (v *InlineQueryResultVideo) GetType() string
type InlineQueryResultVoice ¶
type InlineQueryResultVoice struct {
// Type of the result, must be voice
Type string `json:"type"`
// Unique identifier for this result, 1-64 bytes
ID string `json:"id"`
// A valid URL for the voice recording
VoiceURL string `json:"voice_url"`
// Recording title
Title string `json:"title"`
// Optional. Caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the voice message caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Recording duration in seconds
VoiceDuration int64 `json:"voice_duration,omitempty"`
// Optional. Inline keyboard attached to the message
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// Optional. Content of the message to be sent instead of the voice recording
InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}
Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message.
func (*InlineQueryResultVoice) GetID ¶
func (v *InlineQueryResultVoice) GetID() string
func (*InlineQueryResultVoice) GetReplyMarkup ¶
func (v *InlineQueryResultVoice) GetReplyMarkup() *InlineKeyboardMarkup
func (*InlineQueryResultVoice) GetType ¶
func (v *InlineQueryResultVoice) GetType() string
type InlineQueryResultsButton ¶
type InlineQueryResultsButton struct {
// Label text on the button
Text string `json:"text"`
// Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method switchInlineQuery inside the Web App.
WebApp *WebAppInfo `json:"web_app,omitempty"`
// Optional. Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities.
StartParameter string `json:"start_parameter,omitempty"`
}
This object represents a button to be shown above inline query results. You must use exactly one of the optional fields.
type InputChecklist ¶
type InputChecklist struct {
// Title of the checklist; 1-255 characters after entities parsing
Title string `json:"title"`
// Optional. Mode for parsing entities in the title. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the title, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed.
TitleEntities []MessageEntity `json:"title_entities,omitempty"`
// List of 1-30 tasks in the checklist
Tasks []InputChecklistTask `json:"tasks"`
// Optional. Pass True if other users can add tasks to the checklist
OthersCanAddTasks bool `json:"others_can_add_tasks,omitempty"`
// Optional. Pass True if other users can mark tasks as done or not done in the checklist
OthersCanMarkTasksAsDone bool `json:"others_can_mark_tasks_as_done,omitempty"`
}
Describes a checklist to create.
type InputChecklistTask ¶
type InputChecklistTask struct {
// Unique identifier of the task; must be positive and unique among all task identifiers currently present in the checklist
ID int64 `json:"id"`
// Text of the task; 1-100 characters after entities parsing
Text string `json:"text"`
// Optional. Mode for parsing entities in the text. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the text, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed.
TextEntities []MessageEntity `json:"text_entities,omitempty"`
}
Describes a task to add to a checklist.
type InputContactMessageContent ¶
type InputContactMessageContent struct {
// Contact's phone number
PhoneNumber string `json:"phone_number"`
// Contact's first name
FirstName string `json:"first_name"`
// Optional. Contact's last name
LastName string `json:"last_name,omitempty"`
// Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes
Vcard string `json:"vcard,omitempty"`
}
Represents the content of a contact message to be sent as the result of an inline query.
type InputFile ¶
InputFile represents a file to send: an existing Telegram file_id, an HTTP(S) URL for Telegram to fetch, or local content to upload directly. Construct with InputFileID, InputFileURL, or InputFileUpload — the zero value is invalid.
A request with no InputFile carrying a local upload is JSON-encoded as usual; adding one anywhere in the request switches that single call to multipart/form-data transparently (see internal/api.Client.Call).
func InputFileID ¶
InputFileID references a file already on Telegram's servers.
func InputFileURL ¶
InputFileURL has Telegram fetch the file from a public HTTP(S) URL.
func InputFileUpload ¶
InputFileUpload uploads local content directly, read once when the request is sent — e.g. an *os.File, or any other io.Reader. filename is sent as the multipart part's filename; Telegram uses its extension to help guess content type.
type InputInvoiceMessageContent ¶
type InputInvoiceMessageContent struct {
// Product name, 1-32 characters
Title string `json:"title"`
// Product description, 1-255 characters
Description string `json:"description"`
// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes.
Payload string `json:"payload"`
// Optional. Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
ProviderToken string `json:"provider_token,omitempty"`
// Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
Currency string `json:"currency"`
// Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
Prices []LabeledPrice `json:"prices"`
// Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
MaxTipAmount int64 `json:"max_tip_amount,omitempty"`
// Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
SuggestedTipAmounts []int64 `json:"suggested_tip_amounts,omitempty"`
// Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider.
ProviderData string `json:"provider_data,omitempty"`
// Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.
PhotoURL string `json:"photo_url,omitempty"`
// Optional. Photo size in bytes
PhotoSize int64 `json:"photo_size,omitempty"`
// Optional. Photo width
PhotoWidth int64 `json:"photo_width,omitempty"`
// Optional. Photo height
PhotoHeight int64 `json:"photo_height,omitempty"`
// Optional. Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
NeedName bool `json:"need_name,omitempty"`
// Optional. Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
NeedPhoneNumber bool `json:"need_phone_number,omitempty"`
// Optional. Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
NeedEmail bool `json:"need_email,omitempty"`
// Optional. Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
NeedShippingAddress bool `json:"need_shipping_address,omitempty"`
// Optional. Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
SendPhoneNumberToProvider bool `json:"send_phone_number_to_provider,omitempty"`
// Optional. Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
SendEmailToProvider bool `json:"send_email_to_provider,omitempty"`
// Optional. Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
IsFlexible bool `json:"is_flexible,omitempty"`
}
Represents the content of an invoice message to be sent as the result of an inline query.
type InputLocationMessageContent ¶
type InputLocationMessageContent struct {
// Latitude of the location in degrees
Latitude float64 `json:"latitude"`
// Longitude of the location in degrees
Longitude float64 `json:"longitude"`
// Optional. The radius of uncertainty for the location, measured in meters; 0-1500
HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"`
// Optional. Period in seconds during which the location can be updated, must be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely
LivePeriod int64 `json:"live_period,omitempty"`
// Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
Heading int64 `json:"heading,omitempty"`
// Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
ProximityAlertRadius int64 `json:"proximity_alert_radius,omitempty"`
}
Represents the content of a location message to be sent as the result of an inline query.
type InputMedia ¶
type InputMedia interface {
GetCaption() string
GetCaptionEntities() []MessageEntity
GetMedia() InputFile
GetParseMode() string
GetType() string
// contains filtered or unexported methods
}
This object represents the content of a media message to be sent. It should be one of
type InputMediaAnimation ¶
type InputMediaAnimation struct {
// Type of the media, must be animation
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media InputFile `json:"media"`
// Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Optional. Caption of the animation to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the animation caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Animation width
Width int64 `json:"width,omitempty"`
// Optional. Animation height
Height int64 `json:"height,omitempty"`
// Optional. Animation duration in seconds
Duration int64 `json:"duration,omitempty"`
// Optional. Pass True if the animation needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
}
Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.
func (*InputMediaAnimation) GetCaption ¶
func (v *InputMediaAnimation) GetCaption() string
The Get* methods below implement InputMedia: fields shared by every member, callable on the interface value directly without a type switch.
func (*InputMediaAnimation) GetCaptionEntities ¶
func (v *InputMediaAnimation) GetCaptionEntities() []MessageEntity
func (*InputMediaAnimation) GetMedia ¶
func (v *InputMediaAnimation) GetMedia() InputFile
func (*InputMediaAnimation) GetParseMode ¶
func (v *InputMediaAnimation) GetParseMode() string
func (*InputMediaAnimation) GetType ¶
func (v *InputMediaAnimation) GetType() string
The Get* methods below implement InputPollMedia: fields shared by every member, callable on the interface value directly without a type switch.
type InputMediaAudio ¶
type InputMediaAudio struct {
// Type of the media, must be audio
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media InputFile `json:"media"`
// Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Optional. Caption of the audio to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the audio caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Duration of the audio in seconds
Duration int64 `json:"duration,omitempty"`
// Optional. Performer of the audio
Performer string `json:"performer,omitempty"`
// Optional. Title of the audio
Title string `json:"title,omitempty"`
}
Represents an audio file to be treated as music to be sent.
func (*InputMediaAudio) GetCaption ¶
func (v *InputMediaAudio) GetCaption() string
func (*InputMediaAudio) GetCaptionEntities ¶
func (v *InputMediaAudio) GetCaptionEntities() []MessageEntity
func (*InputMediaAudio) GetMedia ¶
func (v *InputMediaAudio) GetMedia() InputFile
func (*InputMediaAudio) GetParseMode ¶
func (v *InputMediaAudio) GetParseMode() string
func (*InputMediaAudio) GetType ¶
func (v *InputMediaAudio) GetType() string
type InputMediaDocument ¶
type InputMediaDocument struct {
// Type of the media, must be document
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media InputFile `json:"media"`
// Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Optional. Caption of the document to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the document caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always True, if the document is sent as part of an album.
DisableContentTypeDetection bool `json:"disable_content_type_detection,omitempty"`
}
Represents a general file to be sent.
func (*InputMediaDocument) GetCaption ¶
func (v *InputMediaDocument) GetCaption() string
func (*InputMediaDocument) GetCaptionEntities ¶
func (v *InputMediaDocument) GetCaptionEntities() []MessageEntity
func (*InputMediaDocument) GetMedia ¶
func (v *InputMediaDocument) GetMedia() InputFile
func (*InputMediaDocument) GetParseMode ¶
func (v *InputMediaDocument) GetParseMode() string
func (*InputMediaDocument) GetType ¶
func (v *InputMediaDocument) GetType() string
type InputMediaLink ¶
type InputMediaLink struct {
// Type of the media, must be link
Type string `json:"type"`
// HTTP URL of the link
URL string `json:"url"`
}
Represents an HTTP link to be sent.
func (*InputMediaLink) GetType ¶
func (v *InputMediaLink) GetType() string
The Get* methods below implement InputPollOptionMedia: fields shared by every member, callable on the interface value directly without a type switch.
type InputMediaLivePhoto ¶
type InputMediaLivePhoto struct {
// Type of the media, must be live_photo
Type string `json:"type"`
// Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
Media InputFile `json:"media"`
// The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
Photo InputFile `json:"photo"`
// Optional. Caption of the live photo to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the live photo caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Pass True if the live photo needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
}
Represents a live photo to be sent.
func (*InputMediaLivePhoto) GetCaption ¶
func (v *InputMediaLivePhoto) GetCaption() string
func (*InputMediaLivePhoto) GetCaptionEntities ¶
func (v *InputMediaLivePhoto) GetCaptionEntities() []MessageEntity
func (*InputMediaLivePhoto) GetMedia ¶
func (v *InputMediaLivePhoto) GetMedia() InputFile
func (*InputMediaLivePhoto) GetParseMode ¶
func (v *InputMediaLivePhoto) GetParseMode() string
func (*InputMediaLivePhoto) GetType ¶
func (v *InputMediaLivePhoto) GetType() string
type InputMediaLocation ¶
type InputMediaLocation struct {
// Type of the media, must be location
Type string `json:"type"`
// Latitude of the location
Latitude float64 `json:"latitude"`
// Longitude of the location
Longitude float64 `json:"longitude"`
// Optional. The radius of uncertainty for the location, measured in meters; 0-1500
HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"`
}
Represents a location to be sent.
func (*InputMediaLocation) GetType ¶
func (v *InputMediaLocation) GetType() string
type InputMediaPhoto ¶
type InputMediaPhoto struct {
// Type of the media, must be photo
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media InputFile `json:"media"`
// Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the photo caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Pass True if the photo needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
}
Represents a photo to be sent.
func (*InputMediaPhoto) GetCaption ¶
func (v *InputMediaPhoto) GetCaption() string
func (*InputMediaPhoto) GetCaptionEntities ¶
func (v *InputMediaPhoto) GetCaptionEntities() []MessageEntity
func (*InputMediaPhoto) GetMedia ¶
func (v *InputMediaPhoto) GetMedia() InputFile
func (*InputMediaPhoto) GetParseMode ¶
func (v *InputMediaPhoto) GetParseMode() string
func (*InputMediaPhoto) GetType ¶
func (v *InputMediaPhoto) GetType() string
type InputMediaSticker ¶
type InputMediaSticker struct {
// Type of the media, must be sticker
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a .WEBP sticker from the Internet, or pass "attach://<file_attach_name>" to upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media string `json:"media"`
// Optional. Emoji associated with the sticker; only for just uploaded stickers
Emoji string `json:"emoji,omitempty"`
}
Represents a sticker file to be sent.
func (*InputMediaSticker) GetType ¶
func (v *InputMediaSticker) GetType() string
type InputMediaVenue ¶
type InputMediaVenue struct {
// Type of the media, must be venue
Type string `json:"type"`
// Latitude of the location
Latitude float64 `json:"latitude"`
// Longitude of the location
Longitude float64 `json:"longitude"`
// Name of the venue
Title string `json:"title"`
// Address of the venue
Address string `json:"address"`
// Optional. Foursquare identifier of the venue
FoursquareID string `json:"foursquare_id,omitempty"`
// Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
FoursquareType string `json:"foursquare_type,omitempty"`
// Optional. Google Places identifier of the venue
GooglePlaceID string `json:"google_place_id,omitempty"`
// Optional. Google Places type of the venue. (See supported types.)
GooglePlaceType string `json:"google_place_type,omitempty"`
}
Represents a venue to be sent.
func (*InputMediaVenue) GetType ¶
func (v *InputMediaVenue) GetType() string
type InputMediaVideo ¶
type InputMediaVideo struct {
// Type of the media, must be video
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media InputFile `json:"media"`
// Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Optional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Cover string `json:"cover,omitempty"`
// Optional. Start timestamp for the video in the message
StartTimestamp int64 `json:"start_timestamp,omitempty"`
// Optional. Caption of the video to be sent, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Optional. Mode for parsing entities in the video caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. Video width
Width int64 `json:"width,omitempty"`
// Optional. Video height
Height int64 `json:"height,omitempty"`
// Optional. Video duration in seconds
Duration int64 `json:"duration,omitempty"`
// Optional. Pass True if the uploaded video is suitable for streaming
SupportsStreaming bool `json:"supports_streaming,omitempty"`
// Optional. Pass True if the video needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
}
Represents a video to be sent.
func (*InputMediaVideo) GetCaption ¶
func (v *InputMediaVideo) GetCaption() string
func (*InputMediaVideo) GetCaptionEntities ¶
func (v *InputMediaVideo) GetCaptionEntities() []MessageEntity
func (*InputMediaVideo) GetMedia ¶
func (v *InputMediaVideo) GetMedia() InputFile
func (*InputMediaVideo) GetParseMode ¶
func (v *InputMediaVideo) GetParseMode() string
func (*InputMediaVideo) GetType ¶
func (v *InputMediaVideo) GetType() string
type InputMessageContent ¶
type InputMessageContent interface {
// contains filtered or unexported methods
}
This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following types:
type InputPaidMedia ¶
type InputPaidMedia interface {
GetMedia() string
GetType() string
// contains filtered or unexported methods
}
This object describes the paid media to be sent. Currently, it can be one of
type InputPaidMediaLivePhoto ¶
type InputPaidMediaLivePhoto struct {
// Type of the media, must be live_photo
Type string `json:"type"`
// Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
Media string `json:"media"`
// The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
Photo string `json:"photo"`
}
The paid media to send is a live photo.
func (*InputPaidMediaLivePhoto) GetMedia ¶
func (v *InputPaidMediaLivePhoto) GetMedia() string
The Get* methods below implement InputPaidMedia: fields shared by every member, callable on the interface value directly without a type switch.
func (*InputPaidMediaLivePhoto) GetType ¶
func (v *InputPaidMediaLivePhoto) GetType() string
type InputPaidMediaPhoto ¶
type InputPaidMediaPhoto struct {
// Type of the media, must be photo
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media string `json:"media"`
}
The paid media to send is a photo.
func (*InputPaidMediaPhoto) GetMedia ¶
func (v *InputPaidMediaPhoto) GetMedia() string
func (*InputPaidMediaPhoto) GetType ¶
func (v *InputPaidMediaPhoto) GetType() string
type InputPaidMediaVideo ¶
type InputPaidMediaVideo struct {
// Type of the media, must be video
Type string `json:"type"`
// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Media string `json:"media"`
// Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail string `json:"thumbnail,omitempty"`
// Optional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Cover string `json:"cover,omitempty"`
// Optional. Start timestamp for the video in the message
StartTimestamp int64 `json:"start_timestamp,omitempty"`
// Optional. Video width
Width int64 `json:"width,omitempty"`
// Optional. Video height
Height int64 `json:"height,omitempty"`
// Optional. Video duration in seconds
Duration int64 `json:"duration,omitempty"`
// Optional. Pass True if the uploaded video is suitable for streaming
SupportsStreaming bool `json:"supports_streaming,omitempty"`
}
The paid media to send is a video.
func (*InputPaidMediaVideo) GetMedia ¶
func (v *InputPaidMediaVideo) GetMedia() string
func (*InputPaidMediaVideo) GetType ¶
func (v *InputPaidMediaVideo) GetType() string
type InputPollMedia ¶
type InputPollMedia interface {
GetType() string
// contains filtered or unexported methods
}
This object represents the content of a poll description or a quiz explanation to be sent. It should be one of
type InputPollOption ¶
type InputPollOption struct {
// Option text, 1-100 characters
Text string `json:"text"`
// Optional. Mode for parsing entities in the text. See formatting options for more details. Currently, only custom emoji entities are allowed.
TextParseMode string `json:"text_parse_mode,omitempty"`
// Optional. A JSON-serialized list of special entities that appear in the poll option text. It can be specified instead of text_parse_mode.
TextEntities []MessageEntity `json:"text_entities,omitempty"`
// Optional. Media added to the poll option
Media InputPollOptionMedia `json:"media,omitempty"`
}
This object contains information about one answer option in a poll to be sent.
func (*InputPollOption) UnmarshalJSON ¶
func (v *InputPollOption) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes InputPollOption's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type InputPollOptionMedia ¶
type InputPollOptionMedia interface {
GetType() string
// contains filtered or unexported methods
}
This object represents the content of a poll option to be sent. It should be one of
type InputProfilePhoto ¶
type InputProfilePhoto interface {
GetType() string
// contains filtered or unexported methods
}
This object describes a profile photo to set. Currently, it can be one of
type InputProfilePhotoAnimated ¶
type InputProfilePhotoAnimated struct {
// Type of the profile photo, must be animated
Type string `json:"type"`
// The animated profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Animation string `json:"animation"`
// Optional. Timestamp in seconds of the frame that will be used as the static profile photo. Defaults to 0.0.
MainFrameTimestamp float64 `json:"main_frame_timestamp,omitempty"`
}
An animated profile photo in the MPEG4 format.
func (*InputProfilePhotoAnimated) GetType ¶
func (v *InputProfilePhotoAnimated) GetType() string
type InputProfilePhotoStatic ¶
type InputProfilePhotoStatic struct {
// Type of the profile photo, must be static
Type string `json:"type"`
// The static profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Photo string `json:"photo"`
}
A static profile photo in the .JPG format.
func (*InputProfilePhotoStatic) GetType ¶
func (v *InputProfilePhotoStatic) GetType() string
The Get* methods below implement InputProfilePhoto: fields shared by every member, callable on the interface value directly without a type switch.
type InputRichMessage ¶
type InputRichMessage struct {
// Optional. Content of the rich message to send described using HTML formatting. See rich message formatting options for more details.
Html string `json:"html,omitempty"`
// Optional. Content of the rich message to send described using Markdown formatting. See rich message formatting options for more details.
Markdown string `json:"markdown,omitempty"`
// Optional. Pass True if the rich message must be shown right-to-left
IsRtl bool `json:"is_rtl,omitempty"`
// Optional. Pass True to skip automatic detection of entities (e.g., URLs, email addresses, username mentions, hashtags, cashtags, bot commands, or phone numbers) in the text
SkipEntityDetection bool `json:"skip_entity_detection,omitempty"`
}
Describes a rich message to be sent. Exactly one of the fields html or markdown must be used.
func RenderRichMessage ¶
func RenderRichMessage(blocks ...RichBlock) (*InputRichMessage, error)
RenderRichMessage renders a tree of top-level blocks to HTML and returns it ready to send — as SendRichMessageRequest.RichMessage or SendRichMessageDraftRequest.RichMessage. Validates against Telegram's documented Rich Message limits (32,768 characters; 500 blocks, including nested ones; 16 levels of block nesting; 20 table columns) before returning, so an oversized message fails here with a ValidationError instead of a generic error from Telegram after the network round trip.
blocks (and anything nested inside them) can come from these constructors, a struct literal, or values read back off an incoming Message.RichMessage — RenderRichMessage doesn't care which, since it type-switches on the same generated types either way. The one thing it refuses is a media block (RichBlockPhoto and siblings, see this file's package-level doc) — that returns an error naming the offending type.
type InputRichMessageContent ¶
type InputRichMessageContent struct {
// The message to be sent
RichMessage *InputRichMessage `json:"rich_message"`
}
Represents the content of a rich message to be sent as the result of an inline query.
type InputSticker ¶
type InputSticker struct {
// The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new file using multipart/form-data under <file_attach_name> name. Animated and video stickers can't be uploaded via HTTP URL. More information on Sending Files »
Sticker InputFile `json:"sticker"`
// Format of the added sticker, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, “video” for a .WEBM video
Format string `json:"format"`
// List of 1-20 emoji associated with the sticker
EmojiList []string `json:"emoji_list"`
// Optional. Position where the mask should be placed on faces. For “mask” stickers only.
MaskPosition *MaskPosition `json:"mask_position,omitempty"`
// Optional. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only.
Keywords []string `json:"keywords,omitempty"`
}
This object describes a sticker to be added to a sticker set.
type InputStoryContent ¶
type InputStoryContent interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the content of a story to post. Currently, it can be one of
type InputStoryContentPhoto ¶
type InputStoryContentPhoto struct {
// Type of the content, must be photo
Type string `json:"type"`
// The photo to post as a story. The photo must be of the size 1080x1920 and must not exceed 10 MB. The photo can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Photo string `json:"photo"`
}
Describes a photo to post as a story.
func (*InputStoryContentPhoto) GetType ¶
func (v *InputStoryContentPhoto) GetType() string
The Get* methods below implement InputStoryContent: fields shared by every member, callable on the interface value directly without a type switch.
type InputStoryContentVideo ¶
type InputStoryContentVideo struct {
// Type of the content, must be video
Type string `json:"type"`
// The video to post as a story. The video must be of the size 720x1280, streamable, encoded with H.265 codec, with key frames added each second in the MPEG4 format, and must not exceed 30 MB. The video can't be reused and can only be uploaded as a new file, so you can pass "attach://<file_attach_name>" if the video was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Video string `json:"video"`
// Optional. Precise duration of the video in seconds; 0-60
Duration float64 `json:"duration,omitempty"`
// Optional. Timestamp in seconds of the frame that will be used as the static cover for the story. Defaults to 0.0.
CoverFrameTimestamp float64 `json:"cover_frame_timestamp,omitempty"`
// Optional. Pass True if the video has no sound
IsAnimation bool `json:"is_animation,omitempty"`
}
Describes a video to post as a story.
func (*InputStoryContentVideo) GetType ¶
func (v *InputStoryContentVideo) GetType() string
type InputTextMessageContent ¶
type InputTextMessageContent struct {
// Text of the message to be sent, 1-4096 characters
MessageText string `json:"message_text"`
// Optional. Mode for parsing entities in the message text. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// Optional. List of special entities that appear in message text, which can be specified instead of parse_mode
Entities []MessageEntity `json:"entities,omitempty"`
// Optional. Link preview generation options for the message
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
}
Represents the content of a text message to be sent as the result of an inline query.
type InputVenueMessageContent ¶
type InputVenueMessageContent struct {
// Latitude of the venue in degrees
Latitude float64 `json:"latitude"`
// Longitude of the venue in degrees
Longitude float64 `json:"longitude"`
// Name of the venue
Title string `json:"title"`
// Address of the venue
Address string `json:"address"`
// Optional. Foursquare identifier of the venue, if known
FoursquareID string `json:"foursquare_id,omitempty"`
// Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
FoursquareType string `json:"foursquare_type,omitempty"`
// Optional. Google Places identifier of the venue
GooglePlaceID string `json:"google_place_id,omitempty"`
// Optional. Google Places type of the venue. (See supported types.)
GooglePlaceType string `json:"google_place_type,omitempty"`
}
Represents the content of a venue message to be sent as the result of an inline query.
type Invoice ¶
type Invoice struct {
// Product name
Title string `json:"title"`
// Product description
Description string `json:"description"`
// Unique bot deep-linking parameter that can be used to generate this invoice
StartParameter string `json:"start_parameter"`
// Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars
Currency string `json:"currency"`
// Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
TotalAmount int64 `json:"total_amount"`
}
This object contains basic information about an invoice.
type KeyboardButton ¶
type KeyboardButton struct {
// Text of the button. If none of the fields other than text, icon_custom_emoji_id, and style are used, it will be sent as a message when the button is pressed.
Text string `json:"text"`
// Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"`
// Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used.
Style string `json:"style,omitempty"`
// Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only.
RequestUsers *KeyboardButtonRequestUsers `json:"request_users,omitempty"`
// Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only.
RequestChat *KeyboardButtonRequestChat `json:"request_chat,omitempty"`
// Optional. If specified, pressing the button will ask the user to create and share a bot that will be managed by the current bot. Available for bots that enabled management of other bots in the @BotFather Mini App. Available in private chats only.
RequestManagedBot *KeyboardButtonRequestManagedBot `json:"request_managed_bot,omitempty"`
// Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only.
RequestContact bool `json:"request_contact,omitempty"`
// Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only.
RequestLocation bool `json:"request_location,omitempty"`
// Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only.
RequestPoll *KeyboardButtonPollType `json:"request_poll,omitempty"`
// Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
WebApp *WebAppInfo `json:"web_app,omitempty"`
}
This object represents one button of the reply keyboard. At most one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button. For simple text buttons, String can be used instead of this object to specify the button text.
func NewKeyboardButton ¶
func NewKeyboardButton(text string) KeyboardButton
NewKeyboardButton creates a plain text button: pressing it just sends its own text as a regular message.
func NewKeyboardButtonContact ¶
func NewKeyboardButtonContact(text string) KeyboardButton
NewKeyboardButtonContact creates a button that requests the user's phone contact.
func NewKeyboardButtonLocation ¶
func NewKeyboardButtonLocation(text string) KeyboardButton
NewKeyboardButtonLocation creates a button that requests the user's current location.
func NewKeyboardButtonPoll ¶
func NewKeyboardButtonPoll(text string, pollType string) KeyboardButton
NewKeyboardButtonPoll creates a button that opens the poll-creation UI. pollType is "quiz" or "regular"; "" lets the user create a poll of either type.
func NewKeyboardButtonWebApp ¶
func NewKeyboardButtonWebApp(text, webAppURL string) KeyboardButton
NewKeyboardButtonWebApp creates a button that launches the Telegram Web App at webAppURL — only valid in private chats.
type KeyboardButtonPollType ¶
type KeyboardButtonPollType struct {
// Optional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.
Type string `json:"type,omitempty"`
}
This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.
type KeyboardButtonRequestChat ¶
type KeyboardButtonRequestChat struct {
// Signed 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message.
RequestID int64 `json:"request_id"`
// Pass True to request a channel chat, pass False to request a group or a supergroup chat
ChatIsChannel bool `json:"chat_is_channel"`
// Optional. Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied.
ChatIsForum bool `json:"chat_is_forum,omitempty"`
// Optional. Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied.
ChatHasUsername bool `json:"chat_has_username,omitempty"`
// Optional. Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied.
ChatIsCreated bool `json:"chat_is_created,omitempty"`
// Optional. A JSON-serialized object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied.
UserAdministratorRights *ChatAdministratorRights `json:"user_administrator_rights,omitempty"`
// Optional. A JSON-serialized object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied.
BotAdministratorRights *ChatAdministratorRights `json:"bot_administrator_rights,omitempty"`
// Optional. Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied.
BotIsMember bool `json:"bot_is_member,omitempty"`
// Optional. Pass True to request the chat's title
RequestTitle bool `json:"request_title,omitempty"`
// Optional. Pass True to request the chat's username
RequestUsername bool `json:"request_username,omitempty"`
// Optional. Pass True to request the chat's photo
RequestPhoto bool `json:"request_photo,omitempty"`
}
This object defines the criteria used to request a suitable chat. Information about the selected chat will be shared with the bot when the corresponding button is pressed. The bot will be granted requested rights in the chat if appropriate. More about requesting chats ».
type KeyboardButtonRequestManagedBot ¶
type KeyboardButtonRequestManagedBot struct {
// Signed 32-bit identifier of the request. Must be unique within the message.
RequestID int64 `json:"request_id"`
// Optional. Suggested name for the bot
SuggestedName string `json:"suggested_name,omitempty"`
// Optional. Suggested username for the bot
SuggestedUsername string `json:"suggested_username,omitempty"`
}
This object defines the parameters for the creation of a managed bot. Information about the created bot will be shared with the bot using the update managed_bot and a Message with the field managed_bot_created.
type KeyboardButtonRequestUsers ¶
type KeyboardButtonRequestUsers struct {
// Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message.
RequestID int64 `json:"request_id"`
// Optional. Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied.
UserIsBot bool `json:"user_is_bot,omitempty"`
// Optional. Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied.
UserIsPremium bool `json:"user_is_premium,omitempty"`
// Optional. The maximum number of users to be selected; 1-10. Defaults to 1.
MaxQuantity int64 `json:"max_quantity,omitempty"`
// Optional. Pass True to request the users' first and last names
RequestName bool `json:"request_name,omitempty"`
// Optional. Pass True to request the users' usernames
RequestUsername bool `json:"request_username,omitempty"`
// Optional. Pass True to request the users' photos
RequestPhoto bool `json:"request_photo,omitempty"`
}
This object defines the criteria used to request suitable users. Information about the selected users will be shared with the bot when the corresponding button is pressed. More about requesting users »
type LabeledPrice ¶
type LabeledPrice struct {
// Portion label
Label string `json:"label"`
// Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
Amount int64 `json:"amount"`
}
This object represents a portion of the price for goods or services.
type LeaveChatRequest ¶
type LeaveChatRequest struct {
// Unique identifier for the target chat or username of the target supergroup or channel in the format @username. Channel direct messages chats aren't supported; leave the corresponding channel instead.
ChatID ChatID `json:"chat_id"`
}
LeaveChatRequest holds the parameters for leaveChat.
type LifecycleFunc ¶
LifecycleFunc is a startup or shutdown hook registered via TelegramBot.OnStartup or TelegramBot.OnShutdown.
type Link ¶
type Link struct {
// URL of the link
URL string `json:"url"`
}
Represents an HTTP link.
type LinkPreviewOptions ¶
type LinkPreviewOptions struct {
// Optional. True, if the link preview is disabled
IsDisabled bool `json:"is_disabled,omitempty"`
// Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used.
URL string `json:"url,omitempty"`
// Optional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
PreferSmallMedia bool `json:"prefer_small_media,omitempty"`
// Optional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
PreferLargeMedia bool `json:"prefer_large_media,omitempty"`
// Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text
ShowAboveText bool `json:"show_above_text,omitempty"`
}
Describes the options used for link preview generation.
type LivePhoto ¶
type LivePhoto struct {
// Optional. Available sizes of the corresponding static photo
Photo []PhotoSize `json:"photo,omitempty"`
// Identifier for the video file which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for the video file which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Video width as defined by the sender
Width int64 `json:"width"`
// Video height as defined by the sender
Height int64 `json:"height"`
// Duration of the video in seconds as defined by the sender
Duration int64 `json:"duration"`
// Optional. MIME type of the file as defined by the sender
MimeType string `json:"mime_type,omitempty"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a live photo.
type Location ¶
type Location struct {
// Latitude as defined by the sender
Latitude float64 `json:"latitude"`
// Longitude as defined by the sender
Longitude float64 `json:"longitude"`
// Optional. The radius of uncertainty for the location, measured in meters; 0-1500
HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"`
// Optional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only.
LivePeriod int64 `json:"live_period,omitempty"`
// Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only.
Heading int64 `json:"heading,omitempty"`
// Optional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.
ProximityAlertRadius int64 `json:"proximity_alert_radius,omitempty"`
}
This object represents a point on the map.
type LocationAddress ¶
type LocationAddress struct {
// The two-letter ISO 3166-1 alpha-2 country code of the country where the location is located
CountryCode string `json:"country_code"`
// Optional. State of the location
State string `json:"state,omitempty"`
// Optional. City of the location
City string `json:"city,omitempty"`
// Optional. Street address of the location
Street string `json:"street,omitempty"`
}
Describes the physical address of a location.
type LoginURL ¶
type LoginURL struct {
// An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data. NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization.
URL string `json:"url"`
// Optional. New text of the button in forwarded messages
ForwardText string `json:"forward_text,omitempty"`
// Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details.
BotUsername string `json:"bot_username,omitempty"`
// Optional. Pass True to request the permission for your bot to send messages to the user
RequestWriteAccess bool `json:"request_write_access,omitempty"`
}
This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in: Telegram apps support these buttons as of version 5.7. Sample bot: @discussbot
type LoginWidgetData ¶
type LoginWidgetData struct {
ID int64
FirstName string
LastName string
Username string
PhotoURL string
AuthDate time.Time
Hash string
}
LoginWidgetData is the parsed, HMAC-verified payload of a Telegram Login Widget callback. Only ValidateLoginWidgetData produces one.
func ValidateLoginWidgetData ¶
func ValidateLoginWidgetData(values url.Values, botToken string, maxAge time.Duration) (*LoginWidgetData, error)
ValidateLoginWidgetData authenticates the query parameters a Telegram Login Widget redirect/callback delivered, per the Login Widget spec: hash = hex(HMAC-SHA256(data-check-string, SHA256(bot_token))). Note the key derivation differs from WebApp init data (plain SHA256, no "WebAppData"). maxAge bounds auth_date staleness; 0 skips the check.
type ManagedBotCreated ¶
type ManagedBotCreated struct {
// Information about the bot. The bot's token can be fetched using the method getManagedBotToken.
Bot *User `json:"bot"`
}
This object contains information about the bot that was created to be managed by the current bot.
type ManagedBotUpdated ¶
type ManagedBotUpdated struct {
// User that created the bot
User *User `json:"user"`
// Information about the bot. Token of the bot can be fetched using the method getManagedBotToken.
Bot *User `json:"bot"`
}
This object contains information about the creation, token update, or owner update of a bot that is managed by the current bot.
type MaskPosition ¶
type MaskPosition struct {
// The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”.
Point string `json:"point"`
// Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position.
XShift float64 `json:"x_shift"`
// Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position.
YShift float64 `json:"y_shift"`
// Mask scaling coefficient. For example, 2.0 means double size.
Scale float64 `json:"scale"`
}
This object describes the position on faces where a mask should be placed by default.
type MaybeInaccessibleMessage ¶
type MaybeInaccessibleMessage = Message
MaybeInaccessibleMessage is the Bot API's name for Message (see internal/gen/mapping.go: aliasedTypes for why it is flattened rather than modeled separately).
type MediaGroup ¶
type MediaGroup struct {
// contains filtered or unexported fields
}
MediaGroup builds the media array for TelegramBot.SendMediaGroup (an album) and enforces the rules Telegram otherwise reports as opaque 400s: 2–10 items, only photos/live photos/videos/documents/audio, and documents or audio never mixed with other types.
group := gg.NewMediaGroup().
Photo(gg.InputFileUpload("a.jpg", fileA), "first!").
Photo(gg.InputFileID(knownFileID)).
Video(gg.InputFileURL("https://example.com/c.mp4"))
msgs, err := group.Send(c)
The typed methods cover the common cases; MediaGroup.Add takes a hand-built InputMedia item for the long tail (parse_mode, spoilers, thumbnails).
func (*MediaGroup) Add ¶
func (g *MediaGroup) Add(item InputMedia) *MediaGroup
Add appends a hand-built item, for options the typed methods don't cover (parse_mode, caption entities, spoilers, thumbnails, cover frames). The item's Type field may be left empty — Build fills the canonical value.
func (*MediaGroup) Audio ¶
func (g *MediaGroup) Audio(media InputFile, caption ...string) *MediaGroup
Audio adds an audio track, optionally captioned. Telegram only allows audio to be grouped with other audio — MediaGroup.Build enforces it.
func (*MediaGroup) Build ¶
func (g *MediaGroup) Build() ([]InputMedia, error)
Build validates the album and returns the media array for SendMediaGroupRequest.Media. It errors on anything Telegram would 400: fewer than 2 or more than 10 items, an item type albums don't allow (animations, paid media), or documents/audio mixed with anything else. It also fills each item's required Type discriminator when left empty — forgetting it is the classic silent album killer.
func (*MediaGroup) Document ¶
func (g *MediaGroup) Document(media InputFile, caption ...string) *MediaGroup
Document adds a document, optionally captioned. Telegram only allows documents to be grouped with other documents — MediaGroup.Build enforces it.
func (*MediaGroup) LivePhoto ¶
func (g *MediaGroup) LivePhoto(video, photo InputFile, caption ...string) *MediaGroup
LivePhoto adds a live photo — its motion video plus the static photo, optionally captioned. Live photos can't be sent by URL, only by file_id or upload.
func (*MediaGroup) Photo ¶
func (g *MediaGroup) Photo(media InputFile, caption ...string) *MediaGroup
Photo adds a photo, optionally captioned. Note only one item of an album needs a caption — it becomes the album's caption when it's the only one.
func (*MediaGroup) Send ¶
func (g *MediaGroup) Send(c *Ctx) ([]Message, error)
Send builds the album and sends it into whichever chat this update relates to, propagating the source message's business connection and forum topic like Ctx.Answer does. Returns the sent messages (one per album item).
func (*MediaGroup) Video ¶
func (g *MediaGroup) Video(media InputFile, caption ...string) *MediaGroup
Video adds a video, optionally captioned.
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage is an in-process FSMStorage. It's the default storage every TelegramBot starts with — state is lost on restart, which is fine for development and many simple bots; swap in a persistent FSMStorage via TelegramBot.SetFSMStorage for production use across restarts.
By default entries live forever until a handler calls MemoryStorage.Clear — fine for short-lived dev bots, but a long-running one will accumulate an entry for every user who ever touched FSM and never finished. Use NewMemoryStorageWithTTL to evict idle conversations automatically.
func NewMemoryStorage ¶
func NewMemoryStorage() *MemoryStorage
NewMemoryStorage creates an in-process MemoryStorage with no expiry — entries live until a handler calls MemoryStorage.Clear or the process exits.
func NewMemoryStorageWithTTL ¶
func NewMemoryStorageWithTTL(ttl time.Duration) *MemoryStorage
NewMemoryStorageWithTTL evicts an entry once it's gone untouched for ttl. The TTL is sliding, not a fixed countdown from creation: every read or write on a key resets its clock, so a user actively working through a conversation never gets cut off mid-flow — only one that's gone idle for the full ttl gets cleaned up. Call MemoryStorage.Close when done to stop the background sweep goroutine.
func (*MemoryStorage) Clear ¶
func (s *MemoryStorage) Clear(_ context.Context, key StorageKey) error
Clear implements FSMStorage, resetting state and data and ending the conversation.
func (*MemoryStorage) Close ¶
func (s *MemoryStorage) Close()
Close stops the background eviction goroutine started by NewMemoryStorageWithTTL. Safe to call on a storage without TTL enabled, and safe to call more than once.
func (*MemoryStorage) GetData ¶
func (s *MemoryStorage) GetData(_ context.Context, key StorageKey) (map[string]any, error)
GetData implements FSMStorage.
func (*MemoryStorage) GetState ¶
func (s *MemoryStorage) GetState(_ context.Context, key StorageKey) (State, error)
GetState implements FSMStorage.
func (*MemoryStorage) SetData ¶
func (s *MemoryStorage) SetData(_ context.Context, key StorageKey, data map[string]any) error
SetData implements FSMStorage.
func (*MemoryStorage) SetState ¶
func (s *MemoryStorage) SetState(_ context.Context, key StorageKey, state State) error
SetState implements FSMStorage.
func (*MemoryStorage) UpdateData ¶
func (s *MemoryStorage) UpdateData(_ context.Context, key StorageKey, partial map[string]any) (map[string]any, error)
UpdateData implements FSMStorage.
type MenuButton ¶
type MenuButton interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the bot's menu button in a private chat. It should be one of If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands.
type MenuButtonCommands ¶
type MenuButtonCommands struct {
// Type of the button, must be commands
Type string `json:"type"`
}
Represents a menu button, which opens the bot's list of commands.
func (*MenuButtonCommands) GetType ¶
func (v *MenuButtonCommands) GetType() string
The Get* methods below implement MenuButton: fields shared by every member, callable on the interface value directly without a type switch.
type MenuButtonDefault ¶
type MenuButtonDefault struct {
// Type of the button, must be default
Type string `json:"type"`
}
Describes that no specific value for the menu button was set.
func (*MenuButtonDefault) GetType ¶
func (v *MenuButtonDefault) GetType() string
type MenuButtonWebApp ¶
type MenuButtonWebApp struct {
// Type of the button, must be web_app
Type string `json:"type"`
// Text on the button
Text string `json:"text"`
// Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Alternatively, a t.me link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link.
WebApp *WebAppInfo `json:"web_app"`
}
Represents a menu button, which launches a Web App.
func (*MenuButtonWebApp) GetType ¶
func (v *MenuButtonWebApp) GetType() string
type Message ¶
type Message struct {
// Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.
MessageID int64 `json:"message_id"`
// Optional. Unique identifier of a message thread or forum topic to which the message belongs; for supergroups and private chats only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Optional. Information about the direct messages chat topic that contains the message
DirectMessagesTopic *DirectMessagesTopic `json:"direct_messages_topic,omitempty"`
// Optional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats.
From *User `json:"from,omitempty"`
// Optional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats.
SenderChat *Chat `json:"sender_chat,omitempty"`
// Optional. If the sender of the message boosted the chat, the number of boosts added by the user
SenderBoostCount int64 `json:"sender_boost_count,omitempty"`
// Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.
SenderBusinessBot *User `json:"sender_business_bot,omitempty"`
// Optional. Tag or custom title of the sender of the message; for supergroups only
SenderTag string `json:"sender_tag,omitempty"`
// Date the message was sent in Unix time. It is always a positive number, representing a valid date.
Date int64 `json:"date"`
// Optional. The unique identifier for the guest query. Use this identifier with the method answerGuestQuery to send a response message. If non-empty, the message belongs to the chat where the guest bot was summoned, which may not coincide with other existing bot chats sharing the same identifier.
GuestQueryID string `json:"guest_query_id,omitempty"`
// Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Chat the message belongs to
Chat *Chat `json:"chat"`
// Optional. Information about the original message for forwarded messages
ForwardOrigin MessageOrigin `json:"forward_origin,omitempty"`
// Optional. True, if the message is sent to a topic in a forum supergroup or a private chat with the bot
IsTopicMessage bool `json:"is_topic_message,omitempty"`
// Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
IsAutomaticForward bool `json:"is_automatic_forward,omitempty"`
// Optional. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
ReplyToMessage *Message `json:"reply_to_message,omitempty"`
// Optional. Information about the message that is being replied to, which may come from another chat or forum topic
ExternalReply *ExternalReplyInfo `json:"external_reply,omitempty"`
// Optional. For replies that quote part of the original message, the quoted part of the message
Quote *TextQuote `json:"quote,omitempty"`
// Optional. For replies to a story, the original story
ReplyToStory *Story `json:"reply_to_story,omitempty"`
// Optional. Identifier of the specific checklist task that is being replied to
ReplyToChecklistTaskID int64 `json:"reply_to_checklist_task_id,omitempty"`
// Optional. Persistent identifier of the specific poll option that is being replied to
ReplyToPollOptionID string `json:"reply_to_poll_option_id,omitempty"`
// Optional. Bot through which the message was sent
ViaBot *User `json:"via_bot,omitempty"`
// Optional. For a message sent by a guest bot, this is the user whose original message triggered the bot's response
GuestBotCallerUser *User `json:"guest_bot_caller_user,omitempty"`
// Optional. For a message sent by a guest bot, this is the chat whose original message triggered the bot's response
GuestBotCallerChat *Chat `json:"guest_bot_caller_chat,omitempty"`
// Optional. Date the message was last edited in Unix time
EditDate int64 `json:"edit_date,omitempty"`
// Optional. True, if the message can't be forwarded
HasProtectedContent bool `json:"has_protected_content,omitempty"`
// Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message
IsFromOffline bool `json:"is_from_offline,omitempty"`
// Optional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can't be edited.
IsPaidPost bool `json:"is_paid_post,omitempty"`
// Optional. The unique identifier inside this chat of a media message group this message belongs to
MediaGroupID string `json:"media_group_id,omitempty"`
// Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator
AuthorSignature string `json:"author_signature,omitempty"`
// Optional. The number of Telegram Stars that were paid by the sender of the message to send it
PaidStarCount int64 `json:"paid_star_count,omitempty"`
// Optional. For text messages, the actual UTF-8 text of the message
Text string `json:"text,omitempty"`
// Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
Entities []MessageEntity `json:"entities,omitempty"`
// Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
// Optional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can't be edited.
SuggestedPostInfo *SuggestedPostInfo `json:"suggested_post_info,omitempty"`
// Optional. Unique identifier of the message effect added to the message
EffectID string `json:"effect_id,omitempty"`
// Optional. Message is a rich formatted message
RichMessage *RichMessage `json:"rich_message,omitempty"`
// Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set.
Animation *Animation `json:"animation,omitempty"`
// Optional. Message is an audio file, information about the file
Audio *Audio `json:"audio,omitempty"`
// Optional. Message is a general file, information about the file
Document *Document `json:"document,omitempty"`
// Optional. Message is a live photo, information about the live photo. For backward compatibility, when this field is set, the photo field will also be set.
LivePhoto *LivePhoto `json:"live_photo,omitempty"`
// Optional. Message contains paid media; information about the paid media
PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"`
// Optional. Message is a photo, available sizes of the photo
Photo []PhotoSize `json:"photo,omitempty"`
// Optional. Message is a sticker, information about the sticker
Sticker *Sticker `json:"sticker,omitempty"`
// Optional. Message is a forwarded story
Story *Story `json:"story,omitempty"`
// Optional. Message is a video, information about the video
Video *Video `json:"video,omitempty"`
// Optional. Message is a video note, information about the video message
VideoNote *VideoNote `json:"video_note,omitempty"`
// Optional. Message is a voice message, information about the file
Voice *Voice `json:"voice,omitempty"`
// Optional. Caption for the animation, audio, document, paid media, photo, video or voice
Caption string `json:"caption,omitempty"`
// Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Optional. True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Optional. True, if the message media is covered by a spoiler animation
HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"`
// Optional. Message is a checklist
Checklist *Checklist `json:"checklist,omitempty"`
// Optional. Message is a shared contact, information about the contact
Contact *Contact `json:"contact,omitempty"`
// Optional. Message is a dice with random value
Dice *Dice `json:"dice,omitempty"`
// Optional. Message is a game, information about the game. More about games »
Game *Game `json:"game,omitempty"`
// Optional. Message is a native poll, information about the poll
Poll *Poll `json:"poll,omitempty"`
// Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set.
Venue *Venue `json:"venue,omitempty"`
// Optional. Message is a shared location, information about the location
Location *Location `json:"location,omitempty"`
// Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)
NewChatMembers []User `json:"new_chat_members,omitempty"`
// Optional. A member was removed from the group, information about them (this member may be the bot itself)
LeftChatMember *User `json:"left_chat_member,omitempty"`
// Optional. Service message: chat owner has left
ChatOwnerLeft *ChatOwnerLeft `json:"chat_owner_left,omitempty"`
// Optional. Service message: chat owner has changed
ChatOwnerChanged *ChatOwnerChanged `json:"chat_owner_changed,omitempty"`
// Optional. A chat title was changed to this value
NewChatTitle string `json:"new_chat_title,omitempty"`
// Optional. A chat photo was change to this value
NewChatPhoto []PhotoSize `json:"new_chat_photo,omitempty"`
// Optional. Service message: the chat photo was deleted
DeleteChatPhoto bool `json:"delete_chat_photo,omitempty"`
// Optional. Service message: the group has been created
GroupChatCreated bool `json:"group_chat_created,omitempty"`
// Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
SupergroupChatCreated bool `json:"supergroup_chat_created,omitempty"`
// Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.
ChannelChatCreated bool `json:"channel_chat_created,omitempty"`
// Optional. Service message: auto-delete timer settings changed in the chat
MessageAutoDeleteTimerChanged *MessageAutoDeleteTimerChanged `json:"message_auto_delete_timer_changed,omitempty"`
// Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
MigrateToChatID int64 `json:"migrate_to_chat_id,omitempty"`
// Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
MigrateFromChatID int64 `json:"migrate_from_chat_id,omitempty"`
// Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
PinnedMessage *Message `json:"pinned_message,omitempty"`
// Optional. Message is an invoice for a payment, information about the invoice. More about payments »
Invoice *Invoice `json:"invoice,omitempty"`
// Optional. Message is a service message about a successful payment, information about the payment. More about payments »
SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"`
// Optional. Message is a service message about a refunded payment, information about the payment. More about payments »
RefundedPayment *RefundedPayment `json:"refunded_payment,omitempty"`
UsersShared *UsersShared `json:"users_shared,omitempty"`
ChatShared *ChatShared `json:"chat_shared,omitempty"`
// Optional. Service message: a regular gift was sent or received
Gift *GiftInfo `json:"gift,omitempty"`
// Optional. Service message: a unique gift was sent or received
UniqueGift *UniqueGiftInfo `json:"unique_gift,omitempty"`
// Optional. Service message: upgrade of a gift was purchased after the gift was sent
GiftUpgradeSent *GiftInfo `json:"gift_upgrade_sent,omitempty"`
// Optional. The domain name of the website on which the user has logged in. More about Telegram Login »
ConnectedWebsite string `json:"connected_website,omitempty"`
// Optional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess
WriteAccessAllowed *WriteAccessAllowed `json:"write_access_allowed,omitempty"`
// Optional. Telegram Passport data
PassportData *PassportData `json:"passport_data,omitempty"`
// Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered,omitempty"`
// Optional. Service message: user boosted the chat
BoostAdded *ChatBoostAdded `json:"boost_added,omitempty"`
// Optional. Service message: chat background set
ChatBackgroundSet *ChatBackground `json:"chat_background_set,omitempty"`
// Optional. Service message: some tasks in a checklist were marked as done or not done
ChecklistTasksDone *ChecklistTasksDone `json:"checklist_tasks_done,omitempty"`
// Optional. Service message: tasks were added to a checklist
ChecklistTasksAdded *ChecklistTasksAdded `json:"checklist_tasks_added,omitempty"`
// Optional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed
DirectMessagePriceChanged *DirectMessagePriceChanged `json:"direct_message_price_changed,omitempty"`
// Optional. Service message: forum topic created
ForumTopicCreated *ForumTopicCreated `json:"forum_topic_created,omitempty"`
// Optional. Service message: forum topic edited
ForumTopicEdited *ForumTopicEdited `json:"forum_topic_edited,omitempty"`
// Optional. Service message: forum topic closed
ForumTopicClosed *ForumTopicClosed `json:"forum_topic_closed,omitempty"`
// Optional. Service message: forum topic reopened
ForumTopicReopened *ForumTopicReopened `json:"forum_topic_reopened,omitempty"`
// Optional. Service message: the 'General' forum topic hidden
GeneralForumTopicHidden *GeneralForumTopicHidden `json:"general_forum_topic_hidden,omitempty"`
GeneralForumTopicUnhidden *GeneralForumTopicUnhidden `json:"general_forum_topic_unhidden,omitempty"`
// Optional. Service message: a scheduled giveaway was created
GiveawayCreated *GiveawayCreated `json:"giveaway_created,omitempty"`
// Optional. The message is a scheduled giveaway message
Giveaway *Giveaway `json:"giveaway,omitempty"`
// Optional. A giveaway with public winners was completed
GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"`
// Optional. Service message: a giveaway without public winners was completed
GiveawayCompleted *GiveawayCompleted `json:"giveaway_completed,omitempty"`
// Optional. Service message: user created a bot that will be managed by the current bot
ManagedBotCreated *ManagedBotCreated `json:"managed_bot_created,omitempty"`
// Optional. Service message: the price for paid messages has changed in the chat
PaidMessagePriceChanged *PaidMessagePriceChanged `json:"paid_message_price_changed,omitempty"`
// Optional. Service message: answer option was added to a poll
PollOptionAdded *PollOptionAdded `json:"poll_option_added,omitempty"`
// Optional. Service message: answer option was deleted from a poll
PollOptionDeleted *PollOptionDeleted `json:"poll_option_deleted,omitempty"`
// Optional. Service message: a suggested post was approved
SuggestedPostApproved *SuggestedPostApproved `json:"suggested_post_approved,omitempty"`
// Optional. Service message: approval of a suggested post has failed
SuggestedPostApprovalFailed *SuggestedPostApprovalFailed `json:"suggested_post_approval_failed,omitempty"`
// Optional. Service message: a suggested post was declined
SuggestedPostDeclined *SuggestedPostDeclined `json:"suggested_post_declined,omitempty"`
// Optional. Service message: payment for a suggested post was received
SuggestedPostPaid *SuggestedPostPaid `json:"suggested_post_paid,omitempty"`
// Optional. Service message: payment for a suggested post was refunded
SuggestedPostRefunded *SuggestedPostRefunded `json:"suggested_post_refunded,omitempty"`
// Optional. Service message: video chat scheduled
VideoChatScheduled *VideoChatScheduled `json:"video_chat_scheduled,omitempty"`
// Optional. Service message: video chat started
VideoChatStarted *VideoChatStarted `json:"video_chat_started,omitempty"`
// Optional. Service message: video chat ended
VideoChatEnded *VideoChatEnded `json:"video_chat_ended,omitempty"`
// Optional. Service message: new participants invited to a video chat
VideoChatParticipantsInvited *VideoChatParticipantsInvited `json:"video_chat_participants_invited,omitempty"`
// Optional. Service message: data sent by a Web App
WebAppData *WebAppData `json:"web_app_data,omitempty"`
// Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
// contains filtered or unexported fields
}
This object represents a message.
func (*Message) Answer ¶
func (e *Message) Answer(text string, options ...*SendMessageOptions) (*Message, error)
Answer sends a message to the same chat and returns the sent message, enabling the send-then-edit progress flow:
m, err := message.Answer("⏳ working...")
// ... do work ...
m.EditText("✅ done")
Optional parameters ride in via SendMessageOptions:
message.Answer("text", &SendMessageOptions{ParseMode: "HTML"})
message.Answer("text", &SendMessageOptions{ReplyMarkup: keyboard})
func (*Message) Command ¶
func (e *Message) Command() *CommandObject
Command returns the parsed command this message carries, or nil if the message is not a command. Reads text-or-caption, so it agrees with FilterCommand on a captioned command. Handlers registered with FilterCommand use it to read arguments:
cmd := m.Command() // for "/start ref_12345" payload := cmd.Args // "ref_12345"
func (*Message) EditCaption ¶
func (e *Message) EditCaption(caption string, options ...*EditCaptionOptions) (*Message, error)
EditCaption edits this media message's caption and returns the edited message.
func (*Message) EditReplyMarkup ¶
func (e *Message) EditReplyMarkup(markup *InlineKeyboardMarkup) (*Message, error)
EditReplyMarkup edits only this message's inline keyboard and returns the edited message. Pass an empty (non-nil) *InlineKeyboardMarkup to remove the keyboard entirely — editMessageText's caveat applies here too: omitting ReplyMarkup leaves an existing keyboard untouched, it doesn't clear it.
func (*Message) EditText ¶
func (e *Message) EditText(text string, options ...*EditMessageOptions) (*Message, error)
EditText edits this message's text (and optionally its inline keyboard) and returns the edited message. To edit a different message in the chat, use TelegramBot.EditMessageText with an explicit message_id.
func (*Message) EntityText ¶
EntityText returns the substring of the message's text (or caption, for a media message) that e covers. Offset/Length are UTF-16 code units per the wire format, so this decodes through a UTF-16 round trip rather than slicing the Go string directly — a direct byte slice would cut a multi-byte character (most emoji) in half. Returns "" for an entity that doesn't fit the text (wrong message, stale offsets).
func (*Message) FSM ¶
func (e *Message) FSM() *FSMContext
FSM returns the conversation state context for the user who sent this message, scoped per the bot's FSMKeyStrategy (by default: this user in this chat).
func (*Message) FromID ¶
FromID returns the sender's user ID (0 for channel posts and other messages without a sender).
func (*Message) IsInaccessible ¶
IsInaccessible reports whether this is Telegram's InaccessibleMessage placeholder — a message the bot can no longer read (too old, or from before the bot joined), carrying only Chat, MessageID, and Date == 0. golagram flattens the spec's MaybeInaccessibleMessage union into Message (see types.gen.go), so this is the check that distinguishes the two — most relevant on CallbackQuery.Message.
func (*Message) Reply ¶
func (e *Message) Reply(text string, options ...*SendMessageOptions) (*Message, error)
Reply sends a reply to this message and returns the sent message. The reply target rides in reply_parameters; pass your own SendMessageOptions.ReplyParameters to override (e.g. to quote a specific part of the message).
func (*Message) SendChatAction ¶
SendChatAction broadcasts a chat action (e.g. "typing", "upload_photo") into this message's chat — useful right before a slow operation so the user sees something happening in the meantime.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON decodes Message's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type MessageAutoDeleteTimerChanged ¶
type MessageAutoDeleteTimerChanged struct {
// New auto-delete time for messages in the chat; in seconds
MessageAutoDeleteTime int64 `json:"message_auto_delete_time"`
}
This object represents a service message about a change in auto-delete timer settings.
type MessageEntity ¶
type MessageEntity struct {
// Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag or #hashtag@chatusername), “cashtag” ($USD or $USD@chatusername), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time).
Type string `json:"type"`
// Offset in UTF-16 code units to the start of the entity
Offset int64 `json:"offset"`
// Length of the entity in UTF-16 code units
Length int64 `json:"length"`
// Optional. For “text_link” only, URL that will be opened after user taps on the text
URL string `json:"url,omitempty"`
// Optional. For “text_mention” only, the mentioned user
User *User `json:"user,omitempty"`
// Optional. For “pre” only, the programming language of the entity text
Language string `json:"language,omitempty"`
// Optional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker.
CustomEmojiID string `json:"custom_emoji_id,omitempty"`
// Optional. For “date_time” only, the Unix time associated with the entity
UnixTime int64 `json:"unix_time,omitempty"`
// Optional. For “date_time” only, the string that defines the formatting of the date and time. See date-time entity formatting for more details.
DateTimeFormat string `json:"date_time_format,omitempty"`
}
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.
type MessageID ¶
type MessageID struct {
// Unique message identifier. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent.
MessageID int64 `json:"message_id"`
}
This object represents a unique message identifier.
type MessageOrigin ¶
type MessageOrigin interface {
GetDate() int64
GetType() string
// contains filtered or unexported methods
}
This object describes the origin of a message. It can be one of
type MessageOriginChannel ¶
type MessageOriginChannel struct {
// Type of the message origin, always “channel”
Type string `json:"type"`
// Date the message was sent originally in Unix time
Date int64 `json:"date"`
// Channel chat to which the message was originally sent
Chat *Chat `json:"chat"`
// Unique message identifier inside the chat
MessageID int64 `json:"message_id"`
// Optional. Signature of the original post author
AuthorSignature string `json:"author_signature,omitempty"`
}
The message was originally sent to a channel chat.
func (*MessageOriginChannel) GetDate ¶
func (v *MessageOriginChannel) GetDate() int64
func (*MessageOriginChannel) GetType ¶
func (v *MessageOriginChannel) GetType() string
type MessageOriginChat ¶
type MessageOriginChat struct {
// Type of the message origin, always “chat”
Type string `json:"type"`
// Date the message was sent originally in Unix time
Date int64 `json:"date"`
// Chat that sent the message originally
SenderChat *Chat `json:"sender_chat"`
// Optional. For messages originally sent by an anonymous chat administrator, original message author signature
AuthorSignature string `json:"author_signature,omitempty"`
}
The message was originally sent on behalf of a chat to a group chat.
func (*MessageOriginChat) GetDate ¶
func (v *MessageOriginChat) GetDate() int64
func (*MessageOriginChat) GetType ¶
func (v *MessageOriginChat) GetType() string
type MessageOriginHiddenUser ¶
type MessageOriginHiddenUser struct {
// Type of the message origin, always “hidden_user”
Type string `json:"type"`
// Date the message was sent originally in Unix time
Date int64 `json:"date"`
// Name of the user that sent the message originally
SenderUserName string `json:"sender_user_name"`
}
The message was originally sent by an unknown user.
func (*MessageOriginHiddenUser) GetDate ¶
func (v *MessageOriginHiddenUser) GetDate() int64
func (*MessageOriginHiddenUser) GetType ¶
func (v *MessageOriginHiddenUser) GetType() string
type MessageOriginUser ¶
type MessageOriginUser struct {
// Type of the message origin, always “user”
Type string `json:"type"`
// Date the message was sent originally in Unix time
Date int64 `json:"date"`
// User that sent the message originally
SenderUser *User `json:"sender_user"`
}
The message was originally sent by a known user.
func (*MessageOriginUser) GetDate ¶
func (v *MessageOriginUser) GetDate() int64
The Get* methods below implement MessageOrigin: fields shared by every member, callable on the interface value directly without a type switch.
func (*MessageOriginUser) GetType ¶
func (v *MessageOriginUser) GetType() string
type MessageReactionCountUpdated ¶
type MessageReactionCountUpdated struct {
// The chat containing the message
Chat *Chat `json:"chat"`
// Unique message identifier inside the chat
MessageID int64 `json:"message_id"`
// Date of the change in Unix time
Date int64 `json:"date"`
// List of reactions that are present on the message
Reactions []ReactionCount `json:"reactions"`
}
This object represents reaction changes on a message with anonymous reactions.
type MessageReactionUpdated ¶
type MessageReactionUpdated struct {
// The chat containing the message the user reacted to
Chat *Chat `json:"chat"`
// Unique identifier of the message inside the chat
MessageID int64 `json:"message_id"`
// Optional. The user that changed the reaction, if the user isn't anonymous
User *User `json:"user,omitempty"`
// Optional. The chat on behalf of which the reaction was changed, if the user is anonymous
ActorChat *Chat `json:"actor_chat,omitempty"`
// Date of the change in Unix time
Date int64 `json:"date"`
// Previous list of reaction types that were set by the user
OldReaction []ReactionType `json:"old_reaction"`
// New list of reaction types that have been set by the user
NewReaction []ReactionType `json:"new_reaction"`
}
This object represents a change of a reaction on a message performed by a user.
func (*MessageReactionUpdated) UnmarshalJSON ¶
func (v *MessageReactionUpdated) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes MessageReactionUpdated's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type MiddlewareFunc ¶
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc wraps a HandlerFunc — the single middleware shape for every update kind, since handlers themselves are now unified on Ctx. Registered via Router.Use, this is "inner" middleware: it only runs once a specific registration's filters have already matched, wrapping that one handler — see OuterMiddlewareFunc for the outer/inner middleware distinction.
func CallbackAnswerMiddleware ¶
func CallbackAnswerMiddleware() MiddlewareFunc
CallbackAnswerMiddleware auto-answers any callback query left unanswered by its handler, after the handler returns — killing the class of bug where a handler forgets AnswerCallback and the client's loading spinner spins until Telegram gives up. A handler that already called Ctx.AnswerCallback (directly or via CallbackQuery.Answer) is left alone: CallbackQuery.Answered reports whether that happened.
func ChatActionMiddleware ¶
func ChatActionMiddleware() MiddlewareFunc
ChatActionMiddleware keeps a chat action ("typing", "upload_photo", ...) alive for the duration of a slow handler, reading which action from the FlagChatAction registration flag (see WithFlags). A handler with no flag set runs unaffected — this middleware is a no-op for it.
func I18nMiddleware ¶
func I18nMiddleware(t Translator) MiddlewareFunc
I18nMiddleware attaches a Translator to every dispatched update and resolves its locale: an FSM override saved by Ctx.SetLocale wins, then the sender's User.LanguageCode, then the translator's default.
Router.Use middleware is inner — it only wraps the handler of whichever registration already matched, so it runs *after* filters. That means a filter that itself wants translated matching (a reply-keyboard button whose label came from c.T — the standard menu pattern) always sees the untranslated key, because I18nMiddleware hasn't attached the translator yet at filter time. If any filter in the tree needs Ctx.T/Ctx.Locale, register I18nOuter via Router.UseOuter on the root router instead — same resolution, but it runs before filters:
r.UseOuter(gg.I18nOuter(translator))
Use plain I18nMiddleware only when nothing at filter time needs the locale (translated text lives solely in handler bodies):
r.Use(gg.I18nMiddleware(translator))
The FSM override lives in conversation data under a reserved key, so it follows the bot's FSMKeyStrategy and survives restarts on persistent storage.
func LoggingMiddleware ¶
func LoggingMiddleware(logger *slog.Logger) MiddlewareFunc
LoggingMiddleware logs one structured line per dispatched update through logger — kind, chat/user IDs (when the update carries them), and how long the handler took. Errors log at Error level, everything else at Info. This is per-request logging; WithLogger's *slog.Logger covers the dispatcher's own lifecycle/error messages, a different concern.
func RateLimitMiddleware ¶
func RateLimitMiddleware(rl *RateLimiter, onLimited func(c *Ctx) error) MiddlewareFunc
RateLimitMiddleware throttles per sender (c.From().ID) via rl. An update with no identifiable sender (e.g. a channel post) passes through unthrottled — there's no per-user key to bucket it by. A throttled update is dropped silently: onLimited, if non-nil, runs instead of the handler (e.g. to reply "slow down"); pass nil to just drop.
func RateLimitMiddlewareBySender ¶
func RateLimitMiddlewareBySender(rl *RateLimiter, onLimited func(c *Ctx) error) MiddlewareFunc
RateLimitMiddlewareBySender is RateLimitMiddleware, keyed by Ctx.Sender instead of c.From().ID. RateLimitMiddleware treats an anonymous group admin or a channel post as unidentifiable — c.From() is either Telegram's shared dummy user or nil — and lets every one of them through unthrottled, since bucketing them all under one dummy ID would throttle every anonymous admin across every chat together. This buckets by Sender().ID() instead: an anonymous admin is throttled per chat and a channel post is throttled per channel (the only identity Telegram gives either), instead of passing all of them through unthrottled.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is golagram's composable, entity-based formatting builder. Unlike parse_mode strings (HTML/MarkdownV2), building a Node produces the exact MessageEntity list Telegram wants, so there's nothing to escape and nesting always renders correctly:
msg := gg.Text("Hi ", gg.Bold(user.FirstName), "! See ", gg.TextLink("the docs", "https://example.com"), ".")
text, entities := msg.Render()
c.Answer(text, &gg.SendMessageOptions{Entities: entities})
func Blockquote ¶
Blockquote renders its content as a block quotation.
func Code ¶
Code renders text as inline monospace. Unlike the other constructors it takes a plain string, not nested Nodes — Telegram's "code" entity has no meaningful nested formatting.
func CustomEmoji ¶
CustomEmoji renders text as a custom emoji sticker. text is normally the emoji's own placeholder character; customEmojiID comes from a sticker set (TelegramBot.GetCustomEmojiStickers).
func ExpandableBlockquote ¶
ExpandableBlockquote renders its content as a collapsed-by-default block quotation the user can expand.
func Mention ¶
Mention renders text as a clickable mention of user — for users without a @username, where a plain "@username" text_mention/mention entity can't be built from text alone.
func Pre ¶
Pre renders text as a monospace block, optionally syntax-highlighted for the given language (pass "" for none).
func Strikethrough ¶
Strikethrough renders its content struck through.
func Text ¶
Text groups plain strings and other Nodes into one Node, with no formatting of its own — the entry point for building a message: gg.Text("a ", gg.Bold("b"), " c").
type Option ¶
type Option func(*TelegramBot)
Option configures a TelegramBot at construction time.
func WithAllowedUpdates ¶
WithAllowedUpdates overrides which update kinds Telegram delivers (getUpdates'/setWebhook's allowed_updates). Several kinds — including message_reaction, message_reaction_count, and chat_member — are opt-in and simply won't arrive without this: a handler registered for one of them will compile and never fire, with no error. Without this option, golagram computes it automatically from whichever registration methods on Router were actually called (see Router.UsedUpdateKinds) once TelegramBot.Dispatch is set, so most bots never need to touch this directly.
func WithAutoRetry ¶
WithAutoRetry makes every API call transparently sleep and retry when Telegram returns a 429 flood-control error, instead of returning it straight to the caller — as many times as fit within maxWait's total budget (summed across all attempts for one call, using the server's own retry_after each time), then giving up and returning the *APIError like normal. Off by default (maxWait <= 0): flood control still surfaces as a normal error, exactly as before this existed — use IsFlood and AsAPIError to handle it yourself if you don't want automatic retry.
This is retry, not pacing: each call still blocks its own goroutine until Telegram lets it through, so a broadcast loop that fires many sends concurrently will still hit floods repeatedly instead of being throttled ahead of time. There's no proactive outbound rate limiter today — RateLimitMiddleware paces inbound updates per user, not outbound sends.
func WithBaseURL ¶
WithBaseURL points the bot at a custom Bot API server, e.g. a self-hosted telegram-bot-api instance or a fake server in tests.
func WithDropPendingUpdates ¶
func WithDropPendingUpdates() Option
WithDropPendingUpdates discards any updates that queued up while the bot wasn't running (or was running as a webhook) before TelegramBot.Run starts polling — useful after a redeploy when you don't want to process a backlog of stale updates. Applied once, at the start of Run; TelegramBot.RunWebhook has its own equivalent via WebhookConfig.DropPendingUpdates (a real setWebhook parameter — polling's getUpdates has no such parameter, so this approximates it by fast-forwarding past everything queued so far).
func WithFSMKeyStrategy ¶
func WithFSMKeyStrategy(s FSMKeyStrategy) Option
WithFSMKeyStrategy sets how conversation state is scoped (default: FSMKeyChatUser — independent state per user per chat). See FSMKeyStrategy for the alternatives. The strategy also scopes the per-key dispatch lock, so updates sharing FSM state are processed serially and never race on it.
func WithFSMStorage ¶
func WithFSMStorage(storage FSMStorage) Option
WithFSMStorage sets the conversation-state backend (default: in-memory).
func WithHTTPClient ¶
WithHTTPClient replaces the HTTP client used for all Telegram API calls (proxies, custom transports, tighter timeouts).
func WithLogger ¶
WithLogger switches golagram's internal logging (dispatcher lifecycle, getUpdates/webhook errors, unrecovered handler errors that fall through to no TelegramBot.OnError) from plain log.Printf/log.Println to a structured *slog.Logger — every message still says the same thing, but now goes through your handler (JSON output, a level filter, request-scoped attributes via a wrapped logger, whatever you've configured slog for) instead of the standard library's bare text logger. Without this, golagram's log output is unchanged from before *slog.Logger existed here.
func WithPollTimeout ¶
WithPollTimeout sets the getUpdates long-poll timeout in seconds.
func WithSenderIdentity ¶
func WithSenderIdentity() Option
WithSenderIdentity makes FSM state keying resolve identity through Ctx.Sender instead of the update's raw c.From(). Without this, FSMKeyStrategy folds in c.From().ID() — which for an anonymous group admin or a channel post is Telegram's fixed dummy user (the same ID for every anonymous admin in every chat this bot runs in), so under FSMKeyChatUser two different anonymous admins in the same group collide onto one conversation, and under FSMKeyGlobalUser *every* anonymous admin across every chat collides onto one. WithSenderIdentity resolves that component from Sender().ID() instead — a chat's ID for its anonymous admins, a channel's ID for its posts — the only identity Telegram gives either, so state is at least scoped correctly per chat/channel instead of colliding across unrelated senders.
This only affects FSM keying. FilterFromSender and RateLimitMiddlewareBySender are separate, explicit opt-ins for the same Sender()-vs-From() distinction elsewhere.
func WithUpdateBuffer ¶
WithUpdateBuffer sets the size of the internal update queue that absorbs traffic spikes between polling and the workers.
func WithWorkers ¶
WithWorkers sets the number of concurrent update-processing workers.
func WithoutGetMe ¶
func WithoutGetMe() Option
WithoutGetMe skips the getMe network round-trip NewTelegramBot otherwise makes before returning — the only network I/O construction does, and otherwise an unconditional one with no caller-supplied context (a cold serverless start, a unit test with no fake Bot API server, CI with no network all pay for it or work around it).
TelegramBot.Me still works: the bot ID is the numeric prefix of the token itself (already shape-validated by the time this option runs), so it's derived locally instead of asked for. Username stays "" — Telegram never sends it back except from getMe — which means /cmd@bot mention matching (see FilterCommand) and username-based deep links don't work until it's populated. Call TelegramBot.LoadMe once, after construction, for whichever of those this bot actually needs.
type OrderInfo ¶
type OrderInfo struct {
// Optional. User name
Name string `json:"name,omitempty"`
// Optional. User's phone number
PhoneNumber string `json:"phone_number,omitempty"`
// Optional. User email
Email string `json:"email,omitempty"`
// Optional. User shipping address
ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"`
}
This object represents information about an order.
type OuterMiddlewareFunc ¶
OuterMiddlewareFunc wraps a router's entire dispatch attempt — every update that reaches this router, whether or not any of its registrations end up matching — unlike MiddlewareFunc, which only wraps the handler once a specific registration has already matched. This is the "outer" (pre-filter) vs "inner" (post-filter) distinction: register outer middleware via Router.UseOuter for anything that needs to run before filters can evaluate — most commonly loading data (a user record, a permission set) into Ctx via Ctx.Set so a later Filter or inner middleware can read it without a duplicate lookup — or for logging/metrics that should count every update this router saw, not just the ones it matched.
next's own (matched, err) return already reflects this router's own OnError handling for the matched-handler case, so outer middleware sees the settled outcome, not a raw handler error — the same as if it wrapped dispatch from the outside. An outer middleware that decides not to call next at all can return (true, err) to signal "I handled this myself" or (false, nil) to decline, letting a sibling route (or an ancestor router, if this one was reached via Include) keep trying.
func I18nOuter ¶
func I18nOuter(t Translator) OuterMiddlewareFunc
I18nOuter is I18nMiddleware's outer-middleware form: identical locale resolution, but registered via Router.UseOuter so it runs before any filter in the router (and its included sub-routers) evaluates — the fix for the ordering problem described on I18nMiddleware.
r.UseOuter(gg.I18nOuter(translator))
type OwnedGift ¶
type OwnedGift interface {
GetIsSaved() bool
GetOwnedGiftID() string
GetSendDate() int64
GetSenderUser() *User
GetType() string
// contains filtered or unexported methods
}
This object describes a gift received and owned by a user or a chat. Currently, it can be one of
type OwnedGiftRegular ¶
type OwnedGiftRegular struct {
// Type of the gift, always “regular”
Type string `json:"type"`
// Information about the regular gift
Gift *Gift `json:"gift"`
// Optional. Unique identifier of the gift for the bot; for gifts received on behalf of business accounts only
OwnedGiftID string `json:"owned_gift_id,omitempty"`
// Optional. Sender of the gift if it is a known user
SenderUser *User `json:"sender_user,omitempty"`
// Date the gift was sent in Unix time
SendDate int64 `json:"send_date"`
// Optional. Text of the message that was added to the gift
Text string `json:"text,omitempty"`
// Optional. Special entities that appear in the text
Entities []MessageEntity `json:"entities,omitempty"`
// Optional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them
IsPrivate bool `json:"is_private,omitempty"`
// Optional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only
IsSaved bool `json:"is_saved,omitempty"`
// Optional. True, if the gift can be upgraded to a unique gift; for gifts received on behalf of business accounts only
CanBeUpgraded bool `json:"can_be_upgraded,omitempty"`
// Optional. True, if the gift was refunded and isn't available anymore
WasRefunded bool `json:"was_refunded,omitempty"`
// Optional. Number of Telegram Stars that can be claimed by the receiver instead of the gift; omitted if the gift cannot be converted to Telegram Stars; for gifts received on behalf of business accounts only
ConvertStarCount int64 `json:"convert_star_count,omitempty"`
// Optional. Number of Telegram Stars that were paid for the ability to upgrade the gift
PrepaidUpgradeStarCount int64 `json:"prepaid_upgrade_star_count,omitempty"`
// Optional. True, if the gift's upgrade was purchased after the gift was sent; for gifts received on behalf of business accounts only
IsUpgradeSeparate bool `json:"is_upgrade_separate,omitempty"`
// Optional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift.
UniqueGiftNumber int64 `json:"unique_gift_number,omitempty"`
}
Describes a regular gift owned by a user or a chat.
func (*OwnedGiftRegular) GetIsSaved ¶
func (v *OwnedGiftRegular) GetIsSaved() bool
The Get* methods below implement OwnedGift: fields shared by every member, callable on the interface value directly without a type switch.
func (*OwnedGiftRegular) GetOwnedGiftID ¶
func (v *OwnedGiftRegular) GetOwnedGiftID() string
func (*OwnedGiftRegular) GetSendDate ¶
func (v *OwnedGiftRegular) GetSendDate() int64
func (*OwnedGiftRegular) GetSenderUser ¶
func (v *OwnedGiftRegular) GetSenderUser() *User
func (*OwnedGiftRegular) GetType ¶
func (v *OwnedGiftRegular) GetType() string
type OwnedGiftUnique ¶
type OwnedGiftUnique struct {
// Type of the gift, always “unique”
Type string `json:"type"`
// Information about the unique gift
Gift *UniqueGift `json:"gift"`
// Optional. Unique identifier of the received gift for the bot; for gifts received on behalf of business accounts only
OwnedGiftID string `json:"owned_gift_id,omitempty"`
// Optional. Sender of the gift if it is a known user
SenderUser *User `json:"sender_user,omitempty"`
// Date the gift was sent in Unix time
SendDate int64 `json:"send_date"`
// Optional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only
IsSaved bool `json:"is_saved,omitempty"`
// Optional. True, if the gift can be transferred to another owner; for gifts received on behalf of business accounts only
CanBeTransferred bool `json:"can_be_transferred,omitempty"`
// Optional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift
TransferStarCount int64 `json:"transfer_star_count,omitempty"`
// Optional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now.
NextTransferDate int64 `json:"next_transfer_date,omitempty"`
}
Describes a unique gift received and owned by a user or a chat.
func (*OwnedGiftUnique) GetIsSaved ¶
func (v *OwnedGiftUnique) GetIsSaved() bool
func (*OwnedGiftUnique) GetOwnedGiftID ¶
func (v *OwnedGiftUnique) GetOwnedGiftID() string
func (*OwnedGiftUnique) GetSendDate ¶
func (v *OwnedGiftUnique) GetSendDate() int64
func (*OwnedGiftUnique) GetSenderUser ¶
func (v *OwnedGiftUnique) GetSenderUser() *User
func (*OwnedGiftUnique) GetType ¶
func (v *OwnedGiftUnique) GetType() string
type OwnedGifts ¶
type OwnedGifts struct {
// The total number of gifts owned by the user or the chat
TotalCount int64 `json:"total_count"`
// The list of gifts
Gifts []OwnedGift `json:"gifts"`
// Optional. Offset for the next request. If empty, then there are no more results.
NextOffset string `json:"next_offset,omitempty"`
}
Contains the list of gifts received and owned by a user or a chat.
func (*OwnedGifts) UnmarshalJSON ¶
func (v *OwnedGifts) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes OwnedGifts's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type Pagination ¶
type Pagination struct {
// contains filtered or unexported fields
}
Pagination builds the standard « ‹ 3/10 › » inline-keyboard navigation row and routes its taps, so a paged list is one keyboard row and one handler:
var pages = gg.NewPagination("results")
// sending page 1:
kb := gg.NewInlineKeyboardMarkup([][]gg.InlineKeyboardButton{pages.Row(1, total)})
c.Answer(renderPage(1), &gg.SendMessageOptions{ReplyMarkup: kb})
// handling navigation taps:
r.CallbackQuery(pages.Filter()).Handle(func(c *gg.Ctx) error {
page, _ := pages.Page(c)
kb := gg.NewInlineKeyboardMarkup([][]gg.InlineKeyboardButton{pages.Row(page, total)})
if _, err := c.EditText(renderPage(page), &gg.EditMessageOptions{ReplyMarkup: kb}); err != nil {
return err
}
return c.AnswerCallback("")
})
The prefix namespaces the callback data, so several independent paginations coexist in one bot (and even one message).
func NewPagination ¶
func NewPagination(prefix string) *Pagination
NewPagination creates a pagination helper whose buttons carry callback data under the given prefix ("<prefix>:pg:<page>").
func (*Pagination) Filter ¶
func (p *Pagination) Filter() Filter
Filter matches callback queries from this pagination's navigation buttons — not the page indicator, which points nowhere. Combine it with other filters like any Filter.
func (*Pagination) Page ¶
func (p *Pagination) Page(c *Ctx) (int, bool)
Page extracts the tapped target page from a navigation callback. The bool is false when the update isn't one of this pagination's navigation taps (wrong prefix, the indicator button, not a callback query at all).
func (*Pagination) Row ¶
func (p *Pagination) Row(page, total int) []InlineKeyboardButton
Row returns the navigation row for the given 1-based page: first («) and previous (‹) on the left when there's anywhere to go back to, the "page/total" indicator in the middle, next (›) and last (») on the right. Buttons pointing nowhere are omitted, and jump buttons («/») only appear once they'd differ from the step buttons. Returns nil when total < 2 — a single page needs no navigation.
type PaidMedia ¶
type PaidMedia interface {
GetType() string
// contains filtered or unexported methods
}
This object describes paid media. Currently, it can be one of
type PaidMediaInfo ¶
type PaidMediaInfo struct {
// The number of Telegram Stars that must be paid to buy access to the media
StarCount int64 `json:"star_count"`
// Information about the paid media
PaidMedia []PaidMedia `json:"paid_media"`
}
Describes the paid media added to a message.
func (*PaidMediaInfo) UnmarshalJSON ¶
func (v *PaidMediaInfo) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes PaidMediaInfo's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type PaidMediaLivePhoto ¶
type PaidMediaLivePhoto struct {
// Type of the paid media, always “live_photo”
Type string `json:"type"`
// The photo
LivePhoto *LivePhoto `json:"live_photo"`
}
The paid media is a live photo.
func (*PaidMediaLivePhoto) GetType ¶
func (v *PaidMediaLivePhoto) GetType() string
The Get* methods below implement PaidMedia: fields shared by every member, callable on the interface value directly without a type switch.
type PaidMediaPhoto ¶
type PaidMediaPhoto struct {
// Type of the paid media, always “photo”
Type string `json:"type"`
// The photo
Photo []PhotoSize `json:"photo"`
}
The paid media is a photo.
func (*PaidMediaPhoto) GetType ¶
func (v *PaidMediaPhoto) GetType() string
type PaidMediaPreview ¶
type PaidMediaPreview struct {
// Type of the paid media, always “preview”
Type string `json:"type"`
// Optional. Media width as defined by the sender
Width int64 `json:"width,omitempty"`
// Optional. Media height as defined by the sender
Height int64 `json:"height,omitempty"`
// Optional. Duration of the media in seconds as defined by the sender
Duration int64 `json:"duration,omitempty"`
}
The paid media isn't available before the payment.
func (*PaidMediaPreview) GetType ¶
func (v *PaidMediaPreview) GetType() string
type PaidMediaPurchased ¶
type PaidMediaPurchased struct {
// User who purchased the media
From *User `json:"from"`
// Bot-specified paid media payload
PaidMediaPayload string `json:"paid_media_payload"`
}
This object contains information about a paid media purchase.
type PaidMediaVideo ¶
type PaidMediaVideo struct {
// Type of the paid media, always “video”
Type string `json:"type"`
// The video
Video *Video `json:"video"`
}
The paid media is a video.
func (*PaidMediaVideo) GetType ¶
func (v *PaidMediaVideo) GetType() string
type PaidMessagePriceChanged ¶
type PaidMessagePriceChanged struct {
// The new number of Telegram Stars that must be paid by non-administrator users of the supergroup chat for each sent message
PaidMessageStarCount int64 `json:"paid_message_star_count"`
}
Describes a service message about a change in the price of paid messages within a chat.
type PassportData ¶
type PassportData struct {
// Array with information about documents and other Telegram Passport elements that was shared with the bot
Data []EncryptedPassportElement `json:"data"`
// Encrypted credentials required to decrypt the data
Credentials *EncryptedCredentials `json:"credentials"`
}
Describes Telegram Passport data shared with the bot by the user.
type PassportElementError ¶
type PassportElementError interface {
GetMessage() string
GetSource() string
GetType() string
// contains filtered or unexported methods
}
This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:
type PassportElementErrorDataField ¶
type PassportElementErrorDataField struct {
// Error source, must be data
Source string `json:"source"`
// The section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”
Type string `json:"type"`
// Name of the data field which has the error
FieldName string `json:"field_name"`
// Base64-encoded data hash
DataHash string `json:"data_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes.
func (*PassportElementErrorDataField) GetMessage ¶
func (v *PassportElementErrorDataField) GetMessage() string
The Get* methods below implement PassportElementError: fields shared by every member, callable on the interface value directly without a type switch.
func (*PassportElementErrorDataField) GetSource ¶
func (v *PassportElementErrorDataField) GetSource() string
func (*PassportElementErrorDataField) GetType ¶
func (v *PassportElementErrorDataField) GetType() string
type PassportElementErrorFile ¶
type PassportElementErrorFile struct {
// Error source, must be file
Source string `json:"source"`
// The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
Type string `json:"type"`
// Base64-encoded file hash
FileHash string `json:"file_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.
func (*PassportElementErrorFile) GetMessage ¶
func (v *PassportElementErrorFile) GetMessage() string
func (*PassportElementErrorFile) GetSource ¶
func (v *PassportElementErrorFile) GetSource() string
func (*PassportElementErrorFile) GetType ¶
func (v *PassportElementErrorFile) GetType() string
type PassportElementErrorFiles ¶
type PassportElementErrorFiles struct {
// Error source, must be files
Source string `json:"source"`
// The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
Type string `json:"type"`
// List of base64-encoded file hashes
FileHashes []string `json:"file_hashes"`
// Error message
Message string `json:"message"`
}
Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.
func (*PassportElementErrorFiles) GetMessage ¶
func (v *PassportElementErrorFiles) GetMessage() string
func (*PassportElementErrorFiles) GetSource ¶
func (v *PassportElementErrorFiles) GetSource() string
func (*PassportElementErrorFiles) GetType ¶
func (v *PassportElementErrorFiles) GetType() string
type PassportElementErrorFrontSide ¶
type PassportElementErrorFrontSide struct {
// Error source, must be front_side
Source string `json:"source"`
// The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
Type string `json:"type"`
// Base64-encoded hash of the file with the front side of the document
FileHash string `json:"file_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.
func (*PassportElementErrorFrontSide) GetMessage ¶
func (v *PassportElementErrorFrontSide) GetMessage() string
func (*PassportElementErrorFrontSide) GetSource ¶
func (v *PassportElementErrorFrontSide) GetSource() string
func (*PassportElementErrorFrontSide) GetType ¶
func (v *PassportElementErrorFrontSide) GetType() string
type PassportElementErrorReverseSide ¶
type PassportElementErrorReverseSide struct {
// Error source, must be reverse_side
Source string `json:"source"`
// The section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card”
Type string `json:"type"`
// Base64-encoded hash of the file with the reverse side of the document
FileHash string `json:"file_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.
func (*PassportElementErrorReverseSide) GetMessage ¶
func (v *PassportElementErrorReverseSide) GetMessage() string
func (*PassportElementErrorReverseSide) GetSource ¶
func (v *PassportElementErrorReverseSide) GetSource() string
func (*PassportElementErrorReverseSide) GetType ¶
func (v *PassportElementErrorReverseSide) GetType() string
type PassportElementErrorSelfie ¶
type PassportElementErrorSelfie struct {
// Error source, must be selfie
Source string `json:"source"`
// The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
Type string `json:"type"`
// Base64-encoded hash of the file with the selfie
FileHash string `json:"file_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.
func (*PassportElementErrorSelfie) GetMessage ¶
func (v *PassportElementErrorSelfie) GetMessage() string
func (*PassportElementErrorSelfie) GetSource ¶
func (v *PassportElementErrorSelfie) GetSource() string
func (*PassportElementErrorSelfie) GetType ¶
func (v *PassportElementErrorSelfie) GetType() string
type PassportElementErrorTranslationFile ¶
type PassportElementErrorTranslationFile struct {
// Error source, must be translation_file
Source string `json:"source"`
// Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
Type string `json:"type"`
// Base64-encoded file hash
FileHash string `json:"file_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.
func (*PassportElementErrorTranslationFile) GetMessage ¶
func (v *PassportElementErrorTranslationFile) GetMessage() string
func (*PassportElementErrorTranslationFile) GetSource ¶
func (v *PassportElementErrorTranslationFile) GetSource() string
func (*PassportElementErrorTranslationFile) GetType ¶
func (v *PassportElementErrorTranslationFile) GetType() string
type PassportElementErrorTranslationFiles ¶
type PassportElementErrorTranslationFiles struct {
// Error source, must be translation_files
Source string `json:"source"`
// Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
Type string `json:"type"`
// List of base64-encoded file hashes
FileHashes []string `json:"file_hashes"`
// Error message
Message string `json:"message"`
}
Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change.
func (*PassportElementErrorTranslationFiles) GetMessage ¶
func (v *PassportElementErrorTranslationFiles) GetMessage() string
func (*PassportElementErrorTranslationFiles) GetSource ¶
func (v *PassportElementErrorTranslationFiles) GetSource() string
func (*PassportElementErrorTranslationFiles) GetType ¶
func (v *PassportElementErrorTranslationFiles) GetType() string
type PassportElementErrorUnspecified ¶
type PassportElementErrorUnspecified struct {
// Error source, must be unspecified
Source string `json:"source"`
// Type of element of the user's Telegram Passport which has the issue
Type string `json:"type"`
// Base64-encoded element hash
ElementHash string `json:"element_hash"`
// Error message
Message string `json:"message"`
}
Represents an issue in an unspecified place. The error is considered resolved when new data is added.
func (*PassportElementErrorUnspecified) GetMessage ¶
func (v *PassportElementErrorUnspecified) GetMessage() string
func (*PassportElementErrorUnspecified) GetSource ¶
func (v *PassportElementErrorUnspecified) GetSource() string
func (*PassportElementErrorUnspecified) GetType ¶
func (v *PassportElementErrorUnspecified) GetType() string
type PassportFile ¶
type PassportFile struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// File size in bytes
FileSize int64 `json:"file_size"`
// Unix time when the file was uploaded
FileDate int64 `json:"file_date"`
}
This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB.
type PhotoSize ¶
type PhotoSize struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Photo width
Width int64 `json:"width"`
// Photo height
Height int64 `json:"height"`
// Optional. File size in bytes
FileSize int64 `json:"file_size,omitempty"`
}
This object represents one size of a photo or a file / sticker thumbnail.
type PinChatMessageRequest ¶
type PinChatMessageRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Identifier of a message to pin
MessageID int64 `json:"message_id"`
// Unique identifier of the business connection on behalf of which the message will be pinned
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Pass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats.
DisableNotification bool `json:"disable_notification,omitempty"`
}
PinChatMessageRequest holds the parameters for pinChatMessage.
type PluralCategory ¶
type PluralCategory string
PluralCategory is a CLDR plural class a PluralRule maps a number to.
const ( PluralOne PluralCategory = "one" PluralFew PluralCategory = "few" PluralMany PluralCategory = "many" PluralOther PluralCategory = "other" )
type PluralRule ¶
type PluralRule func(n int) PluralCategory
PluralRule picks the plural category for a count (integer counts only — fractional CLDR rules are out of scope for the built-in translator).
type Poll ¶
type Poll struct {
// Unique poll identifier
ID string `json:"id"`
// Poll question, 1-300 characters
Question string `json:"question"`
// Optional. Special entities that appear in the question. Currently, only custom emoji entities are allowed in poll questions
QuestionEntities []MessageEntity `json:"question_entities,omitempty"`
// List of poll options
Options []PollOption `json:"options"`
// Total number of users that voted in the poll
TotalVoterCount int64 `json:"total_voter_count"`
// True, if the poll is closed
IsClosed bool `json:"is_closed"`
// True, if the poll is anonymous
IsAnonymous bool `json:"is_anonymous"`
// Poll type, currently can be “regular” or “quiz”
Type string `json:"type"`
// True, if the poll allows multiple answers
AllowsMultipleAnswers bool `json:"allows_multiple_answers"`
// True, if the poll allows to change the chosen answer options
AllowsRevoting bool `json:"allows_revoting"`
// True if voting is limited to users who have been members of the chat where the poll was originally sent for more than 24 hours
MembersOnly bool `json:"members_only"`
// Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll. The country code “FT” is used for users with anonymous numbers. If omitted, then users from any country can participate in the poll.
CountryCodes []string `json:"country_codes,omitempty"`
// Optional. Array of 0-based identifiers of the correct answer options. Available only for polls in quiz mode which are closed or were sent (not forwarded) by the bot or to the private chat with the bot.
CorrectOptionIds []int64 `json:"correct_option_ids,omitempty"`
// Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters
Explanation string `json:"explanation,omitempty"`
// Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation
ExplanationEntities []MessageEntity `json:"explanation_entities,omitempty"`
// Optional. Media added to the quiz explanation
ExplanationMedia *PollMedia `json:"explanation_media,omitempty"`
// Optional. Amount of time in seconds the poll will be active after creation
OpenPeriod int64 `json:"open_period,omitempty"`
// Optional. Point in time (Unix timestamp) when the poll will be automatically closed
CloseDate int64 `json:"close_date,omitempty"`
// Optional. Description of the poll; for polls inside the Message object only
Description string `json:"description,omitempty"`
// Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the description
DescriptionEntities []MessageEntity `json:"description_entities,omitempty"`
// Optional. Media added to the poll description; for polls inside the Message object only
Media *PollMedia `json:"media,omitempty"`
}
This object contains information about a poll.
type PollAnswer ¶
type PollAnswer struct {
// Unique poll identifier
PollID string `json:"poll_id"`
// Optional. The chat that changed the answer to the poll, if the voter is anonymous
VoterChat *Chat `json:"voter_chat,omitempty"`
// Optional. The user that changed the answer to the poll, if the voter isn't anonymous
User *User `json:"user,omitempty"`
// 0-based identifiers of chosen answer options. May be empty if the vote was retracted.
OptionIds []int64 `json:"option_ids"`
// Persistent identifiers of the chosen answer options. May be empty if the vote was retracted.
OptionPersistentIds []string `json:"option_persistent_ids"`
}
This object represents an answer of a user in a non-anonymous poll.
type PollMedia ¶
type PollMedia struct {
// Optional. Media is an animation, information about the animation
Animation *Animation `json:"animation,omitempty"`
// Optional. Media is an audio file, information about the file; currently, can't be received in a poll option
Audio *Audio `json:"audio,omitempty"`
// Optional. Media is a general file, information about the file; currently, can't be received in a poll option
Document *Document `json:"document,omitempty"`
// Optional. The HTTP link attached to the poll option
Link *Link `json:"link,omitempty"`
// Optional. Media is a live photo, information about the live photo
LivePhoto *LivePhoto `json:"live_photo,omitempty"`
// Optional. Media is a shared location, information about the location
Location *Location `json:"location,omitempty"`
// Optional. Media is a photo, available sizes of the photo
Photo []PhotoSize `json:"photo,omitempty"`
// Optional. Media is a sticker, information about the sticker; currently, for poll options only
Sticker *Sticker `json:"sticker,omitempty"`
// Optional. Media is a venue, information about the venue
Venue *Venue `json:"venue,omitempty"`
// Optional. Media is a video, information about the video
Video *Video `json:"video,omitempty"`
}
At most one of the optional fields can be present in any given object.
type PollOption ¶
type PollOption struct {
// Unique identifier of the option, persistent on option addition and deletion
PersistentID string `json:"persistent_id"`
// Option text, 1-100 characters
Text string `json:"text"`
// Optional. Special entities that appear in the option text. Currently, only custom emoji entities are allowed in poll option texts
TextEntities []MessageEntity `json:"text_entities,omitempty"`
// Optional. Media added to the poll option
Media *PollMedia `json:"media,omitempty"`
// Number of users who voted for this option; may be 0 if unknown
VoterCount int64 `json:"voter_count"`
// Optional. User who added the option; omitted if the option wasn't added by a user after poll creation
AddedByUser *User `json:"added_by_user,omitempty"`
// Optional. Chat that added the option; omitted if the option wasn't added by a chat after poll creation
AddedByChat *Chat `json:"added_by_chat,omitempty"`
// Optional. Point in time (Unix timestamp) when the option was added; omitted if the option existed in the original poll
AdditionDate int64 `json:"addition_date,omitempty"`
}
This object contains information about one answer option in a poll.
type PollOptionAdded ¶
type PollOptionAdded struct {
// Optional. Message containing the poll to which the option was added, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
PollMessage *Message `json:"poll_message,omitempty"`
// Unique identifier of the added option
OptionPersistentID string `json:"option_persistent_id"`
// Option text
OptionText string `json:"option_text"`
// Optional. Special entities that appear in the option_text
OptionTextEntities []MessageEntity `json:"option_text_entities,omitempty"`
}
Describes a service message about an option added to a poll.
type PollOptionDeleted ¶
type PollOptionDeleted struct {
// Optional. Message containing the poll from which the option was deleted, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
PollMessage *Message `json:"poll_message,omitempty"`
// Unique identifier of the deleted option
OptionPersistentID string `json:"option_persistent_id"`
// Option text
OptionText string `json:"option_text"`
// Optional. Special entities that appear in the option_text
OptionTextEntities []MessageEntity `json:"option_text_entities,omitempty"`
}
Describes a service message about an option deleted from a poll.
type PostStoryRequest ¶
type PostStoryRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Content of the story
Content InputStoryContent `json:"content"`
// Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
ActivePeriod int64 `json:"active_period"`
// Caption of the story, 0-2048 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the story caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// A JSON-serialized list of clickable areas to be shown on the story
Areas []StoryArea `json:"areas,omitempty"`
// Pass True to keep the story accessible after it expires
PostToChatPage bool `json:"post_to_chat_page,omitempty"`
// Pass True if the content of the story must be protected from forwarding and screenshotting
ProtectContent bool `json:"protect_content,omitempty"`
}
PostStoryRequest holds the parameters for postStory.
type PreCheckoutQuery ¶
type PreCheckoutQuery struct {
// Unique query identifier
ID string `json:"id"`
// User who sent the query
From *User `json:"from"`
// Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars
Currency string `json:"currency"`
// Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
TotalAmount int64 `json:"total_amount"`
// Bot-specified invoice payload
InvoicePayload string `json:"invoice_payload"`
// Optional. Identifier of the shipping option chosen by the user
ShippingOptionID string `json:"shipping_option_id,omitempty"`
// Optional. Order information provided by the user
OrderInfo *OrderInfo `json:"order_info,omitempty"`
}
This object contains information about an incoming pre-checkout query.
type PreparedInlineMessage ¶
type PreparedInlineMessage struct {
// Unique identifier of the prepared message
ID string `json:"id"`
// Expiration date of the prepared message, in Unix time. Expired prepared messages can no longer be used.
ExpirationDate int64 `json:"expiration_date"`
}
Describes an inline message to be sent by a user of a Mini App.
type PreparedKeyboardButton ¶
type PreparedKeyboardButton struct {
// Unique identifier of the keyboard button
ID string `json:"id"`
}
Describes a keyboard button to be used by a user of a Mini App.
type PromoteChatMemberRequest ¶
type PromoteChatMemberRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Pass True if the administrator's presence in the chat is hidden
IsAnonymous bool `json:"is_anonymous,omitempty"`
// Pass True if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege.
CanManageChat bool `json:"can_manage_chat,omitempty"`
// Pass True if the administrator can delete messages of other users
CanDeleteMessages bool `json:"can_delete_messages,omitempty"`
// Pass True if the administrator can manage video chats
CanManageVideoChats bool `json:"can_manage_video_chats,omitempty"`
// Pass True if the administrator can restrict, ban or unban chat members, or access supergroup statistics. For backward compatibility, defaults to True for promotions of channel administrators.
CanRestrictMembers *bool `json:"can_restrict_members,omitempty"`
// Pass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him)
CanPromoteMembers bool `json:"can_promote_members,omitempty"`
// Pass True if the administrator can change chat title, photo and other settings
CanChangeInfo bool `json:"can_change_info,omitempty"`
// Pass True if the administrator can invite new users to the chat
CanInviteUsers bool `json:"can_invite_users,omitempty"`
// Pass True if the administrator can post stories to the chat
CanPostStories bool `json:"can_post_stories,omitempty"`
// Pass True if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive
CanEditStories bool `json:"can_edit_stories,omitempty"`
// Pass True if the administrator can delete stories posted by other users
CanDeleteStories bool `json:"can_delete_stories,omitempty"`
// Pass True if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only
CanPostMessages bool `json:"can_post_messages,omitempty"`
// Pass True if the administrator can edit messages of other users and can pin messages; for channels only
CanEditMessages bool `json:"can_edit_messages,omitempty"`
// Pass True if the administrator can pin messages; for supergroups only
CanPinMessages bool `json:"can_pin_messages,omitempty"`
// Pass True if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only
CanManageTopics bool `json:"can_manage_topics,omitempty"`
// Pass True if the administrator can manage direct messages within the channel and decline suggested posts; for channels only
CanManageDirectMessages bool `json:"can_manage_direct_messages,omitempty"`
// Pass True if the administrator can edit the tags of regular members; for groups and supergroups only
CanManageTags bool `json:"can_manage_tags,omitempty"`
}
PromoteChatMemberRequest holds the parameters for promoteChatMember.
type ProximityAlertTriggered ¶
type ProximityAlertTriggered struct {
// User that triggered the alert
Traveler *User `json:"traveler"`
// User that set the alert
Watcher *User `json:"watcher"`
// The distance between the users
Distance int64 `json:"distance"`
}
This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter is a per-key token bucket: rate tokens/second refill, burst tokens capacity. Idle keys (untouched for idleTTL) are swept by a background goroutine so a long-running bot doesn't accumulate one bucket per visitor forever — the same sliding-eviction shape as NewMemoryStorageWithTTL, applied to rate limiting instead of FSM state.
func NewRateLimiter ¶
func NewRateLimiter(rate float64, burst int, idleTTL time.Duration) *RateLimiter
NewRateLimiter creates a limiter allowing `rate` events per second per key, with bursts up to `burst`. idleTTL controls how long an untouched key's bucket is kept before being evicted; pass 0 for a sensible default (10x the time to refill one token, floored at a minute). Call RateLimiter.Close when done to stop the background sweep goroutine.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key int64) bool
Allow reports whether the caller identified by key may proceed right now, consuming one token if so.
func (*RateLimiter) Close ¶
func (rl *RateLimiter) Close()
Close stops the background eviction goroutine. Safe to call more than once.
type ReactionCount ¶
type ReactionCount struct {
// Type of the reaction
Type ReactionType `json:"type"`
// Number of times the reaction was added
TotalCount int64 `json:"total_count"`
}
Represents a reaction added to a message along with the number of times it was added.
func (*ReactionCount) UnmarshalJSON ¶
func (v *ReactionCount) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes ReactionCount's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type ReactionType ¶
type ReactionType interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the type of a reaction. Currently, it can be one of
type ReactionTypeCustomEmoji ¶
type ReactionTypeCustomEmoji struct {
// Type of the reaction, always “custom_emoji”
Type string `json:"type"`
// Custom emoji identifier
CustomEmojiID string `json:"custom_emoji_id"`
}
The reaction is based on a custom emoji.
func (*ReactionTypeCustomEmoji) GetType ¶
func (v *ReactionTypeCustomEmoji) GetType() string
type ReactionTypeEmoji ¶
type ReactionTypeEmoji struct {
// Type of the reaction, always “emoji”
Type string `json:"type"`
// Reaction emoji. Currently, it can be one of "❤", "👍", "👎", "🔥", "🥰", "👏", "😁", "🤔", "🤯", "😱", "🤬", "😢", "🎉", "🤩", "🤮", "💩", "🙏", "👌", "🕊", "🤡", "🥱", "🥴", "😍", "🐳", "❤🔥", "🌚", "🌭", "💯", "🤣", "⚡", "🍌", "🏆", "💔", "🤨", "😐", "🍓", "🍾", "💋", "🖕", "😈", "😴", "😭", "🤓", "👻", "👨💻", "👀", "🎃", "🙈", "😇", "😨", "🤝", "✍", "🤗", "🫡", "🎅", "🎄", "☃", "💅", "🤪", "🗿", "🆒", "💘", "🙉", "🦄", "😘", "💊", "🙊", "😎", "👾", "🤷♂", "🤷", "🤷♀", "😡".
Emoji string `json:"emoji"`
}
The reaction is based on an emoji.
func (*ReactionTypeEmoji) GetType ¶
func (v *ReactionTypeEmoji) GetType() string
The Get* methods below implement ReactionType: fields shared by every member, callable on the interface value directly without a type switch.
type ReactionTypePaid ¶
type ReactionTypePaid struct {
// Type of the reaction, always “paid”
Type string `json:"type"`
}
The reaction is paid.
func (*ReactionTypePaid) GetType ¶
func (v *ReactionTypePaid) GetType() string
type ReadBusinessMessageRequest ¶
type ReadBusinessMessageRequest struct {
// Unique identifier of the business connection on behalf of which to read the message
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours.
ChatID int64 `json:"chat_id"`
// Unique identifier of the message to mark as read
MessageID int64 `json:"message_id"`
}
ReadBusinessMessageRequest holds the parameters for readBusinessMessage.
type RefundStarPaymentRequest ¶
type RefundStarPaymentRequest struct {
// Identifier of the user whose payment will be refunded
UserID int64 `json:"user_id"`
// Telegram payment identifier
TelegramPaymentChargeID string `json:"telegram_payment_charge_id"`
}
RefundStarPaymentRequest holds the parameters for refundStarPayment.
type RefundedPayment ¶
type RefundedPayment struct {
// Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars. Currently, always “XTR”.
Currency string `json:"currency"`
// Total refunded price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45, total_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
TotalAmount int64 `json:"total_amount"`
// Bot-specified invoice payload
InvoicePayload string `json:"invoice_payload"`
// Telegram payment identifier
TelegramPaymentChargeID string `json:"telegram_payment_charge_id"`
// Optional. Provider payment identifier
ProviderPaymentChargeID string `json:"provider_payment_charge_id,omitempty"`
}
This object contains basic information about a refunded payment.
type RemoveBusinessAccountProfilePhotoRequest ¶
type RemoveBusinessAccountProfilePhotoRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Pass True to remove the public photo, which is visible even if the main photo is hidden by the business account's privacy settings. After the main photo is removed, the previous profile photo (if present) becomes the main photo.
IsPublic bool `json:"is_public,omitempty"`
}
RemoveBusinessAccountProfilePhotoRequest holds the parameters for removeBusinessAccountProfilePhoto.
type RemoveChatVerificationRequest ¶
type RemoveChatVerificationRequest struct {
// Unique identifier for the target chat or username of the target bot or channel in the format @username
ChatID ChatID `json:"chat_id"`
}
RemoveChatVerificationRequest holds the parameters for removeChatVerification.
type RemoveUserVerificationRequest ¶
type RemoveUserVerificationRequest struct {
// Unique identifier of the target user
UserID int64 `json:"user_id"`
}
RemoveUserVerificationRequest holds the parameters for removeUserVerification.
type ReopenForumTopicRequest ¶
type ReopenForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the target message thread of the forum topic
MessageThreadID int64 `json:"message_thread_id"`
}
ReopenForumTopicRequest holds the parameters for reopenForumTopic.
type ReopenGeneralForumTopicRequest ¶
type ReopenGeneralForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
}
ReopenGeneralForumTopicRequest holds the parameters for reopenGeneralForumTopic.
type ReplaceManagedBotTokenRequest ¶
type ReplaceManagedBotTokenRequest struct {
// User identifier of the managed bot whose token will be replaced
UserID int64 `json:"user_id"`
}
ReplaceManagedBotTokenRequest holds the parameters for replaceManagedBotToken.
type ReplaceStickerInSetRequest ¶
type ReplaceStickerInSetRequest struct {
// User identifier of the sticker set owner
UserID int64 `json:"user_id"`
// Sticker set name
Name string `json:"name"`
// File identifier of the replaced sticker
OldSticker string `json:"old_sticker"`
// A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged.
Sticker *InputSticker `json:"sticker"`
}
ReplaceStickerInSetRequest holds the parameters for replaceStickerInSet.
type ReplyKeyboard ¶
type ReplyKeyboard struct {
// contains filtered or unexported fields
}
ReplyKeyboard is a stepwise builder for a ReplyKeyboardMarkup (a keyboard that replaces the user's system keyboard, as opposed to an InlineKeyboard attached to a message): add buttons via Row, Add, and/or Insert in any combination, then call Build.
func NewReplyKeyboard ¶
func NewReplyKeyboard(resizeKeyboard bool) *ReplyKeyboard
NewReplyKeyboard creates an empty reply keyboard builder. resizeKeyboard requests that clients resize the keyboard vertically for an optimal fit instead of using the default large size.
func (*ReplyKeyboard) Add ¶
func (kb *ReplyKeyboard) Add(buttons ...KeyboardButton) *ReplyKeyboard
Add appends buttons to the keyboard, each on its own row — for a simple single-column list of buttons. See Row to group buttons onto one row instead.
func (*ReplyKeyboard) Adjust ¶
func (kb *ReplyKeyboard) Adjust(sizes ...int) *ReplyKeyboard
Adjust re-flows every button added so far into rows of the given sizes, exactly like InlineKeyboard.Adjust: sizes apply in order, the last one repeats, and it replaces whatever row structure Row/Add/Insert created.
func (*ReplyKeyboard) Build ¶
func (kb *ReplyKeyboard) Build() *ReplyKeyboardMarkup
Build finishes any row still under construction (see Insert) and returns the resulting ReplyKeyboardMarkup.
func (*ReplyKeyboard) Insert ¶
func (kb *ReplyKeyboard) Insert(button KeyboardButton) *ReplyKeyboard
Insert appends button to the row currently under construction; the next call to Row (with no arguments) or to Build finishes it.
func (*ReplyKeyboard) OneTime ¶
func (kb *ReplyKeyboard) OneTime(oneTime bool) *ReplyKeyboard
OneTime sets whether the keyboard hides itself after its next use, instead of staying open until the client replaces or removes it.
func (*ReplyKeyboard) Placeholder ¶
func (kb *ReplyKeyboard) Placeholder(text string) *ReplyKeyboard
Placeholder sets the placeholder text shown in the empty input field while this keyboard is open.
func (*ReplyKeyboard) Row ¶
func (kb *ReplyKeyboard) Row(buttons ...KeyboardButton) *ReplyKeyboard
Row appends buttons together as one new row, first finishing off any row already under construction via Insert.
func (*ReplyKeyboard) Selective ¶
func (kb *ReplyKeyboard) Selective(selective bool) *ReplyKeyboard
Selective sets whether the keyboard is shown only to specific users — the message it's attached to must target them via reply or mention for this to take effect (see ReplyKeyboardMarkup.Selective).
type ReplyKeyboardMarkup ¶
type ReplyKeyboardMarkup struct {
// Array of button rows, each represented by an Array of KeyboardButton objects
Keyboard [][]KeyboardButton `json:"keyboard"`
// Optional. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon.
IsPersistent bool `json:"is_persistent,omitempty"`
// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
ResizeKeyboard bool `json:"resize_keyboard,omitempty"`
// Optional. Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to false.
OneTimeKeyboard bool `json:"one_time_keyboard,omitempty"`
// Optional. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters
InputFieldPlaceholder string `json:"input_field_placeholder,omitempty"`
// Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message. Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard.
Selective bool `json:"selective,omitempty"`
}
This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). Not supported in channels and for messages sent on behalf of a business account.
func NewReplyKeyboardMarkup ¶
func NewReplyKeyboardMarkup(keyboard [][]KeyboardButton, resizeKeyboard bool, oneTimeKeyboard bool, placeholder string) *ReplyKeyboardMarkup
NewReplyKeyboardMarkup builds a ReplyKeyboardMarkup directly from a 2D button array, for callers who already have their buttons laid out and don't need the Row/Add/Insert builder:
markup := gg.NewReplyKeyboardMarkup([][]gg.KeyboardButton{{btn1, btn2}, {btn3}}, true, false, "Placeholder")
func QuickReplyKeyboard ¶
func QuickReplyKeyboard(buttons [][]string, resize bool) *ReplyKeyboardMarkup
QuickReplyKeyboard builds a full reply keyboard from rows of button text, one row per inner slice — a shortcut for the common case that needs no other options:
kb := gg.QuickReplyKeyboard([][]string{{"Button 1", "Button 2"}, {"Button 3"}}, true)
func QuickReplyRow ¶
func QuickReplyRow(buttons ...string) *ReplyKeyboardMarkup
QuickReplyRow builds a single-row, auto-resizing reply keyboard from button text.
type ReplyKeyboardRemove ¶
type ReplyKeyboardRemove struct {
// Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup)
RemoveKeyboard bool `json:"remove_keyboard"`
// Optional. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message. Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet.
Selective bool `json:"selective,omitempty"`
}
Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Not supported in channels and for messages sent on behalf of a business account.
func RemoveKeyboard ¶
func RemoveKeyboard(selective bool) *ReplyKeyboardRemove
RemoveKeyboard builds a ReplyKeyboardRemove, instructing the client to hide the current reply keyboard the next time it shows this message — selective restricts that to specific users the same way ReplyKeyboard.Selective does.
type ReplyMarkup ¶
type ReplyMarkup interface {
// contains filtered or unexported methods
}
ReplyMarkup is a sealed interface for all reply markup types, implemented by InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, and ForceReply.
type ReplyParameters ¶
type ReplyParameters struct {
// Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified
MessageID int64 `json:"message_id"`
// Optional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the bot, supergroup or channel in the format @username. Not supported for messages sent on behalf of a business account and messages from channel direct messages chats.
ChatID ChatID `json:"chat_id,omitzero"`
// Optional. Pass True if the message should be sent even if the specified message to be replied to is not found. Always False for replies in another chat or forum topic. Always True for messages sent on behalf of a business account.
AllowSendingWithoutReply bool `json:"allow_sending_without_reply,omitempty"`
// Optional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities. The message will fail to send if the quote isn't found in the original message.
Quote string `json:"quote,omitempty"`
// Optional. Mode for parsing entities in the quote. See formatting options for more details.
QuoteParseMode string `json:"quote_parse_mode,omitempty"`
// Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode.
QuoteEntities []MessageEntity `json:"quote_entities,omitempty"`
// Optional. Position of the quote in the original message in UTF-16 code units
QuotePosition int64 `json:"quote_position,omitempty"`
// Optional. Identifier of the specific checklist task to be replied to
ChecklistTaskID int64 `json:"checklist_task_id,omitempty"`
// Optional. Persistent identifier of the specific poll option to be replied to
PollOptionID string `json:"poll_option_id,omitempty"`
}
Describes reply parameters for the message that is being sent.
type RepostStoryRequest ¶
type RepostStoryRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the chat which posted the story that should be reposted
FromChatID int64 `json:"from_chat_id"`
// Unique identifier of the story that should be reposted
FromStoryID int64 `json:"from_story_id"`
// Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
ActivePeriod int64 `json:"active_period"`
// Pass True to keep the story accessible after it expires
PostToChatPage bool `json:"post_to_chat_page,omitempty"`
// Pass True if the content of the story must be protected from forwarding and screenshotting
ProtectContent bool `json:"protect_content,omitempty"`
}
RepostStoryRequest holds the parameters for repostStory.
type ResponseParameters ¶
type ResponseParameters struct {
// Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
MigrateToChatID int64 `json:"migrate_to_chat_id,omitempty"`
// Optional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated
RetryAfter int64 `json:"retry_after,omitempty"`
}
Describes why a request was unsuccessful.
type RestrictChatMemberRequest ¶
type RestrictChatMemberRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// A JSON-serialized object for new user permissions
Permissions *ChatPermissions `json:"permissions"`
// Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission.
UseIndependentChatPermissions bool `json:"use_independent_chat_permissions,omitempty"`
// Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever.
UntilDate int64 `json:"until_date,omitempty"`
}
RestrictChatMemberRequest holds the parameters for restrictChatMember.
type RevenueWithdrawalState ¶
type RevenueWithdrawalState interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the state of a revenue withdrawal operation. Currently, it can be one of
type RevenueWithdrawalStateFailed ¶
type RevenueWithdrawalStateFailed struct {
// Type of the state, always “failed”
Type string `json:"type"`
}
The withdrawal failed and the transaction was refunded.
func (*RevenueWithdrawalStateFailed) GetType ¶
func (v *RevenueWithdrawalStateFailed) GetType() string
type RevenueWithdrawalStatePending ¶
type RevenueWithdrawalStatePending struct {
// Type of the state, always “pending”
Type string `json:"type"`
}
The withdrawal is in progress.
func (*RevenueWithdrawalStatePending) GetType ¶
func (v *RevenueWithdrawalStatePending) GetType() string
The Get* methods below implement RevenueWithdrawalState: fields shared by every member, callable on the interface value directly without a type switch.
type RevenueWithdrawalStateSucceeded ¶
type RevenueWithdrawalStateSucceeded struct {
// Type of the state, always “succeeded”
Type string `json:"type"`
// Date the withdrawal was completed in Unix time
Date int64 `json:"date"`
// An HTTPS URL that can be used to see transaction details
URL string `json:"url"`
}
The withdrawal succeeded.
func (*RevenueWithdrawalStateSucceeded) GetType ¶
func (v *RevenueWithdrawalStateSucceeded) GetType() string
type RevokeChatInviteLinkRequest ¶
type RevokeChatInviteLinkRequest struct {
// Unique identifier of the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// The invite link to revoke
InviteLink string `json:"invite_link"`
}
RevokeChatInviteLinkRequest holds the parameters for revokeChatInviteLink.
type RichBlock ¶
type RichBlock interface {
GetType() string
// contains filtered or unexported methods
}
This object represents a block in a rich formatted message. Currently, it can be any of the following types:
func RichAnchorBlock ¶
RichAnchorBlock marks a standalone jump target named name — the block-level counterpart to RichAnchorPoint, for when the anchor isn't attached to any particular span of text.
func RichBlockquote ¶
RichBlockquote is a block quotation (<blockquote>) wrapping blocks, with credit (<cite>) if non-nil — pass nil for none.
func RichDetails ¶
RichDetails is a collapsible section (<details>), always showing summary with blocks revealed on expand (open, or always if open is true).
func RichFooter ¶
RichFooter is a footer block (<footer>).
func RichHeading ¶
RichHeading is a section heading (<h1>-<h6>); size is clamped to 1-6 (1 largest, 6 smallest, per Telegram's own field doc).
func RichList ¶
func RichList(items ...RichBlockListItem) RichBlock
RichList is a list block (<ul>/<ol>) built from items — see RichItem, RichOrderedItem, and RichCheckItem. Whether it renders as ordered, unordered, or a checklist is inferred from the items themselves (see [renderRichList]), not passed here, since that's exactly the information Telegram's own RichBlockListItem fields already carry.
func RichMap ¶
RichMap renders a static map (<tg-map>) centered on lat/long; zoom is clamped to 13-20 per Telegram's documented range.
func RichMathBlock ¶
RichMathBlock renders a LaTeX expression as its own block (<tg-math-block>), as opposed to RichInlineMath within a paragraph.
func RichParagraph ¶
RichParagraph is a plain text block (<p>).
func RichPreformatted ¶
RichPreformatted is a code block (<pre>), tagged with language if non-empty (<pre><code class="language-...">).
func RichPullquote ¶
RichPullquote is a pull quotation (<aside>) — a short quotation pulled out for emphasis, as opposed to RichBlockquote's attribution of quoted source material. credit (<cite>) may be nil.
func RichTable ¶
func RichTable(bordered, striped bool, caption RichText, rows ...[]RichBlockTableCell) RichBlock
RichTable is a table (<table>), one []RichBlockTableCell per row (see RichCell/RichHeaderCell); caption may be nil.
func RichThinking ¶
RichThinking is an AI-style "thinking…" placeholder block (<tg-thinking>) — legal only inside TelegramBot.SendRichMessageDraft; never send it via TelegramBot.SendRichMessage, and it never comes back on a stored message (see RichBlockThinking's own doc).
type RichBlockAnchor ¶
type RichBlockAnchor struct {
// Type of the block, always “anchor”
Type string `json:"type"`
// The name of the anchor
Name string `json:"name"`
}
A block with an anchor, corresponding to the HTML tag <a> with the attribute name.
func (*RichBlockAnchor) GetType ¶
func (v *RichBlockAnchor) GetType() string
type RichBlockAnimation ¶
type RichBlockAnimation struct {
// Type of the block, always “animation”
Type string `json:"type"`
// The animation
Animation *Animation `json:"animation"`
// Optional. True, if the media preview is covered by a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A block with an animation, corresponding to the HTML tag <video>.
func (*RichBlockAnimation) GetType ¶
func (v *RichBlockAnimation) GetType() string
type RichBlockAudio ¶
type RichBlockAudio struct {
// Type of the block, always “audio”
Type string `json:"type"`
// The audio
Audio *Audio `json:"audio"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A block with a music file, corresponding to the HTML tag <audio>.
func (*RichBlockAudio) GetType ¶
func (v *RichBlockAudio) GetType() string
type RichBlockAuthoredMedia ¶
type RichBlockAuthoredMedia struct {
URL string
Spoiler bool
Caption *RichBlockCaption
// contains filtered or unexported fields
}
RichBlockAuthoredMedia is a URL-sourced media leaf — <img>/<video>/ <audio>, chosen by which constructor built it (RichPhoto, RichVideo, RichAudio). Unlike the generated RichBlockPhoto/Video/Audio (decode- only, carrying Telegram's post-upload file references), this is how RenderRichMessage originates new media: point it at a URL and Telegram fetches it. Set Spoiler/Caption on the returned value directly, same as RichCell's Align/Valign — Caption renders as <figure>/<figcaption>, with Caption.Credit as <cite>, same shape as RichBlockPhoto's own caption.
func RichAudio ¶
func RichAudio(url string) *RichBlockAuthoredMedia
RichAudio is RichPhoto's <audio src="..."> counterpart.
func RichPhoto ¶
func RichPhoto(url string) *RichBlockAuthoredMedia
RichPhoto originates a new photo by URL (<img src="...">). See RichBlockAuthoredMedia for Spoiler/Caption and how to group several into a collage or slideshow.
func RichVideo ¶
func RichVideo(url string) *RichBlockAuthoredMedia
RichVideo is RichPhoto's <video src="..."> counterpart.
func (*RichBlockAuthoredMedia) GetType ¶
func (v *RichBlockAuthoredMedia) GetType() string
type RichBlockBlockQuotation ¶
type RichBlockBlockQuotation struct {
// Type of the block, always “blockquote”
Type string `json:"type"`
// Content of the block
Blocks []RichBlock `json:"blocks"`
// Optional. Credit of the block
Credit RichText `json:"credit,omitempty"`
}
A block quotation, corresponding to the HTML tag <blockquote>.
func (*RichBlockBlockQuotation) GetType ¶
func (v *RichBlockBlockQuotation) GetType() string
func (*RichBlockBlockQuotation) UnmarshalJSON ¶
func (v *RichBlockBlockQuotation) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockBlockQuotation's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockCaption ¶
type RichBlockCaption struct {
// Block caption
Text RichText `json:"text"`
// Optional. Block credit which corresponds to the HTML tag <cite>
Credit RichText `json:"credit,omitempty"`
}
Caption of a rich formatted block.
func (*RichBlockCaption) UnmarshalJSON ¶
func (v *RichBlockCaption) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockCaption's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockCollage ¶
type RichBlockCollage struct {
// Type of the block, always “collage”
Type string `json:"type"`
// Elements of the collage
Blocks []RichBlock `json:"blocks"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A collage, corresponding to the custom HTML tag <tg-collage>.
func RichCollage ¶
func RichCollage(items ...RichBlock) *RichBlockCollage
RichCollage groups media into a collage (<tg-collage>) — build the items with RichPhoto/RichVideo/RichAudio. Set Caption on the returned value directly for an overall caption, same as each item's own.
func (*RichBlockCollage) GetType ¶
func (v *RichBlockCollage) GetType() string
func (*RichBlockCollage) UnmarshalJSON ¶
func (v *RichBlockCollage) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockCollage's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockDetails ¶
type RichBlockDetails struct {
// Type of the block, always “details”
Type string `json:"type"`
// Always shown summary of the block
Summary RichText `json:"summary"`
// Content of the block
Blocks []RichBlock `json:"blocks"`
// Optional. True, if the content of the block is visible by default
IsOpen bool `json:"is_open,omitempty"`
}
An expandable block for details disclosure, corresponding to the HTML tag <details>.
func (*RichBlockDetails) GetType ¶
func (v *RichBlockDetails) GetType() string
func (*RichBlockDetails) UnmarshalJSON ¶
func (v *RichBlockDetails) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockDetails's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockDivider ¶
type RichBlockDivider struct {
// Type of the block, always “divider”
Type string `json:"type"`
}
A divider, corresponding to the HTML tag <hr/>.
func (*RichBlockDivider) GetType ¶
func (v *RichBlockDivider) GetType() string
type RichBlockFooter ¶
A footer, corresponding to the HTML tag <footer>.
func (*RichBlockFooter) GetType ¶
func (v *RichBlockFooter) GetType() string
func (*RichBlockFooter) UnmarshalJSON ¶
func (v *RichBlockFooter) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockFooter's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockList ¶
type RichBlockList struct {
// Type of the block, always “list”
Type string `json:"type"`
// Items of the list
Items []RichBlockListItem `json:"items"`
}
A list of blocks, corresponding to the HTML tag <ul> or <ol> with multiple nested tags <li>.
func (*RichBlockList) GetType ¶
func (v *RichBlockList) GetType() string
type RichBlockListItem ¶
type RichBlockListItem struct {
// Label of the item
Label string `json:"label"`
// The content of the item
Blocks []RichBlock `json:"blocks"`
// Optional. True, if the item has a checkbox
HasCheckbox bool `json:"has_checkbox,omitempty"`
// Optional. True, if the item has a checked checkbox
IsChecked bool `json:"is_checked,omitempty"`
// Optional. For ordered lists, the numeric value of the item label
Value int64 `json:"value,omitempty"`
// Optional. For ordered lists, the type of the item label; must be one of “a” for lowercase letters, “A” for uppercase letters, “i” for lowercase Roman numerals, “I” for uppercase Roman numerals, or “1” for decimal numbers
Type string `json:"type,omitempty"`
}
An item of a list.
func RichCheckItem ¶
func RichCheckItem(checked bool, blocks ...RichBlock) RichBlockListItem
RichCheckItem is a checklist item (<input type="checkbox">).
func RichItem ¶
func RichItem(blocks ...RichBlock) RichBlockListItem
RichItem is a plain (unordered, unchecked) list item wrapping blocks — almost always a single RichParagraph.
func RichOrderedItem ¶
func RichOrderedItem(blocks ...RichBlock) RichBlockListItem
RichOrderedItem is a list item that participates in decimal numbering — set the returned value's Type/Value fields directly (see RichBlockListItem's doc) for a different numbering style or an explicit start value.
func (*RichBlockListItem) UnmarshalJSON ¶
func (v *RichBlockListItem) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockListItem's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockMap ¶
type RichBlockMap struct {
// Type of the block, always “map”
Type string `json:"type"`
// Location of the center of the map
Location *Location `json:"location"`
// Map zoom level; 13-20
Zoom int64 `json:"zoom"`
// Expected width of the map
Width int64 `json:"width"`
// Expected height of the map
Height int64 `json:"height"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A block with a map, corresponding to the custom HTML tag <tg-map>.
func (*RichBlockMap) GetType ¶
func (v *RichBlockMap) GetType() string
type RichBlockMathematicalExpression ¶
type RichBlockMathematicalExpression struct {
// Type of the block, always “mathematical_expression”
Type string `json:"type"`
// The mathematical expression in LaTeX format
Expression string `json:"expression"`
}
A block with a mathematical expression in LaTeX format, corresponding to the custom HTML tag <tg-math-block>.
func (*RichBlockMathematicalExpression) GetType ¶
func (v *RichBlockMathematicalExpression) GetType() string
type RichBlockParagraph ¶
type RichBlockParagraph struct {
// Type of the block, always “paragraph”
Type string `json:"type"`
// Text of the block
Text RichText `json:"text"`
}
A text paragraph, corresponding to the HTML tag <p>.
func (*RichBlockParagraph) GetType ¶
func (v *RichBlockParagraph) GetType() string
The Get* methods below implement RichBlock: fields shared by every member, callable on the interface value directly without a type switch.
func (*RichBlockParagraph) UnmarshalJSON ¶
func (v *RichBlockParagraph) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockParagraph's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockPhoto ¶
type RichBlockPhoto struct {
// Type of the block, always “photo”
Type string `json:"type"`
// Available sizes of the photo
Photo []PhotoSize `json:"photo"`
// Optional. True, if the media preview is covered by a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A block with a photo, corresponding to the HTML tag <img>.
func (*RichBlockPhoto) GetType ¶
func (v *RichBlockPhoto) GetType() string
type RichBlockPreformatted ¶
type RichBlockPreformatted struct {
// Type of the block, always “pre”
Type string `json:"type"`
// Text of the block
Text RichText `json:"text"`
// Optional. The programming language of the text
Language string `json:"language,omitempty"`
}
A preformatted text block, corresponding to the nested HTML tags <pre> and <code>.
func (*RichBlockPreformatted) GetType ¶
func (v *RichBlockPreformatted) GetType() string
func (*RichBlockPreformatted) UnmarshalJSON ¶
func (v *RichBlockPreformatted) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockPreformatted's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockPullQuotation ¶
type RichBlockPullQuotation struct {
// Type of the block, always “pullquote”
Type string `json:"type"`
// Text of the block
Text RichText `json:"text"`
// Optional. Credit of the block
Credit RichText `json:"credit,omitempty"`
}
A quotation with centered text, loosely corresponding to the HTML tag <aside>.
func (*RichBlockPullQuotation) GetType ¶
func (v *RichBlockPullQuotation) GetType() string
func (*RichBlockPullQuotation) UnmarshalJSON ¶
func (v *RichBlockPullQuotation) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockPullQuotation's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockSectionHeading ¶
type RichBlockSectionHeading struct {
// Type of the block, always “heading”
Type string `json:"type"`
// Text of the block
Text RichText `json:"text"`
// Relative size of the text font; 1-6, 1 is the largest, 6 is the smallest
Size int64 `json:"size"`
}
A section heading, corresponding to the HTML tags <h1>, <h2>, <h3>, <h4>, <h5>, or <h6>.
func (*RichBlockSectionHeading) GetType ¶
func (v *RichBlockSectionHeading) GetType() string
func (*RichBlockSectionHeading) UnmarshalJSON ¶
func (v *RichBlockSectionHeading) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockSectionHeading's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockSlideshow ¶
type RichBlockSlideshow struct {
// Type of the block, always “slideshow”
Type string `json:"type"`
// Elements of the slideshow
Blocks []RichBlock `json:"blocks"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A slideshow, corresponding to the custom HTML tag <tg-slideshow>.
func RichSlideshow ¶
func RichSlideshow(items ...RichBlock) *RichBlockSlideshow
RichSlideshow is RichCollage's <tg-slideshow> counterpart — media shown one at a time instead of tiled.
func (*RichBlockSlideshow) GetType ¶
func (v *RichBlockSlideshow) GetType() string
func (*RichBlockSlideshow) UnmarshalJSON ¶
func (v *RichBlockSlideshow) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockSlideshow's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockTable ¶
type RichBlockTable struct {
// Type of the block, always “table”
Type string `json:"type"`
// Cells of the table
Cells [][]RichBlockTableCell `json:"cells"`
// Optional. True, if the table has borders
IsBordered bool `json:"is_bordered,omitempty"`
// Optional. True, if the table is striped
IsStriped bool `json:"is_striped,omitempty"`
// Optional. Caption of the table
Caption RichText `json:"caption,omitempty"`
}
A table, corresponding to the HTML tag <table>.
func (*RichBlockTable) GetType ¶
func (v *RichBlockTable) GetType() string
func (*RichBlockTable) UnmarshalJSON ¶
func (v *RichBlockTable) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockTable's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockTableCell ¶
type RichBlockTableCell struct {
// Optional. Text in the cell. If omitted, then the cell is invisible.
Text RichText `json:"text,omitempty"`
// Optional. True, if the cell is a header cell
IsHeader bool `json:"is_header,omitempty"`
// Optional. The number of columns the cell spans if it is bigger than 1
Colspan int64 `json:"colspan,omitempty"`
// Optional. The number of rows the cell spans if it is bigger than 1
Rowspan int64 `json:"rowspan,omitempty"`
// Horizontal cell content alignment. Currently, must be one of “left”, “center”, or “right”.
Align string `json:"align"`
// Vertical cell content alignment. Currently, must be one of “top”, “middle”, or “bottom”.
Valign string `json:"valign"`
}
Cell in a table.
func RichCell ¶
func RichCell(spans ...RichText) RichBlockTableCell
RichCell is a table data cell (<td>), left/top-aligned by default — set the returned value's Align/Valign fields directly to override, since Telegram's own RichBlockTableCell fields have no "default" value (they're required, not omitempty) and an empty string isn't one of the three the docs allow.
func RichHeaderCell ¶
func RichHeaderCell(spans ...RichText) RichBlockTableCell
RichHeaderCell is RichCell marked as a header cell (<th>).
func (*RichBlockTableCell) UnmarshalJSON ¶
func (v *RichBlockTableCell) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockTableCell's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockThinking ¶
type RichBlockThinking struct {
// Type of the block, always “thinking”
Type string `json:"type"`
// Text of the block. See https://t.me/addemoji/AIActions for examples of custom emoji, which are recommended for usage in the block.
Text RichText `json:"text"`
}
A block with a “Thinking…” placeholder, corresponding to the custom HTML tag <tg-thinking>. The block may be used only in sendRichMessageDraft, therefore it can't be received in messages. See https://t.me/addemoji/AIActions for examples of custom emoji, which are recommended for usage in the block.
func (*RichBlockThinking) GetType ¶
func (v *RichBlockThinking) GetType() string
func (*RichBlockThinking) UnmarshalJSON ¶
func (v *RichBlockThinking) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichBlockThinking's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichBlockVideo ¶
type RichBlockVideo struct {
// Type of the block, always “video”
Type string `json:"type"`
// The video
Video *Video `json:"video"`
// Optional. True, if the media preview is covered by a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A block with a video, corresponding to the HTML tag <video>.
func (*RichBlockVideo) GetType ¶
func (v *RichBlockVideo) GetType() string
type RichBlockVoiceNote ¶
type RichBlockVoiceNote struct {
// Type of the block, always “voice_note”
Type string `json:"type"`
// The voice note
VoiceNote *Voice `json:"voice_note"`
// Optional. Caption of the block
Caption *RichBlockCaption `json:"caption,omitempty"`
}
A block with a voice note, corresponding to the HTML tag <audio>.
func (*RichBlockVoiceNote) GetType ¶
func (v *RichBlockVoiceNote) GetType() string
type RichMessage ¶
type RichMessage struct {
// Content of the message
Blocks []RichBlock `json:"blocks"`
// Optional. True, if the rich message must be shown right-to-left
IsRtl bool `json:"is_rtl,omitempty"`
}
Rich formatted message.
func (*RichMessage) PlainText ¶
func (m *RichMessage) PlainText() string
PlainText flattens m back to plain, readable text — the read-side counterpart to RenderRichMessage. There's no plain-text way to represent bold/italic/etc., so style is dropped entirely; paragraph breaks, list items, and blockquote/table structure are kept since those stay meaningful without it. Useful for logging, search indexing, or forwarding a rich message's content somewhere only plain text works.
func (*RichMessage) UnmarshalJSON ¶
func (v *RichMessage) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichMessage's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichPlainText ¶
type RichPlainText string
RichPlainText is RichText's "String for plain text" alternative: Telegram represents an unstyled run of text as a bare JSON string rather than an object with a "type" discriminator, unlike every other RichText member — see [unmarshalRichText] in types.gen.go, which tries this decode first. Not a spec-named type, so — unlike RichTextBold and its siblings — it isn't generated; it's hand-written here because RichText's marker methods are unexported and can only be implemented from within this package.
func (RichPlainText) GetType ¶
func (RichPlainText) GetType() string
GetType returns "" — RichPlainText has no discriminator value; Telegram sends it as a bare JSON string, never as an object with a "type" field.
type RichText ¶
type RichText interface {
GetType() string
// contains filtered or unexported methods
}
This object represents a rich formatted text. Currently, it can be either a String for plain text, an Array of RichText, or any of the following types:
func RichAnchorLink ¶
RichAnchorLink links spans to the in-message anchor named name (<a href="#name">) — jumps to RichAnchorBlock/RichAnchorPoint with a matching name, or to the top of the message if name is "".
func RichAnchorPoint ¶
RichAnchorPoint marks an inline jump target named name (<a name="...">), for RichAnchorLink to link to. See RichAnchorBlock for a block-level (standalone) anchor instead.
func RichInlineMath ¶
RichInlineMath renders a LaTeX expression inline (<tg-math>). latex is sent verbatim, not HTML-escaped — escaping would corrupt LaTeX's own backslashes and braces.
func RichItalic ¶
RichItalic wraps spans in italics (<i>).
func RichLink ¶
RichLink wraps spans in a link to url (<a href="...">); with no spans, the URL itself is the visible label.
func RichPlain ¶
RichPlain wraps s as a RichText leaf — Telegram's "String for plain text" alternative, decoded as RichPlainText.
func RichSpoiler ¶
RichSpoiler hides spans behind a spoiler (<tg-spoiler>).
func RichStrikethrough ¶
RichStrikethrough strikes through spans (<s>).
func RichUnderline ¶
RichUnderline underlines spans (<u>).
func RichUserMention ¶
RichUserMention links spans to user by ID (<a href="tg://user?id=...">) — works even without a username, unlike an @mention. With no spans, the user's first name is the visible label.
type RichTextAnchor ¶
type RichTextAnchor struct {
// Type of the rich text, always “anchor”
Type string `json:"type"`
// The name of the anchor
Name string `json:"name"`
}
An anchor.
func (*RichTextAnchor) GetType ¶
func (v *RichTextAnchor) GetType() string
type RichTextAnchorLink ¶
type RichTextAnchorLink struct {
// Type of the rich text, always “anchor_link”
Type string `json:"type"`
// The link text
Text RichText `json:"text"`
// The name of the anchor. If the name is empty, then the link brings back to the top of the message.
AnchorName string `json:"anchor_name"`
}
A link to an anchor.
func (*RichTextAnchorLink) GetType ¶
func (v *RichTextAnchorLink) GetType() string
func (*RichTextAnchorLink) UnmarshalJSON ¶
func (v *RichTextAnchorLink) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextAnchorLink's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextBankCardNumber ¶
type RichTextBankCardNumber struct {
// Type of the rich text, always “bank_card_number”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The bank card number
BankCardNumber string `json:"bank_card_number"`
}
A text with a bank card number.
func (*RichTextBankCardNumber) GetType ¶
func (v *RichTextBankCardNumber) GetType() string
func (*RichTextBankCardNumber) UnmarshalJSON ¶
func (v *RichTextBankCardNumber) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextBankCardNumber's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextBold ¶
type RichTextBold struct {
// Type of the rich text, always “bold”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A bold text.
func (*RichTextBold) GetType ¶
func (v *RichTextBold) GetType() string
The Get* methods below implement RichText: fields shared by every member, callable on the interface value directly without a type switch.
func (*RichTextBold) UnmarshalJSON ¶
func (v *RichTextBold) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextBold's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextBotCommand ¶
type RichTextBotCommand struct {
// Type of the rich text, always “bot_command”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The bot command
BotCommand string `json:"bot_command"`
}
A bot command.
func (*RichTextBotCommand) GetType ¶
func (v *RichTextBotCommand) GetType() string
func (*RichTextBotCommand) UnmarshalJSON ¶
func (v *RichTextBotCommand) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextBotCommand's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextCashtag ¶
type RichTextCashtag struct {
// Type of the rich text, always “cashtag”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The cashtag
Cashtag string `json:"cashtag"`
}
A cashtag.
func (*RichTextCashtag) GetType ¶
func (v *RichTextCashtag) GetType() string
func (*RichTextCashtag) UnmarshalJSON ¶
func (v *RichTextCashtag) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextCashtag's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextCode ¶
type RichTextCode struct {
// Type of the rich text, always “code”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A monowidth text.
func (*RichTextCode) GetType ¶
func (v *RichTextCode) GetType() string
func (*RichTextCode) UnmarshalJSON ¶
func (v *RichTextCode) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextCode's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextCustomEmoji ¶
type RichTextCustomEmoji struct {
// Type of the rich text, always “custom_emoji”
Type string `json:"type"`
// Unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker.
CustomEmojiID string `json:"custom_emoji_id"`
// Alternative emoji for the custom emoji
AlternativeText string `json:"alternative_text"`
}
A custom emoji.
func (*RichTextCustomEmoji) GetType ¶
func (v *RichTextCustomEmoji) GetType() string
type RichTextDateTime ¶
type RichTextDateTime struct {
// Type of the rich text, always “date_time”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The Unix time associated with the entity
UnixTime int64 `json:"unix_time"`
// The string that defines the formatting of the date and time. See date-time entity formatting for more details.
DateTimeFormat string `json:"date_time_format"`
}
Formatted date and time.
func (*RichTextDateTime) GetType ¶
func (v *RichTextDateTime) GetType() string
func (*RichTextDateTime) UnmarshalJSON ¶
func (v *RichTextDateTime) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextDateTime's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextEmailAddress ¶
type RichTextEmailAddress struct {
// Type of the rich text, always “email_address”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The email address
EmailAddress string `json:"email_address"`
}
A text with an email address.
func (*RichTextEmailAddress) GetType ¶
func (v *RichTextEmailAddress) GetType() string
func (*RichTextEmailAddress) UnmarshalJSON ¶
func (v *RichTextEmailAddress) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextEmailAddress's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextHashtag ¶
type RichTextHashtag struct {
// Type of the rich text, always “hashtag”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The hashtag
Hashtag string `json:"hashtag"`
}
A hashtag.
func (*RichTextHashtag) GetType ¶
func (v *RichTextHashtag) GetType() string
func (*RichTextHashtag) UnmarshalJSON ¶
func (v *RichTextHashtag) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextHashtag's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextItalic ¶
type RichTextItalic struct {
// Type of the rich text, always “italic”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
An italicized text.
func (*RichTextItalic) GetType ¶
func (v *RichTextItalic) GetType() string
func (*RichTextItalic) UnmarshalJSON ¶
func (v *RichTextItalic) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextItalic's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextMarked ¶
type RichTextMarked struct {
// Type of the rich text, always “marked”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A marked text.
func (*RichTextMarked) GetType ¶
func (v *RichTextMarked) GetType() string
func (*RichTextMarked) UnmarshalJSON ¶
func (v *RichTextMarked) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextMarked's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextMathematicalExpression ¶
type RichTextMathematicalExpression struct {
// Type of the rich text, always “mathematical_expression”
Type string `json:"type"`
// The expression in LaTeX format
Expression string `json:"expression"`
}
A mathematical expression.
func (*RichTextMathematicalExpression) GetType ¶
func (v *RichTextMathematicalExpression) GetType() string
type RichTextMention ¶
type RichTextMention struct {
// Type of the rich text, always “mention”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The username
Username string `json:"username"`
}
A mention by a username.
func (*RichTextMention) GetType ¶
func (v *RichTextMention) GetType() string
func (*RichTextMention) UnmarshalJSON ¶
func (v *RichTextMention) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextMention's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextPhoneNumber ¶
type RichTextPhoneNumber struct {
// Type of the rich text, always “phone_number”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The phone number
PhoneNumber string `json:"phone_number"`
}
A text with a phone number.
func (*RichTextPhoneNumber) GetType ¶
func (v *RichTextPhoneNumber) GetType() string
func (*RichTextPhoneNumber) UnmarshalJSON ¶
func (v *RichTextPhoneNumber) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextPhoneNumber's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextReference ¶
type RichTextReference struct {
// Type of the rich text, always “reference”
Type string `json:"type"`
// Text of the reference
Text RichText `json:"text"`
// The name of the reference
Name string `json:"name"`
}
A reference.
func (*RichTextReference) GetType ¶
func (v *RichTextReference) GetType() string
func (*RichTextReference) UnmarshalJSON ¶
func (v *RichTextReference) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextReference's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextReferenceLink ¶
type RichTextReferenceLink struct {
// Type of the rich text, always “reference_link”
Type string `json:"type"`
// The link text
Text RichText `json:"text"`
// The name of the reference
ReferenceName string `json:"reference_name"`
}
A link to a reference.
func (*RichTextReferenceLink) GetType ¶
func (v *RichTextReferenceLink) GetType() string
func (*RichTextReferenceLink) UnmarshalJSON ¶
func (v *RichTextReferenceLink) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextReferenceLink's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextSequence ¶
type RichTextSequence []RichText
RichTextSequence is RichText's "Array of RichText" alternative: several consecutive spans (plain text followed by a bold word, say) arrive concatenated in one JSON array instead of one object. Not a spec-named type, hand-written for the same reason as RichPlainText.
func (RichTextSequence) GetType ¶
func (RichTextSequence) GetType() string
GetType returns "" — RichTextSequence has no discriminator value either.
type RichTextSpoiler ¶
type RichTextSpoiler struct {
// Type of the rich text, always “spoiler”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A text covered by a spoiler.
func (*RichTextSpoiler) GetType ¶
func (v *RichTextSpoiler) GetType() string
func (*RichTextSpoiler) UnmarshalJSON ¶
func (v *RichTextSpoiler) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextSpoiler's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextStrikethrough ¶
type RichTextStrikethrough struct {
// Type of the rich text, always “strikethrough”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A strikethrough text.
func (*RichTextStrikethrough) GetType ¶
func (v *RichTextStrikethrough) GetType() string
func (*RichTextStrikethrough) UnmarshalJSON ¶
func (v *RichTextStrikethrough) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextStrikethrough's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextSubscript ¶
type RichTextSubscript struct {
// Type of the rich text, always “subscript”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A subscript text.
func (*RichTextSubscript) GetType ¶
func (v *RichTextSubscript) GetType() string
func (*RichTextSubscript) UnmarshalJSON ¶
func (v *RichTextSubscript) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextSubscript's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextSuperscript ¶
type RichTextSuperscript struct {
// Type of the rich text, always “superscript”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
A superscript text.
func (*RichTextSuperscript) GetType ¶
func (v *RichTextSuperscript) GetType() string
func (*RichTextSuperscript) UnmarshalJSON ¶
func (v *RichTextSuperscript) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextSuperscript's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextTextMention ¶
type RichTextTextMention struct {
// Type of the rich text, always “text_mention”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// The mentioned user
User *User `json:"user"`
}
A mention of a Telegram user by their identifier.
func (*RichTextTextMention) GetType ¶
func (v *RichTextTextMention) GetType() string
func (*RichTextTextMention) UnmarshalJSON ¶
func (v *RichTextTextMention) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextTextMention's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextURL ¶
type RichTextURL struct {
// Type of the rich text, always “url”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
// URL of the link
URL string `json:"url"`
}
A text with a link.
func (*RichTextURL) GetType ¶
func (v *RichTextURL) GetType() string
func (*RichTextURL) UnmarshalJSON ¶
func (v *RichTextURL) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextURL's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type RichTextUnderline ¶
type RichTextUnderline struct {
// Type of the rich text, always “underline”
Type string `json:"type"`
// The text
Text RichText `json:"text"`
}
An underlined text.
func (*RichTextUnderline) GetType ¶
func (v *RichTextUnderline) GetType() string
func (*RichTextUnderline) UnmarshalJSON ¶
func (v *RichTextUnderline) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes RichTextUnderline's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router collects handler registrations, one per update kind, tried in registration order (first match wins). Compose routers with Router.Include: a router included partway through registration is tried at that point in the overall order, with its own middleware applied only to its own handlers.
A kind's "default" handler is just a registration with no filters, placed last for that kind — since registration order is priority, it only runs when nothing more specific matched.
func (*Router) BusinessConnection ¶
BusinessConnection registers a handler for the business_connection update kind.
func (*Router) BusinessMessage ¶
BusinessMessage registers a handler for the business_message update kind.
func (*Router) CallbackQuery ¶
CallbackQuery registers a handler for the callback_query update kind.
func (*Router) ChannelPost ¶
ChannelPost registers a handler for the channel_post update kind.
func (*Router) ChatJoinRequest ¶
ChatJoinRequest registers a handler for the chat_join_request update kind.
func (*Router) ChatMember ¶
ChatMember registers a handler for the chat_member update kind (some other member's status changed — requires the bot to be an admin).
func (*Router) ChosenInlineResult ¶
ChosenInlineResult registers a handler for the chosen_inline_result update kind.
func (*Router) DeletedBusinessMessages ¶
DeletedBusinessMessages registers a handler for the deleted_business_messages update kind.
func (*Router) EditedBusinessMessage ¶
EditedBusinessMessage registers a handler for the edited_business_message update kind.
func (*Router) EditedChannelPost ¶
EditedChannelPost registers a handler for the edited_channel_post update kind.
func (*Router) EditedMessage ¶
EditedMessage registers a handler for the edited_message update kind.
func (*Router) GuestMessage ¶
GuestMessage registers a handler for the guest_message update kind.
func (*Router) Include ¶
Include appends a sub-router, tried at this point in the parent's registration order. Panics if including sub would create a cycle (sub is r itself, or already — directly or transitively — includes r): dispatch recurses through included routers, so an actual cycle would infinite-loop the first update that reaches it, a far worse failure mode than a panic at wiring time, before TelegramBot.Run / TelegramBot.RunWebhook ever starts.
Middleware does NOT flow from r into sub through Include — see Router.Use's doc. This differs from the "outer wraps inner" middleware semantics some router libraries default to; it's a deliberate choice here, not an oversight. If r.Use(mw) must apply to sub's handlers too, call sub.Use(mw) directly (or register mw on every router in the tree that needs it) rather than relying on Include to propagate it.
func (*Router) InlineQuery ¶
InlineQuery registers a handler for the inline_query update kind.
func (*Router) ManagedBot ¶
ManagedBot registers a handler for the managed_bot update kind.
func (*Router) Message ¶
Message registers a handler for the message update kind. Filters combine with AND; zero filters matches every message.
func (*Router) MessageReaction ¶
MessageReaction registers a handler for the message_reaction update kind.
func (*Router) MessageReactionCount ¶
MessageReactionCount registers a handler for the message_reaction_count update kind.
func (*Router) MyChatMember ¶
MyChatMember registers a handler for the my_chat_member update kind (the bot's own membership status changed in a chat).
func (*Router) OnError ¶
func (r *Router) OnError(h ErrorHandlerFunc)
OnError sets this router's error handler, intercepting any error a handler matched within its own subtree returns (including from included sub-routers) before it bubbles further out. If a sub-router that matched has its own OnError, that one runs instead — this router only sees the error if the sub-router that actually handled the update didn't already handle it. An error that reaches the root router with no OnError set anywhere in the chain falls through to TelegramBot.OnError, exactly as before per-router error handlers existed.
func (*Router) Poll ¶
Poll registers a handler for the poll update kind (a poll's public status changed — this is not poll_answer, which is one voter's answer).
func (*Router) PollAnswer ¶
PollAnswer registers a handler for the poll_answer update kind.
func (*Router) PreCheckoutQuery ¶
PreCheckoutQuery registers a handler for the pre_checkout_query update kind.
func (*Router) PurchasedPaidMedia ¶
PurchasedPaidMedia registers a handler for the purchased_paid_media update kind.
func (*Router) RemovedChatBoost ¶
RemovedChatBoost registers a handler for the removed_chat_boost update kind.
func (*Router) ShippingQuery ¶
ShippingQuery registers a handler for the shipping_query update kind.
func (*Router) Update ¶
Update registers a handler matching every update kind unconditionally (subject only to any filters passed) — a catch-all observer for cross-cutting concerns that want to see every update regardless of kind (logging, metrics, ...), not one of the per-kind handlers above. Since it's a catch-all, place it last in registration order unless you specifically want it to preempt more specific handlers for the same update. Its presence anywhere in the router tree disables Router.UsedUpdateKinds's allowed_updates restriction entirely (see its doc).
func (*Router) Use ¶
func (r *Router) Use(mw MiddlewareFunc)
Use registers middleware that wraps every handler matched by this router (not included sub-routers' own middleware, which is theirs alone).
func (*Router) UseOuter ¶
func (r *Router) UseOuter(mw OuterMiddlewareFunc)
UseOuter registers outer middleware — see OuterMiddlewareFunc — that wraps this router's entire dispatch attempt, including updates none of its own registrations end up matching. Scoped the same way Use is: an included sub-router's own UseOuter middleware is its own, not inherited from (or shared with) whichever router included it — register on every router in the tree that needs it, same guidance as Use's doc.
func (*Router) UsedUpdateKinds ¶
UsedUpdateKinds returns the Telegram update field names (e.g. "message", "chat_member") that have at least one registered handler anywhere in this router or its included sub-routers, deduplicated. Used to compute getUpdates'/setWebhook's allowed_updates automatically — see WithAllowedUpdates and TelegramBot.Run. Returns nil (no restriction) if any Router.Update catch-all is registered anywhere in the tree.
type SMO ¶
type SMO = SendMessageOptions
SMO is SendMessageOptions' short alias — see SendMessageOptions' doc.
type SavePreparedInlineMessageRequest ¶
type SavePreparedInlineMessageRequest struct {
// Unique identifier of the target user that can use the prepared message
UserID int64 `json:"user_id"`
// A JSON-serialized object describing the message to be sent
Result InlineQueryResult `json:"result"`
// Pass True if the message can be sent to private chats with users
AllowUserChats bool `json:"allow_user_chats,omitempty"`
// Pass True if the message can be sent to private chats with bots
AllowBotChats bool `json:"allow_bot_chats,omitempty"`
// Pass True if the message can be sent to group and supergroup chats
AllowGroupChats bool `json:"allow_group_chats,omitempty"`
// Pass True if the message can be sent to channel chats
AllowChannelChats bool `json:"allow_channel_chats,omitempty"`
}
SavePreparedInlineMessageRequest holds the parameters for savePreparedInlineMessage.
type SavePreparedKeyboardButtonRequest ¶
type SavePreparedKeyboardButtonRequest struct {
// Unique identifier of the target user that can use the button
UserID int64 `json:"user_id"`
// A JSON-serialized object describing the button to be saved. The button must be of the type request_users, request_chat, or request_managed_bot.
Button *KeyboardButton `json:"button"`
}
SavePreparedKeyboardButtonRequest holds the parameters for savePreparedKeyboardButton.
type SendAnimationRequest ¶
type SendAnimationRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files »
Animation InputFile `json:"animation"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Duration of sent animation in seconds
Duration int64 `json:"duration,omitempty"`
// Animation width
Width int64 `json:"width,omitempty"`
// Animation height
Height int64 `json:"height,omitempty"`
// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the animation caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Pass True if the animation needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendAnimationRequest holds the parameters for sendAnimation.
type SendAudioRequest ¶
type SendAudioRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
Audio InputFile `json:"audio"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Audio caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the audio caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Duration of the audio in seconds
Duration int64 `json:"duration,omitempty"`
// Performer
Performer string `json:"performer,omitempty"`
// Track name
Title string `json:"title,omitempty"`
// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendAudioRequest holds the parameters for sendAudio.
type SendChatActionRequest ¶
type SendChatActionRequest struct {
// Unique identifier for the target chat or username of the target bot or supergroup in the format @username. Channel chats and channel direct messages chats aren't supported.
ChatID ChatID `json:"chat_id"`
// Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
Action string `json:"action"`
// Unique identifier of the business connection on behalf of which the action will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread or topic of a forum; for supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
}
SendChatActionRequest holds the parameters for sendChatAction.
type SendChatJoinRequestWebAppRequest ¶
type SendChatJoinRequestWebAppRequest struct {
// Unique identifier of the join request query
ChatJoinRequestQueryID string `json:"chat_join_request_query_id"`
// The URL of the Mini App to be opened
WebAppURL string `json:"web_app_url"`
}
SendChatJoinRequestWebAppRequest holds the parameters for sendChatJoinRequestWebApp.
type SendChecklistRequest ¶
type SendChecklistRequest struct {
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier for the target chat or username of the target bot in the format @username
ChatID ChatID `json:"chat_id"`
// A JSON-serialized object for the checklist to send
Checklist *InputChecklist `json:"checklist"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Unique identifier of the message effect to be added to the message
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object for description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// A JSON-serialized object for an inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
SendChecklistRequest holds the parameters for sendChecklist.
type SendContactRequest ¶
type SendContactRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Contact's phone number
PhoneNumber string `json:"phone_number"`
// Contact's first name
FirstName string `json:"first_name"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Contact's last name
LastName string `json:"last_name,omitempty"`
// Additional data about the contact in the form of a vCard, 0-2048 bytes
Vcard string `json:"vcard,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendContactRequest holds the parameters for sendContact.
type SendDiceRequest ¶
type SendDiceRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”.
Emoji string `json:"emoji,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendDiceRequest holds the parameters for sendDice.
type SendDocumentRequest ¶
type SendDocumentRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
Document InputFile `json:"document"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the document caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Disables automatic server-side content type detection for files uploaded using multipart/form-data
DisableContentTypeDetection bool `json:"disable_content_type_detection,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendDocumentRequest holds the parameters for sendDocument.
type SendGameRequest ¶
type SendGameRequest struct {
// Unique identifier for the target chat or username of the target bot in the format @username. Games can't be sent to channel direct messages chats and channel chats.
ChatID ChatID `json:"chat_id"`
// Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather.
GameShortName string `json:"game_short_name"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game.
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
SendGameRequest holds the parameters for sendGame.
type SendGiftRequest ¶
type SendGiftRequest struct {
// Identifier of the gift; limited gifts can't be sent to channel chats
GiftID string `json:"gift_id"`
// Required if chat_id is not specified. Unique identifier of the target user who will receive the gift.
UserID int64 `json:"user_id,omitempty"`
// Required if user_id is not specified. Unique identifier for the chat or username of the channel (in the format @username) that will receive the gift.
ChatID ChatID `json:"chat_id,omitzero"`
// Pass True to pay for the gift upgrade from the bot's balance, thereby making the upgrade free for the receiver
PayForUpgrade bool `json:"pay_for_upgrade,omitempty"`
// Text that will be shown along with the gift; 0-128 characters
Text string `json:"text,omitempty"`
// Mode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
TextParseMode string `json:"text_parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
TextEntities []MessageEntity `json:"text_entities,omitempty"`
}
SendGiftRequest holds the parameters for sendGift.
type SendInvoiceRequest ¶
type SendInvoiceRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Product name, 1-32 characters
Title string `json:"title"`
// Product description, 1-255 characters
Description string `json:"description"`
// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes.
Payload string `json:"payload"`
// Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
Currency string `json:"currency"`
// Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
Prices []LabeledPrice `json:"prices"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
ProviderToken string `json:"provider_token,omitempty"`
// The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
MaxTipAmount int64 `json:"max_tip_amount,omitempty"`
// A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
SuggestedTipAmounts []int64 `json:"suggested_tip_amounts,omitempty"`
// Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter.
StartParameter string `json:"start_parameter,omitempty"`
// JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
ProviderData string `json:"provider_data,omitempty"`
// URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
PhotoURL string `json:"photo_url,omitempty"`
// Photo size in bytes
PhotoSize int64 `json:"photo_size,omitempty"`
// Photo width
PhotoWidth int64 `json:"photo_width,omitempty"`
// Photo height
PhotoHeight int64 `json:"photo_height,omitempty"`
// Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
NeedName bool `json:"need_name,omitempty"`
// Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
NeedPhoneNumber bool `json:"need_phone_number,omitempty"`
// Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
NeedEmail bool `json:"need_email,omitempty"`
// Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
NeedShippingAddress bool `json:"need_shipping_address,omitempty"`
// Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
SendPhoneNumberToProvider bool `json:"send_phone_number_to_provider,omitempty"`
// Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
SendEmailToProvider bool `json:"send_email_to_provider,omitempty"`
// Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
IsFlexible bool `json:"is_flexible,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
SendInvoiceRequest holds the parameters for sendInvoice.
func NewStarsInvoice ¶
func NewStarsInvoice(chatID ChatID, title, description, payload string, stars int64) *SendInvoiceRequest
NewStarsInvoice builds a sendInvoice request for a Telegram Stars payment: currency XTR, no provider token, exactly one price component (all three are what the Stars flow requires). Tweak the returned request (photo, reply markup, ...) before sending:
req := gg.NewStarsInvoice(gg.ChatIDFromInt(chatID), "Pro", "Unlock pro features", "pro-1m", 250) req.PhotoURL = "https://example.com/pro.png" msg, err := bot.SendInvoice(ctx, req)
type SendLivePhotoRequest ¶
type SendLivePhotoRequest struct {
// Unique identifier for the target chat or username of the target channel (in the format @channelusername)
ChatID ChatID `json:"chat_id"`
// Live photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size. Pass a file_id as String to send a video that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
LivePhoto InputFile `json:"live_photo"`
// The static photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
Photo InputFile `json:"photo"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the video caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Pass True if the video needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendLivePhotoRequest holds the parameters for sendLivePhoto.
type SendLocationRequest ¶
type SendLocationRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Latitude of the location
Latitude float64 `json:"latitude"`
// Longitude of the location
Longitude float64 `json:"longitude"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// The radius of uncertainty for the location, measured in meters; 0-1500
HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"`
// Period in seconds during which the location will be updated (see Live Locations, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely
LivePeriod int64 `json:"live_period,omitempty"`
// For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
Heading int64 `json:"heading,omitempty"`
// For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
ProximityAlertRadius int64 `json:"proximity_alert_radius,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendLocationRequest holds the parameters for sendLocation.
type SendMediaGroupRequest ¶
type SendMediaGroupRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// A JSON-serialized array describing messages to be sent, must include 2-10 items
Media []InputMedia `json:"media"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Sends messages silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent messages from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
}
SendMediaGroupRequest holds the parameters for sendMediaGroup.
type SendMessageDraftRequest ¶
type SendMessageDraftRequest struct {
// Unique identifier for the target private chat
ChatID int64 `json:"chat_id"`
// Unique identifier of the message draft; must be non-zero. Changes to drafts with the same identifier are animated.
DraftID int64 `json:"draft_id"`
// Unique identifier for the target message thread
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Text of the message to be sent, 0-4096 characters after entities parsing. Pass an empty text to show a “Thinking…” placeholder.
Text string `json:"text,omitempty"`
// Mode for parsing entities in the message text. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
Entities []MessageEntity `json:"entities,omitempty"`
}
SendMessageDraftRequest holds the parameters for sendMessageDraft.
type SendMessageOptions ¶
type SendMessageOptions struct {
ParseMode string
Entities []Entity
LinkPreviewOptions *LinkPreviewOptions
DisableNotification bool
ProtectContent bool
AllowPaidBroadcast bool
MessageEffectID string
// MessageThreadID targets a forum topic. Normally left unset —
// [Message.Answer] / [Message.Reply] auto-propagate the source
// message's own topic, so this only needs setting explicitly to send
// into a different topic.
MessageThreadID int64
DirectMessagesTopicID int64
SuggestedPostParameters *SuggestedPostParameters
// ReplyParameters sets the reply target explicitly (quoting, replying
// across chats, allow_sending_without_reply). [Message.Reply] fills in
// a plain same-chat reply automatically when this is nil.
ReplyParameters *ReplyParameters
ReplyMarkup ReplyMarkup
// BusinessConnectionID is normally left unset — [Message.Answer] /
// [Message.Reply] auto-propagate the source message's own
// BusinessConnectionID, so this only needs setting explicitly to
// override that.
BusinessConnectionID string
}
SendMessageOptions carries the optional parameters of sendMessage for the sugar send paths (Message.Answer / Message.Reply, Ctx.Answer / Ctx.Reply, ...). Zero values mean "use Telegram's default", so a struct literal reads naturally:
message.Answer("hi", &SendMessageOptions{ParseMode: "HTML"})
The full parameter set (including required fields) is the generated SendMessageRequest, used with TelegramBot.SendMessage directly.
type SendMessageRequest ¶
type SendMessageRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Text of the message to be sent, 1-4096 characters after entities parsing
Text string `json:"text"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Mode for parsing entities in the message text. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
Entities []MessageEntity `json:"entities,omitempty"`
// Link preview generation options for the message
LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendMessageRequest holds the parameters for sendMessage.
type SendPaidMediaRequest ¶
type SendPaidMediaRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance.
ChatID ChatID `json:"chat_id"`
// The number of Telegram Stars that must be paid to buy access to the media; 1-25000
StarCount int64 `json:"star_count"`
// A JSON-serialized array describing the media to be sent; up to 10 items
Media []InputPaidMedia `json:"media"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Bot-defined paid media payload, 0-128 bytes. This will not be displayed to the user, use it for your internal processes.
Payload string `json:"payload,omitempty"`
// Media caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the media caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendPaidMediaRequest holds the parameters for sendPaidMedia.
type SendPhotoRequest ¶
type SendPhotoRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files »
Photo InputFile `json:"photo"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the photo caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Pass True if the photo needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendPhotoRequest holds the parameters for sendPhoto.
type SendPollRequest ¶
type SendPollRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Polls can't be sent to channel direct messages chats.
ChatID ChatID `json:"chat_id"`
// Poll question, 1-300 characters
Question string `json:"question"`
// A JSON-serialized list of 1-12 answer options
Options []InputPollOption `json:"options"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Mode for parsing entities in the question. See formatting options for more details. Currently, only custom emoji entities are allowed.
QuestionParseMode string `json:"question_parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of question_parse_mode.
QuestionEntities []MessageEntity `json:"question_entities,omitempty"`
// True, if the poll needs to be anonymous, defaults to True
IsAnonymous *bool `json:"is_anonymous,omitempty"`
// Poll type, “quiz” or “regular”, defaults to “regular”
Type string `json:"type,omitempty"`
// Pass True, if the poll allows multiple answers, defaults to False
AllowsMultipleAnswers bool `json:"allows_multiple_answers,omitempty"`
// Pass True, if the poll allows to change chosen answer options, defaults to False for quizzes and to True for regular polls
AllowsRevoting bool `json:"allows_revoting,omitempty"`
// Pass True, if the poll options must be shown in random order
ShuffleOptions bool `json:"shuffle_options,omitempty"`
// Pass True, if answer options can be added to the poll after creation; not supported for anonymous polls and quizzes
AllowAddingOptions bool `json:"allow_adding_options,omitempty"`
// Pass True, if poll results must be shown only after the poll closes
HideResultsUntilCloses bool `json:"hide_results_until_closes,omitempty"`
// Pass True, if voting is limited to users who have been members of the chat where the poll is being sent for more than 24 hours; for channel chats only
MembersOnly bool `json:"members_only,omitempty"`
// A JSON-serialized list of 0-12 two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll; for channel chats only. Use “FT” as a country code to allow users with anonymous numbers to vote. If omitted or empty, then users from any country can participate in the poll.
CountryCodes []string `json:"country_codes,omitempty"`
// A JSON-serialized list of monotonically increasing 0-based identifiers of the correct answer options, required for polls in quiz mode
CorrectOptionIds []int64 `json:"correct_option_ids,omitempty"`
// Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing
Explanation string `json:"explanation,omitempty"`
// Mode for parsing entities in the explanation. See formatting options for more details.
ExplanationParseMode string `json:"explanation_parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of explanation_parse_mode.
ExplanationEntities []MessageEntity `json:"explanation_entities,omitempty"`
// Media added to the quiz explanation
ExplanationMedia InputPollMedia `json:"explanation_media,omitempty"`
// Amount of time in seconds the poll will be active after creation, 5-2628000. Can't be used together with close_date.
OpenPeriod int64 `json:"open_period,omitempty"`
// Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 2628000 seconds in the future. Can't be used together with open_period.
CloseDate int64 `json:"close_date,omitempty"`
// Pass True if the poll needs to be immediately closed. This can be useful for poll preview.
IsClosed bool `json:"is_closed,omitempty"`
// Description of the poll to be sent, 0-1024 characters after entities parsing
Description string `json:"description,omitempty"`
// Mode for parsing entities in the poll description. See formatting options for more details.
DescriptionParseMode string `json:"description_parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the poll description, which can be specified instead of description_parse_mode
DescriptionEntities []MessageEntity `json:"description_entities,omitempty"`
// Media added to the poll description
Media InputPollMedia `json:"media,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendPollRequest holds the parameters for sendPoll.
type SendRichMessageDraftRequest ¶
type SendRichMessageDraftRequest struct {
// Unique identifier for the target private chat
ChatID int64 `json:"chat_id"`
// Unique identifier of the message draft; must be non-zero. Changes to drafts with the same identifier are animated.
DraftID int64 `json:"draft_id"`
// The partial message to be streamed
RichMessage *InputRichMessage `json:"rich_message"`
// Unique identifier for the target message thread
MessageThreadID int64 `json:"message_thread_id,omitempty"`
}
SendRichMessageDraftRequest holds the parameters for sendRichMessageDraft.
type SendRichMessageRequest ¶
type SendRichMessageRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// The message to be sent
RichMessage *InputRichMessage `json:"rich_message"`
// Unique identifier of the business connection on behalf of which the message will be sent. Bot can send rich messages on behalf of a business account only if the corresponding user can send rich messages.
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendRichMessageRequest holds the parameters for sendRichMessage.
type SendStickerRequest ¶
type SendStickerRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. More information on Sending Files ». Video and animated stickers can't be sent via an HTTP URL.
Sticker InputFile `json:"sticker"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Emoji associated with the sticker; only for just uploaded stickers
Emoji string `json:"emoji,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendStickerRequest holds the parameters for sendSticker.
type SendVenueRequest ¶
type SendVenueRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Latitude of the venue
Latitude float64 `json:"latitude"`
// Longitude of the venue
Longitude float64 `json:"longitude"`
// Name of the venue
Title string `json:"title"`
// Address of the venue
Address string `json:"address"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Foursquare identifier of the venue
FoursquareID string `json:"foursquare_id,omitempty"`
// Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
FoursquareType string `json:"foursquare_type,omitempty"`
// Google Places identifier of the venue
GooglePlaceID string `json:"google_place_id,omitempty"`
// Google Places type of the venue. (See supported types.)
GooglePlaceType string `json:"google_place_type,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendVenueRequest holds the parameters for sendVenue.
type SendVideoNoteRequest ¶
type SendVideoNoteRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported.
VideoNote InputFile `json:"video_note"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Duration of sent video in seconds
Duration int64 `json:"duration,omitempty"`
// Video width and height, i.e. diameter of the video message
Length int64 `json:"length,omitempty"`
// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendVideoNoteRequest holds the parameters for sendVideoNote.
type SendVideoRequest ¶
type SendVideoRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files »
Video InputFile `json:"video"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Duration of sent video in seconds
Duration int64 `json:"duration,omitempty"`
// Video width
Width int64 `json:"width,omitempty"`
// Video height
Height int64 `json:"height,omitempty"`
// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass "attach://<file_attach_name>" if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
Thumbnail InputFile `json:"thumbnail,omitempty"`
// Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://<file_attach_name>" to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
Cover InputFile `json:"cover,omitempty"`
// Start timestamp for the video in the message
StartTimestamp int64 `json:"start_timestamp,omitempty"`
// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the video caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Pass True, if the caption must be shown above the message media
ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"`
// Pass True if the video needs to be covered with a spoiler animation
HasSpoiler bool `json:"has_spoiler,omitempty"`
// Pass True if the uploaded video is suitable for streaming
SupportsStreaming bool `json:"supports_streaming,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendVideoRequest holds the parameters for sendVideo.
type SendVoiceRequest ¶
type SendVoiceRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
Voice InputFile `json:"voice"`
// Unique identifier of the business connection on behalf of which the message will be sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
MessageThreadID int64 `json:"message_thread_id,omitempty"`
// Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
DirectMessagesTopicID int64 `json:"direct_messages_topic_id,omitempty"`
// Voice message caption, 0-1024 characters after entities parsing
Caption string `json:"caption,omitempty"`
// Mode for parsing entities in the voice message caption. See formatting options for more details.
ParseMode string `json:"parse_mode,omitempty"`
// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
CaptionEntities []MessageEntity `json:"caption_entities,omitempty"`
// Duration of the voice message in seconds
Duration int64 `json:"duration,omitempty"`
// Sends the message silently. Users will receive a notification with no sound.
DisableNotification bool `json:"disable_notification,omitempty"`
// Protects the contents of the sent message from forwarding and saving
ProtectContent bool `json:"protect_content,omitempty"`
// Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
AllowPaidBroadcast bool `json:"allow_paid_broadcast,omitempty"`
// Unique identifier of the message effect to be added to the message; for private chats only
MessageEffectID string `json:"message_effect_id,omitempty"`
// A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"`
// Description of the message to reply to
ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"`
// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
ReplyMarkup ReplyMarkup `json:"reply_markup,omitempty"`
}
SendVoiceRequest holds the parameters for sendVoice.
type Sender ¶
type Sender struct {
// User is set when the sender is a real user (including the dummy
// user Telegram substitutes for backward compatibility — check Chat
// first, since Chat being non-nil means User should be ignored).
User *User
// Chat is set when the update was sent "as" a chat: an anonymous
// admin (as the group), a channel post or its linked-channel
// auto-forward (as the channel), or an anonymous poll voter/reactor
// (as whichever chat voted/reacted anonymously).
Chat *Chat
// IsAutomaticForward mirrors [Message.IsAutomaticForward]: true when
// this is a channel post that was auto-forwarded into its linked
// discussion group, as opposed to the channel posting to itself.
IsAutomaticForward bool
// AuthorSignature is the anonymous admin's custom title, or a
// channel post's author signature, when Telegram provides one.
AuthorSignature string
// contains filtered or unexported fields
}
Sender resolves who is really behind an update, in the cases where Telegram reports the sender "as a chat" rather than as a user: anonymous group admins, channel posts, a channel's linked-discussion auto-forwards, and anonymous poll voters/reactors. In all of these, the update's User field is either absent or a fixed dummy value (Telegram's own docs call it a "fake sender user" for backward compatibility) — Chat carries the real identity instead.
Only Message- and reaction-derived Senders populate the internal chatID used by the Is* predicates; a Sender derived from a poll answer leaves it unset (Telegram gives poll answers no separate "landing chat" to compare against), so Sender.IsAnonymousAdmin / Sender.IsChannelPost / Sender.IsAnonymousChannel / Sender.IsLinkedChannel always report false for one. Use Sender.ID / Sender.Name / Sender.Username for poll-answer senders instead.
func (*Sender) ID ¶
ID returns the sender's identifying ID: Chat.ID when sending as a chat, otherwise User.ID, otherwise 0.
func (*Sender) IsAnonymousAdmin ¶
IsAnonymousAdmin reports whether this is an anonymous group/supergroup admin, sending as the group itself.
func (*Sender) IsAnonymousChannel ¶
IsAnonymousChannel reports whether this is a channel sending anonymously into a different chat (not an auto-forwarded linked-channel post).
func (*Sender) IsChannelPost ¶
IsChannelPost reports whether this is a channel posting to itself.
func (*Sender) IsLinkedChannel ¶
IsLinkedChannel reports whether this is a channel post that was automatically forwarded into its linked discussion group.
type SentGuestMessage ¶
type SentGuestMessage struct {
// Identifier of the sent inline message
InlineMessageID string `json:"inline_message_id"`
}
Describes an inline message sent by a guest bot.
type SentWebAppMessage ¶
type SentWebAppMessage struct {
// Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message.
InlineMessageID string `json:"inline_message_id,omitempty"`
}
Describes an inline message sent by a Web App on behalf of a user.
type SetBusinessAccountBioRequest ¶
type SetBusinessAccountBioRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// The new value of the bio for the business account; 0-140 characters
Bio string `json:"bio,omitempty"`
}
SetBusinessAccountBioRequest holds the parameters for setBusinessAccountBio.
type SetBusinessAccountGiftSettingsRequest ¶
type SetBusinessAccountGiftSettingsRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field
ShowGiftButton bool `json:"show_gift_button"`
// Types of gifts accepted by the business account
AcceptedGiftTypes *AcceptedGiftTypes `json:"accepted_gift_types"`
}
SetBusinessAccountGiftSettingsRequest holds the parameters for setBusinessAccountGiftSettings.
type SetBusinessAccountNameRequest ¶
type SetBusinessAccountNameRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// The new value of the first name for the business account; 1-64 characters
FirstName string `json:"first_name"`
// The new value of the last name for the business account; 0-64 characters
LastName string `json:"last_name,omitempty"`
}
SetBusinessAccountNameRequest holds the parameters for setBusinessAccountName.
type SetBusinessAccountProfilePhotoRequest ¶
type SetBusinessAccountProfilePhotoRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// The new profile photo to set
Photo InputProfilePhoto `json:"photo"`
// Pass True to set the public photo, which will be visible even if the main photo is hidden by the business account's privacy settings. An account can have only one public photo.
IsPublic bool `json:"is_public,omitempty"`
}
SetBusinessAccountProfilePhotoRequest holds the parameters for setBusinessAccountProfilePhoto.
type SetBusinessAccountUsernameRequest ¶
type SetBusinessAccountUsernameRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// The new value of the username for the business account; 0-32 characters
Username string `json:"username,omitempty"`
}
SetBusinessAccountUsernameRequest holds the parameters for setBusinessAccountUsername.
type SetChatAdministratorCustomTitleRequest ¶
type SetChatAdministratorCustomTitleRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// New custom title for the administrator; 0-16 characters, emoji are not allowed
CustomTitle string `json:"custom_title"`
}
SetChatAdministratorCustomTitleRequest holds the parameters for setChatAdministratorCustomTitle.
type SetChatDescriptionRequest ¶
type SetChatDescriptionRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// New chat description, 0-255 characters
Description string `json:"description,omitempty"`
}
SetChatDescriptionRequest holds the parameters for setChatDescription.
type SetChatMemberTagRequest ¶
type SetChatMemberTagRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// New tag for the member; 0-16 characters, emoji are not allowed
Tag string `json:"tag,omitempty"`
}
SetChatMemberTagRequest holds the parameters for setChatMemberTag.
type SetChatMenuButtonRequest ¶
type SetChatMenuButtonRequest struct {
// Unique identifier for the target private chat. If not specified, the bot's default menu button will be changed.
ChatID int64 `json:"chat_id,omitempty"`
// A JSON-serialized object for the bot's new menu button. Defaults to MenuButtonDefault.
MenuButton MenuButton `json:"menu_button,omitempty"`
}
SetChatMenuButtonRequest holds the parameters for setChatMenuButton.
type SetChatPermissionsRequest ¶
type SetChatPermissionsRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// A JSON-serialized object for new default chat permissions
Permissions *ChatPermissions `json:"permissions"`
// Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission.
UseIndependentChatPermissions bool `json:"use_independent_chat_permissions,omitempty"`
}
SetChatPermissionsRequest holds the parameters for setChatPermissions.
type SetChatPhotoRequest ¶
type SetChatPhotoRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// New chat photo, uploaded using multipart/form-data
Photo InputFile `json:"photo"`
}
SetChatPhotoRequest holds the parameters for setChatPhoto.
type SetChatStickerSetRequest ¶
type SetChatStickerSetRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Name of the sticker set to be set as the group sticker set
StickerSetName string `json:"sticker_set_name"`
}
SetChatStickerSetRequest holds the parameters for setChatStickerSet.
type SetChatTitleRequest ¶
type SetChatTitleRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// New chat title, 1-128 characters
Title string `json:"title"`
}
SetChatTitleRequest holds the parameters for setChatTitle.
type SetCustomEmojiStickerSetThumbnailRequest ¶
type SetCustomEmojiStickerSetThumbnailRequest struct {
// Sticker set name
Name string `json:"name"`
// Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail
CustomEmojiID string `json:"custom_emoji_id,omitempty"`
}
SetCustomEmojiStickerSetThumbnailRequest holds the parameters for setCustomEmojiStickerSetThumbnail.
type SetGameScoreRequest ¶
type SetGameScoreRequest struct {
// User identifier
UserID int64 `json:"user_id"`
// New score, must be non-negative
Score int64 `json:"score"`
// Pass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters.
Force bool `json:"force,omitempty"`
// Pass True if the game message should not be automatically edited to include the current scoreboard
DisableEditMessage bool `json:"disable_edit_message,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat.
ChatID int64 `json:"chat_id,omitempty"`
// Required if inline_message_id is not specified. Identifier of the sent message.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
}
SetGameScoreRequest holds the parameters for setGameScore.
type SetManagedBotAccessSettingsRequest ¶
type SetManagedBotAccessSettingsRequest struct {
// User identifier of the managed bot whose access settings will be changed
UserID int64 `json:"user_id"`
// Pass True, if only selected users can access the bot. The bot's owner can always access it.
IsAccessRestricted bool `json:"is_access_restricted"`
// A JSON-serialized list of up to 10 identifiers of users who will have access to the bot in addition to its owner. Ignored if is_access_restricted is false.
AddedUserIds []int64 `json:"added_user_ids,omitempty"`
}
SetManagedBotAccessSettingsRequest holds the parameters for setManagedBotAccessSettings.
type SetMessageReactionRequest ¶
type SetMessageReactionRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead.
MessageID int64 `json:"message_id"`
// A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots.
Reaction []ReactionType `json:"reaction,omitempty"`
// Pass True to set the reaction with a big animation
IsBig bool `json:"is_big,omitempty"`
}
SetMessageReactionRequest holds the parameters for setMessageReaction.
type SetMyCommandsRequest ¶
type SetMyCommandsRequest struct {
// A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
Commands []BotCommand `json:"commands"`
// A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
Scope BotCommandScope `json:"scope,omitempty"`
// A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands.
LanguageCode string `json:"language_code,omitempty"`
}
SetMyCommandsRequest holds the parameters for setMyCommands.
type SetMyDefaultAdministratorRightsRequest ¶
type SetMyDefaultAdministratorRightsRequest struct {
// A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared.
Rights *ChatAdministratorRights `json:"rights,omitempty"`
// Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.
ForChannels bool `json:"for_channels,omitempty"`
}
SetMyDefaultAdministratorRightsRequest holds the parameters for setMyDefaultAdministratorRights.
type SetMyDescriptionRequest ¶
type SetMyDescriptionRequest struct {
// New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
Description string `json:"description,omitempty"`
// A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.
LanguageCode string `json:"language_code,omitempty"`
}
SetMyDescriptionRequest holds the parameters for setMyDescription.
type SetMyNameRequest ¶
type SetMyNameRequest struct {
// New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
Name string `json:"name,omitempty"`
// A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name.
LanguageCode string `json:"language_code,omitempty"`
}
SetMyNameRequest holds the parameters for setMyName.
type SetMyProfilePhotoRequest ¶
type SetMyProfilePhotoRequest struct {
// The new profile photo to set
Photo InputProfilePhoto `json:"photo"`
}
SetMyProfilePhotoRequest holds the parameters for setMyProfilePhoto.
type SetMyShortDescriptionRequest ¶
type SetMyShortDescriptionRequest struct {
// New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
ShortDescription string `json:"short_description,omitempty"`
// A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description.
LanguageCode string `json:"language_code,omitempty"`
}
SetMyShortDescriptionRequest holds the parameters for setMyShortDescription.
type SetPassportDataErrorsRequest ¶
type SetPassportDataErrorsRequest struct {
// User identifier
UserID int64 `json:"user_id"`
// A JSON-serialized array describing the errors
Errors []PassportElementError `json:"errors"`
}
SetPassportDataErrorsRequest holds the parameters for setPassportDataErrors.
type SetStickerEmojiListRequest ¶
type SetStickerEmojiListRequest struct {
// File identifier of the sticker
Sticker string `json:"sticker"`
// A JSON-serialized list of 1-20 emoji associated with the sticker
EmojiList []string `json:"emoji_list"`
}
SetStickerEmojiListRequest holds the parameters for setStickerEmojiList.
type SetStickerKeywordsRequest ¶
type SetStickerKeywordsRequest struct {
// File identifier of the sticker
Sticker string `json:"sticker"`
// A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters
Keywords []string `json:"keywords,omitempty"`
}
SetStickerKeywordsRequest holds the parameters for setStickerKeywords.
type SetStickerMaskPositionRequest ¶
type SetStickerMaskPositionRequest struct {
// File identifier of the sticker
Sticker string `json:"sticker"`
// A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position.
MaskPosition *MaskPosition `json:"mask_position,omitempty"`
}
SetStickerMaskPositionRequest holds the parameters for setStickerMaskPosition.
type SetStickerPositionInSetRequest ¶
type SetStickerPositionInSetRequest struct {
// File identifier of the sticker
Sticker string `json:"sticker"`
// New sticker position in the set, zero-based
Position int64 `json:"position"`
}
SetStickerPositionInSetRequest holds the parameters for setStickerPositionInSet.
type SetStickerSetThumbnailRequest ¶
type SetStickerSetThumbnailRequest struct {
// Sticker set name
Name string `json:"name"`
// User identifier of the sticker set owner
UserID int64 `json:"user_id"`
// Format of the thumbnail, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, or “video” for a .WEBM video
Format string `json:"format"`
// A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animation-requirements for animated sticker technical requirements), or a .WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.
Thumbnail InputFile `json:"thumbnail,omitempty"`
}
SetStickerSetThumbnailRequest holds the parameters for setStickerSetThumbnail.
type SetStickerSetTitleRequest ¶
type SetStickerSetTitleRequest struct {
// Sticker set name
Name string `json:"name"`
// Sticker set title, 1-64 characters
Title string `json:"title"`
}
SetStickerSetTitleRequest holds the parameters for setStickerSetTitle.
type SetUserEmojiStatusRequest ¶
type SetUserEmojiStatusRequest struct {
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Custom emoji identifier of the emoji status to set. Pass an empty string to remove the status.
EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"`
// Expiration date of the emoji status, if any
EmojiStatusExpirationDate int64 `json:"emoji_status_expiration_date,omitempty"`
}
SetUserEmojiStatusRequest holds the parameters for setUserEmojiStatus.
type SetWebhookRequest ¶
type SetWebhookRequest struct {
// HTTPS URL to send updates to. Use an empty string to remove webhook integration.
URL string `json:"url"`
// Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.
Certificate InputFile `json:"certificate,omitempty"`
// The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS
IpAddress string `json:"ip_address,omitempty"`
// The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.
MaxConnections int64 `json:"max_connections,omitempty"`
// A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.
AllowedUpdates []string `json:"allowed_updates,omitempty"`
// Pass True to drop all pending updates
DropPendingUpdates bool `json:"drop_pending_updates,omitempty"`
// A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you.
SecretToken string `json:"secret_token,omitempty"`
}
SetWebhookRequest holds the parameters for setWebhook.
type SharedUser ¶
type SharedUser struct {
UserID int64 `json:"user_id"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Username string `json:"username,omitempty"`
Photo []PhotoSize `json:"photo,omitempty"`
}
This object contains information about a user that was shared with the bot using a KeyboardButtonRequestUsers button.
type ShippingAddress ¶
type ShippingAddress struct {
// Two-letter ISO 3166-1 alpha-2 country code
CountryCode string `json:"country_code"`
// State, if applicable
State string `json:"state"`
// City
City string `json:"city"`
// First line for the address
StreetLine1 string `json:"street_line1"`
// Second line for the address
StreetLine2 string `json:"street_line2"`
// Address post code
PostCode string `json:"post_code"`
}
This object represents a shipping address.
type ShippingOption ¶
type ShippingOption struct {
// Shipping option identifier
ID string `json:"id"`
// Option title
Title string `json:"title"`
// List of price portions
Prices []LabeledPrice `json:"prices"`
}
This object represents one shipping option.
type ShippingQuery ¶
type ShippingQuery struct {
// Unique query identifier
ID string `json:"id"`
// User who sent the query
From *User `json:"from"`
// Bot-specified invoice payload
InvoicePayload string `json:"invoice_payload"`
// User specified shipping address
ShippingAddress *ShippingAddress `json:"shipping_address"`
}
This object contains information about an incoming shipping query.
type StarAmount ¶
type StarAmount struct {
// Integer amount of Telegram Stars, rounded to 0; can be negative
Amount int64 `json:"amount"`
// Optional. The number of 1/1000000000 shares of Telegram Stars; from -999999999 to 999999999; can be negative if and only if amount is non-positive
NanostarAmount int64 `json:"nanostar_amount,omitempty"`
}
Describes an amount of Telegram Stars.
type StarTransaction ¶
type StarTransaction struct {
// Unique identifier of the transaction. Coincides with the identifier of the original transaction for refund transactions. Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users.
ID string `json:"id"`
// Integer amount of Telegram Stars transferred by the transaction
Amount int64 `json:"amount"`
// Optional. The number of 1/1000000000 shares of Telegram Stars transferred by the transaction; from 0 to 999999999
NanostarAmount int64 `json:"nanostar_amount,omitempty"`
// Date the transaction was created in Unix time
Date int64 `json:"date"`
// Optional. Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). Only for incoming transactions.
Source TransactionPartner `json:"source,omitempty"`
// Optional. Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). Only for outgoing transactions.
Receiver TransactionPartner `json:"receiver,omitempty"`
}
Describes a Telegram Star transaction. Note that if the buyer initiates a chargeback with the payment provider from whom they acquired Stars (e.g., Apple, Google) following this transaction, the refunded Stars will be deducted from the bot's balance. This is outside of Telegram's control.
func (*StarTransaction) UnmarshalJSON ¶
func (v *StarTransaction) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes StarTransaction's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type StarTransactions ¶
type StarTransactions struct {
// The list of transactions
Transactions []StarTransaction `json:"transactions"`
}
Contains a list of Telegram Star transactions.
type State ¶
type State string
State represents a single step in a conversation. It's a plain string under the hood — group related states with a StateGroup, e.g.:
var Reg = StateGroup("registration")
var (
RegWaitingName = Reg.New("waiting_name") // "registration:waiting_name"
RegWaitingAge = Reg.New("waiting_age") // "registration:waiting_age"
)
const AnyState State = "*"
AnyState matches in StateIs when the user has any state set (i.e. is somewhere in a conversation), regardless of which one.
const NoState State = ""
NoState matches a user who has no FSM state set, i.e. isn't in a conversation.
type StateGroup ¶
type StateGroup string
StateGroup names a family of related states. It exists so a whole conversation can be matched at once (StateIn) without listing every step, and so state names can't collide across flows.
func (StateGroup) Contains ¶
func (g StateGroup) Contains(s State) bool
Contains reports whether s belongs to this group.
func (StateGroup) New ¶
func (g StateGroup) New(name string) State
New derives a State belonging to this group: StateGroup("reg").New("name") is the State "reg:name".
type StepOption ¶
type StepOption func(*stepConfig)
StepOption configures a Wizard.Step registration.
func WithStepAllowCommands ¶
func WithStepAllowCommands() StepOption
WithStepAllowCommands lets this step's handler see text starting with "/". By default, any command falls through past the wizard instead of being misread as step input — so a stray command mid-wizard reaches its own handler (or nothing) instead of being swallowed.
func WithStepIgnore ¶
func WithStepIgnore(filters ...Filter) StepOption
WithStepIgnore excludes updates matching any of filters from this step — e.g. a persistent reply-keyboard button that should fall through to its own handler instead of being swallowed as this step's answer.
func WithStepName ¶
func WithStepName(name string) StepOption
WithStepName overrides the step's underlying State name (default "step<N>") — useful for readable state values when inspecting storage directly or in logs.
type Sticker ¶
type Sticker struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video.
Type string `json:"type"`
// Sticker width
Width int64 `json:"width"`
// Sticker height
Height int64 `json:"height"`
// True, if the sticker is animated
IsAnimated bool `json:"is_animated"`
// True, if the sticker is a video sticker
IsVideo bool `json:"is_video"`
// Optional. Sticker thumbnail in the .WEBP or .JPG format
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
// Optional. Emoji associated with the sticker
Emoji string `json:"emoji,omitempty"`
// Optional. Name of the sticker set to which the sticker belongs
SetName string `json:"set_name,omitempty"`
// Optional. For premium regular stickers, premium animation for the sticker
PremiumAnimation *File `json:"premium_animation,omitempty"`
// Optional. For mask stickers, the position where the mask should be placed
MaskPosition *MaskPosition `json:"mask_position,omitempty"`
// Optional. For custom emoji stickers, unique identifier of the custom emoji
CustomEmojiID string `json:"custom_emoji_id,omitempty"`
// Optional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places
NeedsRepainting bool `json:"needs_repainting,omitempty"`
// Optional. File size in bytes
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a sticker.
type StickerSet ¶
type StickerSet struct {
// Sticker set name
Name string `json:"name"`
// Sticker set title
Title string `json:"title"`
// Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji”
StickerType string `json:"sticker_type"`
// List of all set stickers
Stickers []Sticker `json:"stickers"`
// Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
}
This object represents a sticker set.
type StopMessageLiveLocationRequest ¶
type StopMessageLiveLocationRequest struct {
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
ChatID ChatID `json:"chat_id,omitzero"`
// Required if inline_message_id is not specified. Identifier of the message with live location to stop.
MessageID int64 `json:"message_id,omitempty"`
// Required if chat_id and message_id are not specified. Identifier of the inline message.
InlineMessageID string `json:"inline_message_id,omitempty"`
// A JSON-serialized object for a new inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
StopMessageLiveLocationRequest holds the parameters for stopMessageLiveLocation.
type StopPollRequest ¶
type StopPollRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Identifier of the original message with the poll
MessageID int64 `json:"message_id"`
// Unique identifier of the business connection on behalf of which the message to be edited was sent
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// A JSON-serialized object for a new message inline keyboard
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}
StopPollRequest holds the parameters for stopPoll.
type StorageKey ¶
StorageKey identifies one conversation in an FSMStorage. Which fields are populated depends on the bot's FSMKeyStrategy — the default fills ChatID and UserID; ThreadID is only used under FSMKeyUserInTopic.
type Story ¶
type Story struct {
// Chat that posted the story
Chat *Chat `json:"chat"`
// Unique identifier for the story in the chat
ID int64 `json:"id"`
}
This object represents a story.
type StoryArea ¶
type StoryArea struct {
// Position of the area
Position *StoryAreaPosition `json:"position"`
// Type of the area
Type StoryAreaType `json:"type"`
}
Describes a clickable area on a story media.
func (*StoryArea) UnmarshalJSON ¶
UnmarshalJSON decodes StoryArea's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type StoryAreaPosition ¶
type StoryAreaPosition struct {
// The abscissa of the area's center, as a percentage of the media width
XPercentage float64 `json:"x_percentage"`
// The ordinate of the area's center, as a percentage of the media height
YPercentage float64 `json:"y_percentage"`
// The width of the area's rectangle, as a percentage of the media width
WidthPercentage float64 `json:"width_percentage"`
// The height of the area's rectangle, as a percentage of the media height
HeightPercentage float64 `json:"height_percentage"`
// The clockwise rotation angle of the rectangle, in degrees; 0-360
RotationAngle float64 `json:"rotation_angle"`
// The radius of the rectangle corner rounding, as a percentage of the media width
CornerRadiusPercentage float64 `json:"corner_radius_percentage"`
}
Describes the position of a clickable area within a story.
type StoryAreaType ¶
type StoryAreaType interface {
GetType() string
// contains filtered or unexported methods
}
Describes the type of a clickable area on a story. Currently, it can be one of
type StoryAreaTypeLink ¶
type StoryAreaTypeLink struct {
// Type of the area, always “link”
Type string `json:"type"`
// HTTP or tg:// URL to be opened when the area is clicked
URL string `json:"url"`
}
Describes a story area pointing to an HTTP or tg:// link. Currently, a story can have up to 3 link areas.
func (*StoryAreaTypeLink) GetType ¶
func (v *StoryAreaTypeLink) GetType() string
type StoryAreaTypeLocation ¶
type StoryAreaTypeLocation struct {
// Type of the area, always “location”
Type string `json:"type"`
// Location latitude in degrees
Latitude float64 `json:"latitude"`
// Location longitude in degrees
Longitude float64 `json:"longitude"`
// Optional. Address of the location
Address *LocationAddress `json:"address,omitempty"`
}
Describes a story area pointing to a location. Currently, a story can have up to 10 location areas.
func (*StoryAreaTypeLocation) GetType ¶
func (v *StoryAreaTypeLocation) GetType() string
The Get* methods below implement StoryAreaType: fields shared by every member, callable on the interface value directly without a type switch.
type StoryAreaTypeSuggestedReaction ¶
type StoryAreaTypeSuggestedReaction struct {
// Type of the area, always “suggested_reaction”
Type string `json:"type"`
// Type of the reaction
ReactionType ReactionType `json:"reaction_type"`
// Optional. Pass True if the reaction area has a dark background
IsDark bool `json:"is_dark,omitempty"`
// Optional. Pass True if reaction area corner is flipped
IsFlipped bool `json:"is_flipped,omitempty"`
}
Describes a story area pointing to a suggested reaction. Currently, a story can have up to 5 suggested reaction areas.
func (*StoryAreaTypeSuggestedReaction) GetType ¶
func (v *StoryAreaTypeSuggestedReaction) GetType() string
func (*StoryAreaTypeSuggestedReaction) UnmarshalJSON ¶
func (v *StoryAreaTypeSuggestedReaction) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes StoryAreaTypeSuggestedReaction's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type StoryAreaTypeUniqueGift ¶
type StoryAreaTypeUniqueGift struct {
// Type of the area, always “unique_gift”
Type string `json:"type"`
// Unique name of the gift
Name string `json:"name"`
}
Describes a story area pointing to a unique gift. Currently, a story can have at most 1 unique gift area.
func (*StoryAreaTypeUniqueGift) GetType ¶
func (v *StoryAreaTypeUniqueGift) GetType() string
type StoryAreaTypeWeather ¶
type StoryAreaTypeWeather struct {
// Type of the area, always “weather”
Type string `json:"type"`
// Temperature, in degree Celsius
Temperature float64 `json:"temperature"`
// Emoji representing the weather
Emoji string `json:"emoji"`
// A color of the area background in the ARGB format
BackgroundColor int64 `json:"background_color"`
}
Describes a story area containing weather information. Currently, a story can have up to 3 weather areas.
func (*StoryAreaTypeWeather) GetType ¶
func (v *StoryAreaTypeWeather) GetType() string
type SuccessfulPayment ¶
type SuccessfulPayment struct {
// Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars
Currency string `json:"currency"`
// Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
TotalAmount int64 `json:"total_amount"`
// Bot-specified invoice payload
InvoicePayload string `json:"invoice_payload"`
// Optional. Expiration date of the subscription, in Unix time; for recurring payments only
SubscriptionExpirationDate int64 `json:"subscription_expiration_date,omitempty"`
// Optional. True, if the payment is a recurring payment for a subscription
IsRecurring bool `json:"is_recurring,omitempty"`
// Optional. True, if the payment is the first payment for a subscription
IsFirstRecurring bool `json:"is_first_recurring,omitempty"`
// Optional. Identifier of the shipping option chosen by the user
ShippingOptionID string `json:"shipping_option_id,omitempty"`
// Optional. Order information provided by the user
OrderInfo *OrderInfo `json:"order_info,omitempty"`
// Telegram payment identifier
TelegramPaymentChargeID string `json:"telegram_payment_charge_id"`
// Provider payment identifier
ProviderPaymentChargeID string `json:"provider_payment_charge_id"`
}
This object contains basic information about a successful payment. Note that if the buyer initiates a chargeback with the relevant payment provider following this transaction, the funds may be debited from your balance. This is outside of Telegram's control.
type SuggestedPostApprovalFailed ¶
type SuggestedPostApprovalFailed struct {
// Optional. Message containing the suggested post whose approval has failed. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"`
// Expected price of the post
Price *SuggestedPostPrice `json:"price"`
}
Describes a service message about the failed approval of a suggested post. Currently, only caused by insufficient user funds at the time of approval.
type SuggestedPostApproved ¶
type SuggestedPostApproved struct {
// Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"`
// Optional. Amount paid for the post
Price *SuggestedPostPrice `json:"price,omitempty"`
// Date when the post will be published
SendDate int64 `json:"send_date"`
}
Describes a service message about the approval of a suggested post.
type SuggestedPostDeclined ¶
type SuggestedPostDeclined struct {
// Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"`
// Optional. Comment with which the post was declined
Comment string `json:"comment,omitempty"`
}
Describes a service message about the rejection of a suggested post.
type SuggestedPostInfo ¶
type SuggestedPostInfo struct {
// State of the suggested post. Currently, it can be one of “pending”, “approved”, “declined”.
State string `json:"state"`
// Optional. Proposed price of the post. If the field is omitted, then the post is unpaid.
Price *SuggestedPostPrice `json:"price,omitempty"`
// Optional. Proposed send date of the post. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user or administrator who approves it.
SendDate int64 `json:"send_date,omitempty"`
}
Contains information about a suggested post.
type SuggestedPostPaid ¶
type SuggestedPostPaid struct {
// Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"`
// Currency in which the payment was made. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins.
Currency string `json:"currency"`
// Optional. The amount of the currency that was received by the channel in nanotoncoins; for payments in toncoins only
Amount int64 `json:"amount,omitempty"`
// Optional. The amount of Telegram Stars that was received by the channel; for payments in Telegram Stars only
StarAmount *StarAmount `json:"star_amount,omitempty"`
}
Describes a service message about a successful payment for a suggested post.
type SuggestedPostParameters ¶
type SuggestedPostParameters struct {
// Optional. Proposed price for the post. If the field is omitted, then the post is unpaid.
Price *SuggestedPostPrice `json:"price,omitempty"`
// Optional. Proposed send date of the post. If specified, then the date must be between 300 second and 2678400 seconds (30 days) in the future. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user who approves it.
SendDate int64 `json:"send_date,omitempty"`
}
Contains parameters of a post that is being suggested by the bot.
type SuggestedPostPrice ¶
type SuggestedPostPrice struct {
// Currency in which the post will be paid. Currently, must be one of “XTR” for Telegram Stars or “TON” for toncoins.
Currency string `json:"currency"`
// The amount of the currency that will be paid for the post in the smallest units of the currency, i.e. Telegram Stars or nanotoncoins. Currently, price in Telegram Stars must be between 5 and 100000, and price in nanotoncoins must be between 10000000 and 10000000000000.
Amount int64 `json:"amount"`
}
Describes the price of a suggested post.
type SuggestedPostRefunded ¶
type SuggestedPostRefunded struct {
// Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"`
// Reason for the refund. Currently, one of “post_deleted” if the post was deleted within 24 hours of being posted or removed from scheduled messages without being posted, or “payment_refunded” if the payer refunded their payment.
Reason string `json:"reason"`
}
Describes a service message about a payment refund for a suggested post.
type SwitchInlineQueryChosenChat ¶
type SwitchInlineQueryChosenChat struct {
// Optional. The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted.
Query string `json:"query,omitempty"`
// Optional. True, if private chats with users can be chosen
AllowUserChats bool `json:"allow_user_chats,omitempty"`
// Optional. True, if private chats with bots can be chosen
AllowBotChats bool `json:"allow_bot_chats,omitempty"`
// Optional. True, if group and supergroup chats can be chosen
AllowGroupChats bool `json:"allow_group_chats,omitempty"`
// Optional. True, if channel chats can be chosen
AllowChannelChats bool `json:"allow_channel_chats,omitempty"`
}
This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query.
type TelegramBot ¶
type TelegramBot struct {
// contains filtered or unexported fields
}
TelegramBot is a running bot: one Bot API client, one Router, one FSM storage backend, and the worker pool that both TelegramBot.Run (polling) and TelegramBot.RunWebhook dispatch through. Construct one with NewTelegramBot, wire a router with TelegramBot.Dispatch, then call Run or RunWebhook.
A TelegramBot runs once: Run/RunWebhook/StartWorkers close updateChan on shutdown (TelegramBot.StopWorkers) and never reopen it, so a second call after the first has returned fails fast instead of panicking on a send-to-closed-channel later. Construct a new TelegramBot to run again.
func NewTelegramBot ¶
func NewTelegramBot(token string, opts ...Option) (*TelegramBot, error)
NewTelegramBot creates a bot for token, applies opts, and validates the token with a real getMe call before returning — so a bad token fails here, at construction, rather than on the first update. The returned bot has no router yet; call TelegramBot.Dispatch before TelegramBot.Run or TelegramBot.RunWebhook. Pass WithoutGetMe to skip that call (and the network round-trip, and its uncancelable context) entirely.
func (*TelegramBot) AddStickerToSet ¶
func (b *TelegramBot) AddStickerToSet(ctx context.Context, req *AddStickerToSetRequest) (bool, error)
Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns True on success.
Returns True on success.
func (*TelegramBot) AnswerCallbackQuery ¶
func (b *TelegramBot) AnswerCallbackQuery(ctx context.Context, req *AnswerCallbackQueryRequest) (bool, error)
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
On success, True is returned.
func (*TelegramBot) AnswerChatJoinRequestQuery ¶
func (b *TelegramBot) AnswerChatJoinRequestQuery(ctx context.Context, req *AnswerChatJoinRequestQueryRequest) (bool, error)
Use this method to process a received chat join request query. Returns True on success.
Returns True on success.
func (*TelegramBot) AnswerGuestQuery ¶
func (b *TelegramBot) AnswerGuestQuery(ctx context.Context, req *AnswerGuestQueryRequest) (*SentGuestMessage, error)
Use this method to reply to a received guest message. On success, a SentGuestMessage object is returned.
On success, a SentGuestMessage object is returned.
func (*TelegramBot) AnswerInlineQuery ¶
func (b *TelegramBot) AnswerInlineQuery(ctx context.Context, req *AnswerInlineQueryRequest) (bool, error)
Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.
On success, True is returned.
func (*TelegramBot) AnswerPreCheckoutQuery ¶
func (b *TelegramBot) AnswerPreCheckoutQuery(ctx context.Context, req *AnswerPreCheckoutQueryRequest) (bool, error)
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
On success, True is returned.
func (*TelegramBot) AnswerShippingQuery ¶
func (b *TelegramBot) AnswerShippingQuery(ctx context.Context, req *AnswerShippingQueryRequest) (bool, error)
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
On success, True is returned.
func (*TelegramBot) AnswerWebAppQuery ¶
func (b *TelegramBot) AnswerWebAppQuery(ctx context.Context, req *AnswerWebAppQueryRequest) (*SentWebAppMessage, error)
Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
On success, a SentWebAppMessage object is returned.
func (*TelegramBot) ApproveChatJoinRequest ¶
func (b *TelegramBot) ApproveChatJoinRequest(ctx context.Context, req *ApproveChatJoinRequestRequest) (bool, error)
Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
Returns True on success.
func (*TelegramBot) ApproveSuggestedPost ¶
func (b *TelegramBot) ApproveSuggestedPost(ctx context.Context, req *ApproveSuggestedPostRequest) (bool, error)
Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat. Returns True on success.
Returns True on success.
func (*TelegramBot) BanChatMember ¶
func (b *TelegramBot) BanChatMember(ctx context.Context, req *BanChatMemberRequest) (bool, error)
Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. Returns True on success.
func (*TelegramBot) BanChatSenderChat ¶
func (b *TelegramBot) BanChatSenderChat(ctx context.Context, req *BanChatSenderChatRequest) (bool, error)
Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) Close ¶
func (b *TelegramBot) Close(ctx context.Context) (bool, error)
Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters.
The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success.
func (*TelegramBot) CloseForumTopic ¶
func (b *TelegramBot) CloseForumTopic(ctx context.Context, req *CloseForumTopicRequest) (bool, error)
Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
Returns True on success.
func (*TelegramBot) CloseGeneralForumTopic ¶
func (b *TelegramBot) CloseGeneralForumTopic(ctx context.Context, req *CloseGeneralForumTopicRequest) (bool, error)
Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) ConvertGiftToStars ¶
func (b *TelegramBot) ConvertGiftToStars(ctx context.Context, req *ConvertGiftToStarsRequest) (bool, error)
Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) CopyMessage ¶
func (b *TelegramBot) CopyMessage(ctx context.Context, req *CopyMessageRequest) (*MessageID, error)
Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
Returns the MessageId of the sent message on success.
func (*TelegramBot) CopyMessages ¶
func (b *TelegramBot) CopyMessages(ctx context.Context, req *CopyMessagesRequest) ([]MessageID, error)
Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.
On success, an array of MessageId of the sent messages is returned.
func (*TelegramBot) CreateChatInviteLink ¶
func (b *TelegramBot) CreateChatInviteLink(ctx context.Context, req *CreateChatInviteLinkRequest) (*ChatInviteLink, error)
Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
Returns the new invite link as ChatInviteLink object.
func (*TelegramBot) CreateChatSubscriptionInviteLink ¶
func (b *TelegramBot) CreateChatSubscriptionInviteLink(ctx context.Context, req *CreateChatSubscriptionInviteLinkRequest) (*ChatInviteLink, error)
Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object.
Returns the new invite link as a ChatInviteLink object.
func (*TelegramBot) CreateForumTopic ¶
func (b *TelegramBot) CreateForumTopic(ctx context.Context, req *CreateForumTopicRequest) (*ForumTopic, error)
Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object.
Returns information about the created topic as a ForumTopic object.
func (*TelegramBot) CreateInvoiceLink ¶
func (b *TelegramBot) CreateInvoiceLink(ctx context.Context, req *CreateInvoiceLinkRequest) (string, error)
Use this method to create a link for an invoice. Returns the created invoice link as String on success.
Returns the created invoice link as String on success.
func (*TelegramBot) CreateNewStickerSet ¶
func (b *TelegramBot) CreateNewStickerSet(ctx context.Context, req *CreateNewStickerSetRequest) (bool, error)
Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success.
Returns True on success.
func (*TelegramBot) CreateStartGroupLink ¶
func (b *TelegramBot) CreateStartGroupLink(payload string, encode bool) (string, error)
CreateStartGroupLink is TelegramBot.CreateStartLink for the "add me to a group" flow: https://t.me/<bot>?startgroup=<payload>. Telegram shows a group picker, adds the bot, and delivers the payload like a /start deep link.
func (*TelegramBot) CreateStartLink ¶
func (b *TelegramBot) CreateStartLink(payload string, encode bool) (string, error)
CreateStartLink returns a https://t.me/<bot>?start=<payload> deep link that opens a private chat with this bot and delivers the payload to the /start handler (route it with FilterCommandStartDeepLink, read it via c.Command().Args).
With encode=false the payload must already satisfy Telegram's rules (1-64 chars of A-Z a-z 0-9 _ -); with encode=true it is base64-wrapped first (decode with DecodeStartPayload), which fits 48 raw bytes.
func (*TelegramBot) DeclineChatJoinRequest ¶
func (b *TelegramBot) DeclineChatJoinRequest(ctx context.Context, req *DeclineChatJoinRequestRequest) (bool, error)
Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
Returns True on success.
func (*TelegramBot) DeclineSuggestedPost ¶
func (b *TelegramBot) DeclineSuggestedPost(ctx context.Context, req *DeclineSuggestedPostRequest) (bool, error)
Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteAllMessageReactions ¶
func (b *TelegramBot) DeleteAllMessageReactions(ctx context.Context, req *DeleteAllMessageReactionsRequest) (bool, error)
Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteBusinessMessages ¶
func (b *TelegramBot) DeleteBusinessMessages(ctx context.Context, req *DeleteBusinessMessagesRequest) (bool, error)
Delete messages on behalf of a business account. Requires the can_delete_sent_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteChatPhoto ¶
func (b *TelegramBot) DeleteChatPhoto(ctx context.Context, req *DeleteChatPhotoRequest) (bool, error)
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteChatStickerSet ¶
func (b *TelegramBot) DeleteChatStickerSet(ctx context.Context, req *DeleteChatStickerSetRequest) (bool, error)
Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
func (*TelegramBot) DeleteForumTopic ¶
func (b *TelegramBot) DeleteForumTopic(ctx context.Context, req *DeleteForumTopicRequest) (bool, error)
Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteMessage ¶
func (b *TelegramBot) DeleteMessage(ctx context.Context, req *DeleteMessageRequest) (bool, error)
Use this method to delete a message, including service messages, with the following limitations: - A message can only be deleted if it was sent less than 48 hours ago. - Service messages about a supergroup, channel, or forum topic creation can't be deleted. - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. - Bots can delete outgoing messages in private chats, groups, and supergroups. - Bots can delete incoming messages in private chats. - Bots granted can_post_messages permissions can delete outgoing messages in channels. - If the bot is an administrator of a group, it can delete any message there. - If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there. - If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteMessageReaction ¶
func (b *TelegramBot) DeleteMessageReaction(ctx context.Context, req *DeleteMessageReactionRequest) (bool, error)
Use this method to remove a reaction from a message in a group or a supergroup chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteMessages ¶
func (b *TelegramBot) DeleteMessages(ctx context.Context, req *DeleteMessagesRequest) (bool, error)
Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteMyCommands ¶
func (b *TelegramBot) DeleteMyCommands(ctx context.Context, req *DeleteMyCommandsRequest) (bool, error)
Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteStickerFromSet ¶
func (b *TelegramBot) DeleteStickerFromSet(ctx context.Context, req *DeleteStickerFromSetRequest) (bool, error)
Use this method to delete a sticker from a set created by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteStickerSet ¶
func (b *TelegramBot) DeleteStickerSet(ctx context.Context, req *DeleteStickerSetRequest) (bool, error)
Use this method to delete a sticker set that was created by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteStory ¶
func (b *TelegramBot) DeleteStory(ctx context.Context, req *DeleteStoryRequest) (bool, error)
Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) DeleteWebhook ¶
func (b *TelegramBot) DeleteWebhook(ctx context.Context, req *DeleteWebhookRequest) (bool, error)
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
Returns True on success.
func (*TelegramBot) Dispatch ¶
func (b *TelegramBot) Dispatch(r *Router)
Dispatch sets the router that handles every incoming update. Call it before Run.
func (*TelegramBot) EditChatInviteLink ¶
func (b *TelegramBot) EditChatInviteLink(ctx context.Context, req *EditChatInviteLinkRequest) (*ChatInviteLink, error)
Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.
Returns the edited invite link as a ChatInviteLink object.
func (*TelegramBot) EditChatSubscriptionInviteLink ¶
func (b *TelegramBot) EditChatSubscriptionInviteLink(ctx context.Context, req *EditChatSubscriptionInviteLinkRequest) (*ChatInviteLink, error)
Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object.
Returns the edited invite link as a ChatInviteLink object.
func (*TelegramBot) EditForumTopic ¶
func (b *TelegramBot) EditForumTopic(ctx context.Context, req *EditForumTopicRequest) (bool, error)
Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
Returns True on success.
func (*TelegramBot) EditGeneralForumTopic ¶
func (b *TelegramBot) EditGeneralForumTopic(ctx context.Context, req *EditGeneralForumTopicRequest) (bool, error)
Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) EditMessageCaption ¶
func (b *TelegramBot) EditMessageCaption(ctx context.Context, req *EditMessageCaptionRequest) (*Message, error)
Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
func (*TelegramBot) EditMessageChecklist ¶
func (b *TelegramBot) EditMessageChecklist(ctx context.Context, req *EditMessageChecklistRequest) (*Message, error)
Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned.
On success, the edited Message is returned.
func (*TelegramBot) EditMessageLiveLocation ¶
func (b *TelegramBot) EditMessageLiveLocation(ctx context.Context, req *EditMessageLiveLocationRequest) (*Message, error)
Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
func (*TelegramBot) EditMessageMedia ¶
func (b *TelegramBot) EditMessageMedia(ctx context.Context, req *EditMessageMediaRequest) (*Message, error)
Use this method to edit animation, audio, document, live photo, photo, or video messages, or to replace a text or a rich message with a media. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo, a live photo, or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
func (*TelegramBot) EditMessageReplyMarkup ¶
func (b *TelegramBot) EditMessageReplyMarkup(ctx context.Context, req *EditMessageReplyMarkupRequest) (*Message, error)
Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
func (*TelegramBot) EditMessageText ¶
func (b *TelegramBot) EditMessageText(ctx context.Context, req *EditMessageTextRequest) (*Message, error)
Use this method to edit text, rich and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
func (*TelegramBot) EditStory ¶
func (b *TelegramBot) EditStory(ctx context.Context, req *EditStoryRequest) (*Story, error)
Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.
Returns Story on success.
func (*TelegramBot) EditUserStarSubscription ¶
func (b *TelegramBot) EditUserStarSubscription(ctx context.Context, req *EditUserStarSubscriptionRequest) (bool, error)
Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success.
Returns True on success.
func (*TelegramBot) ExportChatInviteLink ¶
func (b *TelegramBot) ExportChatInviteLink(ctx context.Context, req *ExportChatInviteLinkRequest) (string, error)
Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.
Returns the new invite link as String on success.
func (*TelegramBot) ForwardMessage ¶
func (b *TelegramBot) ForwardMessage(ctx context.Context, req *ForwardMessageRequest) (*Message, error)
Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) ForwardMessages ¶
func (b *TelegramBot) ForwardMessages(ctx context.Context, req *ForwardMessagesRequest) ([]MessageID, error)
Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.
On success, an array of MessageId of the sent messages is returned.
func (*TelegramBot) GetAvailableGifts ¶
func (b *TelegramBot) GetAvailableGifts(ctx context.Context) (*Gifts, error)
Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object.
Returns the list of gifts that can be sent by the bot to users and channel chats. Returns a Gifts object.
func (*TelegramBot) GetBusinessAccountGifts ¶
func (b *TelegramBot) GetBusinessAccountGifts(ctx context.Context, req *GetBusinessAccountGiftsRequest) (*OwnedGifts, error)
Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success.
Returns the gifts received and owned by a managed business account. Returns OwnedGifts on success.
func (*TelegramBot) GetBusinessAccountStarBalance ¶
func (b *TelegramBot) GetBusinessAccountStarBalance(ctx context.Context, req *GetBusinessAccountStarBalanceRequest) (*StarAmount, error)
Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success.
Returns the amount of Telegram Stars owned by a managed business account. Returns StarAmount on success.
func (*TelegramBot) GetBusinessConnection ¶
func (b *TelegramBot) GetBusinessConnection(ctx context.Context, req *GetBusinessConnectionRequest) (*BusinessConnection, error)
Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success.
Returns a BusinessConnection object on success.
func (*TelegramBot) GetChat ¶
func (b *TelegramBot) GetChat(ctx context.Context, req *GetChatRequest) (*ChatFullInfo, error)
Use this method to get up-to-date information about the chat. Returns a ChatFullInfo object on success.
Returns a ChatFullInfo object on success.
func (*TelegramBot) GetChatAdministrators ¶
func (b *TelegramBot) GetChatAdministrators(ctx context.Context, req *GetChatAdministratorsRequest) ([]ChatMember, error)
Use this method to get a list of administrators in a chat. Returns an Array of ChatMember objects.
Returns an Array of ChatMember objects.
func (*TelegramBot) GetChatGifts ¶
func (b *TelegramBot) GetChatGifts(ctx context.Context, req *GetChatGiftsRequest) (*OwnedGifts, error)
Returns the gifts owned by a chat. Returns OwnedGifts on success.
Returns the gifts owned by a chat. Returns OwnedGifts on success.
func (*TelegramBot) GetChatMember ¶
func (b *TelegramBot) GetChatMember(ctx context.Context, req *GetChatMemberRequest) (ChatMember, error)
Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success.
Returns a ChatMember object on success.
func (*TelegramBot) GetChatMemberCount ¶
func (b *TelegramBot) GetChatMemberCount(ctx context.Context, req *GetChatMemberCountRequest) (int64, error)
Use this method to get the number of members in a chat. Returns Int on success.
Returns Int on success.
func (*TelegramBot) GetChatMenuButton ¶
func (b *TelegramBot) GetChatMenuButton(ctx context.Context, req *GetChatMenuButtonRequest) (MenuButton, error)
Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
Returns MenuButton on success.
func (*TelegramBot) GetCustomEmojiStickers ¶
func (b *TelegramBot) GetCustomEmojiStickers(ctx context.Context, req *GetCustomEmojiStickersRequest) ([]Sticker, error)
Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
Returns an Array of Sticker objects.
func (*TelegramBot) GetFile ¶
func (b *TelegramBot) GetFile(ctx context.Context, req *GetFileRequest) (*File, error)
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. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
On success, a File object is returned.
func (*TelegramBot) GetForumTopicIconStickers ¶
func (b *TelegramBot) GetForumTopicIconStickers(ctx context.Context) ([]Sticker, error)
Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects.
Returns an Array of Sticker objects.
func (*TelegramBot) GetGameHighScores ¶
func (b *TelegramBot) GetGameHighScores(ctx context.Context, req *GetGameHighScoresRequest) ([]GameHighScore, error)
Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects. This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change.
Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects. This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them.
func (*TelegramBot) GetHealthMonitor ¶
func (b *TelegramBot) GetHealthMonitor() *HealthMonitor
GetHealthMonitor returns the bot's HealthMonitor, for reading dispatch counters directly instead of (or in addition to) the HTTP endpoint started by TelegramBot.StartHealthServer.
func (*TelegramBot) GetManagedBotAccessSettings ¶
func (b *TelegramBot) GetManagedBotAccessSettings(ctx context.Context, req *GetManagedBotAccessSettingsRequest) (*BotAccessSettings, error)
Use this method to get the access settings of a managed bot. Returns a BotAccessSettings object on success.
Returns a BotAccessSettings object on success.
func (*TelegramBot) GetManagedBotToken ¶
func (b *TelegramBot) GetManagedBotToken(ctx context.Context, req *GetManagedBotTokenRequest) (string, error)
Use this method to get the token of a managed bot. Returns the token as String on success.
Returns the token as String on success.
func (*TelegramBot) GetMe ¶
func (b *TelegramBot) GetMe(ctx context.Context) (*User, error)
A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.
Returns basic information about the bot in form of a User object.
func (*TelegramBot) GetMyCommands ¶
func (b *TelegramBot) GetMyCommands(ctx context.Context, req *GetMyCommandsRequest) ([]BotCommand, error)
Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.
Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.
func (*TelegramBot) GetMyDefaultAdministratorRights ¶
func (b *TelegramBot) GetMyDefaultAdministratorRights(ctx context.Context, req *GetMyDefaultAdministratorRightsRequest) (*ChatAdministratorRights, error)
Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
Returns ChatAdministratorRights on success.
func (*TelegramBot) GetMyDescription ¶
func (b *TelegramBot) GetMyDescription(ctx context.Context, req *GetMyDescriptionRequest) (*BotDescription, error)
Use this method to get the current bot description for the given user language. Returns BotDescription on success.
Returns BotDescription on success.
func (*TelegramBot) GetMyName ¶
func (b *TelegramBot) GetMyName(ctx context.Context, req *GetMyNameRequest) (*BotName, error)
Use this method to get the current bot name for the given user language. Returns BotName on success.
Returns BotName on success.
func (*TelegramBot) GetMyShortDescription ¶
func (b *TelegramBot) GetMyShortDescription(ctx context.Context, req *GetMyShortDescriptionRequest) (*BotShortDescription, error)
Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success.
Returns BotShortDescription on success.
func (*TelegramBot) GetMyStarBalance ¶
func (b *TelegramBot) GetMyStarBalance(ctx context.Context) (*StarAmount, error)
A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object.
On success, returns a StarAmount object.
func (*TelegramBot) GetStarTransactions ¶
func (b *TelegramBot) GetStarTransactions(ctx context.Context, req *GetStarTransactionsRequest) (*StarTransactions, error)
Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object.
Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object.
func (*TelegramBot) GetStickerSet ¶
func (b *TelegramBot) GetStickerSet(ctx context.Context, req *GetStickerSetRequest) (*StickerSet, error)
Use this method to get a sticker set. On success, a StickerSet object is returned.
On success, a StickerSet object is returned.
func (*TelegramBot) GetUpdates ¶
func (b *TelegramBot) GetUpdates(ctx context.Context, req *GetUpdatesRequest) ([]Update, error)
Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.
Returns an Array of Update objects.
func (*TelegramBot) GetUserChatBoosts ¶
func (b *TelegramBot) GetUserChatBoosts(ctx context.Context, req *GetUserChatBoostsRequest) (*UserChatBoosts, error)
Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.
Returns a UserChatBoosts object.
func (*TelegramBot) GetUserGifts ¶
func (b *TelegramBot) GetUserGifts(ctx context.Context, req *GetUserGiftsRequest) (*OwnedGifts, error)
Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.
Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.
func (*TelegramBot) GetUserPersonalChatMessages ¶
func (b *TelegramBot) GetUserPersonalChatMessages(ctx context.Context, req *GetUserPersonalChatMessagesRequest) ([]Message, error)
Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user. On success, an array of Message objects is returned.
On success, an array of Message objects is returned.
func (*TelegramBot) GetUserProfileAudios ¶
func (b *TelegramBot) GetUserProfileAudios(ctx context.Context, req *GetUserProfileAudiosRequest) (*UserProfileAudios, error)
Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object.
Returns a UserProfileAudios object.
func (*TelegramBot) GetUserProfilePhotos ¶
func (b *TelegramBot) GetUserProfilePhotos(ctx context.Context, req *GetUserProfilePhotosRequest) (*UserProfilePhotos, error)
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
Returns a UserProfilePhotos object.
func (*TelegramBot) GetWebhookInfo ¶
func (b *TelegramBot) GetWebhookInfo(ctx context.Context) (*WebhookInfo, error)
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
func (*TelegramBot) GiftPremiumSubscription ¶
func (b *TelegramBot) GiftPremiumSubscription(ctx context.Context, req *GiftPremiumSubscriptionRequest) (bool, error)
Gifts a Telegram Premium subscription to the given user. Returns True on success.
Returns True on success.
func (*TelegramBot) HandleUpdate ¶
func (b *TelegramBot) HandleUpdate(ctx context.Context, u *Update)
HandleUpdate synchronously dispatches u through the configured router, exactly as the polling and webhook workers do internally — without requiring StartWorkers, Run, or RunWebhook. This is the entrypoint for testing a bot: build an *Update by hand, or with the golagramtest package's factories, and pass it here directly. Call TelegramBot.Dispatch to attach a router first — with no router attached, HandleUpdate is a no-op that still counts the update as unmatched.
func (*TelegramBot) Handler ¶
func (b *TelegramBot) Handler(cfg WebhookConfig) http.Handler
Handler returns an http.Handler that verifies cfg.SecretToken and feeds incoming updates into the same dispatch() (and the same worker pool, started by TelegramBot.RunWebhook) that polling uses — for embedding into an existing server/mux (echo/chi/stdlib) instead of letting RunWebhook own the listener. If you use this directly instead of RunWebhook, you're responsible for calling TelegramBot.SetWebhook yourself and for the worker pool: TelegramBot.StartWorkers before serving, TelegramBot.StopWorkers on shutdown.
func (*TelegramBot) HideGeneralForumTopic ¶
func (b *TelegramBot) HideGeneralForumTopic(ctx context.Context, req *HideGeneralForumTopicRequest) (bool, error)
Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success.
Returns True on success.
func (*TelegramBot) LeaveChat ¶
func (b *TelegramBot) LeaveChat(ctx context.Context, req *LeaveChatRequest) (bool, error)
Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
Returns True on success.
func (*TelegramBot) LoadMe ¶
func (b *TelegramBot) LoadMe(ctx context.Context) error
LoadMe calls getMe and replaces TelegramBot.Me with the result, including Username. Only needed for a bot constructed with WithoutGetMe that turns out to need /cmd@bot mention matching (see FilterCommand) or username-based deep links after all — call it once, any time before those features are exercised.
func (*TelegramBot) LogOut ¶
func (b *TelegramBot) LogOut(ctx context.Context) (bool, error)
Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters.
Returns True on success.
func (*TelegramBot) Me ¶
func (b *TelegramBot) Me() *User
Me returns the bot's own user info: the full result of getMe, or — if this bot was constructed with WithoutGetMe and TelegramBot.LoadMe hasn't been called since — just the ID derived from the token, with Username empty.
func (*TelegramBot) OnError ¶
func (b *TelegramBot) OnError(handler ErrorHandlerFunc)
OnError sets the bot-wide fallback for errors a handler returns (or a recovered handler panic) that no router-level Router.OnError already handled. Without one set, such errors are just logged.
func (*TelegramBot) OnShutdown ¶
func (b *TelegramBot) OnShutdown(f LifecycleFunc)
OnShutdown registers a hook to run once, in registration order, after Run/RunWebhook has stopped accepting new updates and every in-flight handler has finished — e.g. closing a database connection. A hook's error is logged, not fatal: by the time these run the bot is already shutting down, so there's nothing left to abort, and one hook failing shouldn't skip the others' cleanup.
func (*TelegramBot) OnStartup ¶
func (b *TelegramBot) OnStartup(f LifecycleFunc)
OnStartup registers a hook to run once, in registration order, before Run or RunWebhook starts dispatching updates — e.g. connecting to a database, warming a cache. If any hook returns an error, Run/RunWebhook aborts immediately (no workers started, no polling/serving) and returns that error wrapped.
func (*TelegramBot) PinChatMessage ¶
func (b *TelegramBot) PinChatMessage(ctx context.Context, req *PinChatMessageRequest) (bool, error)
Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success.
Returns True on success.
func (*TelegramBot) PostStory ¶
func (b *TelegramBot) PostStory(ctx context.Context, req *PostStoryRequest) (*Story, error)
Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.
Returns Story on success.
func (*TelegramBot) PromoteChatMember ¶
func (b *TelegramBot) PromoteChatMember(ctx context.Context, req *PromoteChatMemberRequest) (bool, error)
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.
Returns True on success.
func (*TelegramBot) ReadBusinessMessage ¶
func (b *TelegramBot) ReadBusinessMessage(ctx context.Context, req *ReadBusinessMessageRequest) (bool, error)
Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) RefundStarPayment ¶
func (b *TelegramBot) RefundStarPayment(ctx context.Context, req *RefundStarPaymentRequest) (bool, error)
Refunds a successful payment in Telegram Stars. Returns True on success.
Returns True on success.
func (*TelegramBot) RefundStars ¶
func (b *TelegramBot) RefundStars(ctx context.Context, userID int64, telegramPaymentChargeID string) error
RefundStars refunds a completed Telegram Stars payment. The charge ID comes from SuccessfulPayment.TelegramPaymentChargeID — persist it at payment time; it's the only handle for a later refund.
func (*TelegramBot) RemoveBusinessAccountProfilePhoto ¶
func (b *TelegramBot) RemoveBusinessAccountProfilePhoto(ctx context.Context, req *RemoveBusinessAccountProfilePhotoRequest) (bool, error)
Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) RemoveChatVerification ¶
func (b *TelegramBot) RemoveChatVerification(ctx context.Context, req *RemoveChatVerificationRequest) (bool, error)
Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) RemoveMyProfilePhoto ¶
func (b *TelegramBot) RemoveMyProfilePhoto(ctx context.Context) (bool, error)
Removes the profile photo of the bot. Requires no parameters. Returns True on success.
Returns True on success.
func (*TelegramBot) RemoveUserVerification ¶
func (b *TelegramBot) RemoveUserVerification(ctx context.Context, req *RemoveUserVerificationRequest) (bool, error)
Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) ReopenForumTopic ¶
func (b *TelegramBot) ReopenForumTopic(ctx context.Context, req *ReopenForumTopicRequest) (bool, error)
Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
Returns True on success.
func (*TelegramBot) ReopenGeneralForumTopic ¶
func (b *TelegramBot) ReopenGeneralForumTopic(ctx context.Context, req *ReopenGeneralForumTopicRequest) (bool, error)
Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success.
Returns True on success.
func (*TelegramBot) ReplaceManagedBotToken ¶
func (b *TelegramBot) ReplaceManagedBotToken(ctx context.Context, req *ReplaceManagedBotTokenRequest) (string, error)
Use this method to revoke the current token of a managed bot and generate a new one. Returns the new token as String on success.
Returns the new token as String on success.
func (*TelegramBot) ReplaceStickerInSet ¶
func (b *TelegramBot) ReplaceStickerInSet(ctx context.Context, req *ReplaceStickerInSetRequest) (bool, error)
Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns True on success.
Returns True on success.
func (*TelegramBot) RepostStory ¶
func (b *TelegramBot) RepostStory(ctx context.Context, req *RepostStoryRequest) (*Story, error)
Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success.
Returns Story on success.
func (*TelegramBot) RestrictChatMember ¶
func (b *TelegramBot) RestrictChatMember(ctx context.Context, req *RestrictChatMemberRequest) (bool, error)
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
Returns True on success.
func (*TelegramBot) RevokeChatInviteLink ¶
func (b *TelegramBot) RevokeChatInviteLink(ctx context.Context, req *RevokeChatInviteLinkRequest) (*ChatInviteLink, error)
Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.
Returns the revoked invite link as ChatInviteLink object.
func (*TelegramBot) Run ¶
func (b *TelegramBot) Run(ctx context.Context) error
Run starts long-polling getUpdates and dispatches every update through the router set by TelegramBot.Dispatch, blocking until ctx is canceled or a startup hook (see TelegramBot.OnStartup) returns an error. On a getUpdates failure it retries with exponential backoff instead of returning — a canceled ctx is the only case Run returns from, and it returns nil for that, not ctx.Err(). Shutdown drains every in-flight handler (see TelegramBot.StopWorkers) and runs shutdown hooks (see TelegramBot.OnShutdown) before returning. One-shot, like RunWebhook and StartWorkers (see TelegramBot) — calling Run again after a previous Run/RunWebhook/StartWorkers has returned returns errAlreadyRan instead of polling.
func (*TelegramBot) RunWebhook ¶
func (b *TelegramBot) RunWebhook(ctx context.Context, cfg WebhookConfig) error
RunWebhook runs the bot in webhook mode: calls TelegramBot.SetWebhook, starts the same worker pool TelegramBot.Run (polling) uses, and serves cfg.Path until ctx is canceled, then drains in-flight handlers before returning — the same shutdown shape as Run. Handlers registered via TelegramBot.Dispatch are unaffected by which runtime mode delivers their updates. One-shot, like Run and StartWorkers (see TelegramBot) — calling RunWebhook again after a previous Run/RunWebhook/StartWorkers has returned returns errAlreadyRan instead of serving.
func (*TelegramBot) SavePreparedInlineMessage ¶
func (b *TelegramBot) SavePreparedInlineMessage(ctx context.Context, req *SavePreparedInlineMessageRequest) (*PreparedInlineMessage, error)
Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object.
Returns a PreparedInlineMessage object.
func (*TelegramBot) SavePreparedKeyboardButton ¶
func (b *TelegramBot) SavePreparedKeyboardButton(ctx context.Context, req *SavePreparedKeyboardButtonRequest) (*PreparedKeyboardButton, error)
Stores a keyboard button that can be used by a user within a Mini App. Returns a PreparedKeyboardButton object.
Returns a PreparedKeyboardButton object.
func (*TelegramBot) SendAnimation ¶
func (b *TelegramBot) SendAnimation(ctx context.Context, req *SendAnimationRequest) (*Message, error)
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
On success, the sent Message is returned.
func (*TelegramBot) SendAudio ¶
func (b *TelegramBot) SendAudio(ctx context.Context, req *SendAudioRequest) (*Message, error)
Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. For sending voice messages, use the sendVoice method instead.
On success, the sent Message is returned.
func (*TelegramBot) SendChatAction ¶
func (b *TelegramBot) SendChatAction(ctx context.Context, req *SendChatActionRequest) (bool, error)
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot. We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
Returns True on success.
func (*TelegramBot) SendChatJoinRequestWebApp ¶
func (b *TelegramBot) SendChatJoinRequestWebApp(ctx context.Context, req *SendChatJoinRequestWebAppRequest) (bool, error)
Use this method to process a received chat join request query by showing a Mini App to the user before deciding the outcome. Call answerChatJoinRequestQuery to resolve the join request query based on the user interaction with the Mini App. Returns True on success.
Returns True on success.
func (*TelegramBot) SendChecklist ¶
func (b *TelegramBot) SendChecklist(ctx context.Context, req *SendChecklistRequest) (*Message, error)
Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendContact ¶
func (b *TelegramBot) SendContact(ctx context.Context, req *SendContactRequest) (*Message, error)
Use this method to send phone contacts. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendDice ¶
func (b *TelegramBot) SendDice(ctx context.Context, req *SendDiceRequest) (*Message, error)
Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendDocument ¶
func (b *TelegramBot) SendDocument(ctx context.Context, req *SendDocumentRequest) (*Message, error)
Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
On success, the sent Message is returned.
func (*TelegramBot) SendGame ¶
func (b *TelegramBot) SendGame(ctx context.Context, req *SendGameRequest) (*Message, error)
Use this method to send a game. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendGift ¶
func (b *TelegramBot) SendGift(ctx context.Context, req *SendGiftRequest) (bool, error)
Sends a gift to the given user or channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.
Returns True on success.
func (*TelegramBot) SendInvoice ¶
func (b *TelegramBot) SendInvoice(ctx context.Context, req *SendInvoiceRequest) (*Message, error)
Use this method to send invoices. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendLivePhoto ¶
func (b *TelegramBot) SendLivePhoto(ctx context.Context, req *SendLivePhotoRequest) (*Message, error)
Use this method to send live photos. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendLocation ¶
func (b *TelegramBot) SendLocation(ctx context.Context, req *SendLocationRequest) (*Message, error)
Use this method to send point on the map. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendMediaGroup ¶
func (b *TelegramBot) SendMediaGroup(ctx context.Context, req *SendMediaGroupRequest) ([]Message, error)
Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Message objects that were sent is returned.
On success, an array of Message objects that were sent is returned.
func (*TelegramBot) SendMessage ¶
func (b *TelegramBot) SendMessage(ctx context.Context, req *SendMessageRequest) (*Message, error)
Use this method to send text messages. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendMessageDraft ¶
func (b *TelegramBot) SendMessageDraft(ctx context.Context, req *SendMessageDraftRequest) (bool, error)
Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendMessage with the complete message to persist it in the user's chat. Returns True on success.
Returns True on success.
func (*TelegramBot) SendPaidMedia ¶
func (b *TelegramBot) SendPaidMedia(ctx context.Context, req *SendPaidMediaRequest) (*Message, error)
Use this method to send paid media. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendPhoto ¶
func (b *TelegramBot) SendPhoto(ctx context.Context, req *SendPhotoRequest) (*Message, error)
Use this method to send photos. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendPoll ¶
func (b *TelegramBot) SendPoll(ctx context.Context, req *SendPollRequest) (*Message, error)
Use this method to send a native poll. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendRichMessage ¶
func (b *TelegramBot) SendRichMessage(ctx context.Context, req *SendRichMessageRequest) (*Message, error)
Use this method to send rich messages. If the message contains a block with a media element, then the bot must have the right to send the media to the chat. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendRichMessageDraft ¶
func (b *TelegramBot) SendRichMessageDraft(ctx context.Context, req *SendRichMessageDraftRequest) (bool, error)
Use this method to stream a partial rich message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendRichMessage with the complete message to persist it in the user's chat. Returns True on success.
Returns True on success.
func (*TelegramBot) SendSticker ¶
func (b *TelegramBot) SendSticker(ctx context.Context, req *SendStickerRequest) (*Message, error)
Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendVenue ¶
func (b *TelegramBot) SendVenue(ctx context.Context, req *SendVenueRequest) (*Message, error)
Use this method to send information about a venue. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendVideo ¶
func (b *TelegramBot) SendVideo(ctx context.Context, req *SendVideoRequest) (*Message, error)
Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
On success, the sent Message is returned.
func (*TelegramBot) SendVideoNote ¶
func (b *TelegramBot) SendVideoNote(ctx context.Context, req *SendVideoNoteRequest) (*Message, error)
As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
On success, the sent Message is returned.
func (*TelegramBot) SendVoice ¶
func (b *TelegramBot) SendVoice(ctx context.Context, req *SendVoiceRequest) (*Message, error)
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
On success, the sent Message is returned.
func (*TelegramBot) SetBotCommands ¶
func (b *TelegramBot) SetBotCommands(commands []BotCommand) error
SetBotCommands sets the bot's command menu for the default scope. For a specific scope or language, use the generated TelegramBot.SetMyCommands with SetMyCommandsRequest.Scope / SetMyCommandsRequest.LanguageCode.
func (*TelegramBot) SetBusinessAccountBio ¶
func (b *TelegramBot) SetBusinessAccountBio(ctx context.Context, req *SetBusinessAccountBioRequest) (bool, error)
Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) SetBusinessAccountGiftSettings ¶
func (b *TelegramBot) SetBusinessAccountGiftSettings(ctx context.Context, req *SetBusinessAccountGiftSettingsRequest) (bool, error)
Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) SetBusinessAccountName ¶
func (b *TelegramBot) SetBusinessAccountName(ctx context.Context, req *SetBusinessAccountNameRequest) (bool, error)
Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) SetBusinessAccountProfilePhoto ¶
func (b *TelegramBot) SetBusinessAccountProfilePhoto(ctx context.Context, req *SetBusinessAccountProfilePhotoRequest) (bool, error)
Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) SetBusinessAccountUsername ¶
func (b *TelegramBot) SetBusinessAccountUsername(ctx context.Context, req *SetBusinessAccountUsernameRequest) (bool, error)
Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatAdministratorCustomTitle ¶
func (b *TelegramBot) SetChatAdministratorCustomTitle(ctx context.Context, req *SetChatAdministratorCustomTitleRequest) (bool, error)
Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatDescription ¶
func (b *TelegramBot) SetChatDescription(ctx context.Context, req *SetChatDescriptionRequest) (bool, error)
Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatMemberTag ¶
func (b *TelegramBot) SetChatMemberTag(ctx context.Context, req *SetChatMemberTagRequest) (bool, error)
Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the can_manage_tags administrator right. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatMenuButton ¶
func (b *TelegramBot) SetChatMenuButton(ctx context.Context, req *SetChatMenuButtonRequest) (bool, error)
Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatPermissions ¶
func (b *TelegramBot) SetChatPermissions(ctx context.Context, req *SetChatPermissionsRequest) (bool, error)
Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatPhoto ¶
func (b *TelegramBot) SetChatPhoto(ctx context.Context, req *SetChatPhotoRequest) (bool, error)
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) SetChatStickerSet ¶
func (b *TelegramBot) SetChatStickerSet(ctx context.Context, req *SetChatStickerSetRequest) (bool, error)
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
func (*TelegramBot) SetChatTitle ¶
func (b *TelegramBot) SetChatTitle(ctx context.Context, req *SetChatTitleRequest) (bool, error)
Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) SetCustomEmojiStickerSetThumbnail ¶
func (b *TelegramBot) SetCustomEmojiStickerSetThumbnail(ctx context.Context, req *SetCustomEmojiStickerSetThumbnailRequest) (bool, error)
Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.
Returns True on success.
func (*TelegramBot) SetFSMStorage ¶
func (b *TelegramBot) SetFSMStorage(storage FSMStorage)
SetFSMStorage swaps the conversation-state backend. TelegramBot starts with an in-process MemoryStorage by default; call this before Run to use a persistent FSMStorage instead.
func (*TelegramBot) SetGameScore ¶
func (b *TelegramBot) SetGameScore(ctx context.Context, req *SetGameScoreRequest) (*Message, error)
Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
func (*TelegramBot) SetManagedBotAccessSettings ¶
func (b *TelegramBot) SetManagedBotAccessSettings(ctx context.Context, req *SetManagedBotAccessSettingsRequest) (bool, error)
Use this method to change the access settings of a managed bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMessageReaction ¶
func (b *TelegramBot) SetMessageReaction(ctx context.Context, req *SetMessageReactionRequest) (bool, error)
Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMyCommands ¶
func (b *TelegramBot) SetMyCommands(ctx context.Context, req *SetMyCommandsRequest) (bool, error)
Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMyDefaultAdministratorRights ¶
func (b *TelegramBot) SetMyDefaultAdministratorRights(ctx context.Context, req *SetMyDefaultAdministratorRightsRequest) (bool, error)
Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMyDescription ¶
func (b *TelegramBot) SetMyDescription(ctx context.Context, req *SetMyDescriptionRequest) (bool, error)
Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMyName ¶
func (b *TelegramBot) SetMyName(ctx context.Context, req *SetMyNameRequest) (bool, error)
Use this method to change the bot's name. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMyProfilePhoto ¶
func (b *TelegramBot) SetMyProfilePhoto(ctx context.Context, req *SetMyProfilePhotoRequest) (bool, error)
Changes the profile photo of the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetMyShortDescription ¶
func (b *TelegramBot) SetMyShortDescription(ctx context.Context, req *SetMyShortDescriptionRequest) (bool, error)
Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetPassportDataErrors ¶
func (b *TelegramBot) SetPassportDataErrors(ctx context.Context, req *SetPassportDataErrorsRequest) (bool, error)
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
func (*TelegramBot) SetStickerEmojiList ¶
func (b *TelegramBot) SetStickerEmojiList(ctx context.Context, req *SetStickerEmojiListRequest) (bool, error)
Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetStickerKeywords ¶
func (b *TelegramBot) SetStickerKeywords(ctx context.Context, req *SetStickerKeywordsRequest) (bool, error)
Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetStickerMaskPosition ¶
func (b *TelegramBot) SetStickerMaskPosition(ctx context.Context, req *SetStickerMaskPositionRequest) (bool, error)
Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) SetStickerPositionInSet ¶
func (b *TelegramBot) SetStickerPositionInSet(ctx context.Context, req *SetStickerPositionInSetRequest) (bool, error)
Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
Returns True on success.
func (*TelegramBot) SetStickerSetThumbnail ¶
func (b *TelegramBot) SetStickerSetThumbnail(ctx context.Context, req *SetStickerSetThumbnailRequest) (bool, error)
Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success.
Returns True on success.
func (*TelegramBot) SetStickerSetTitle ¶
func (b *TelegramBot) SetStickerSetTitle(ctx context.Context, req *SetStickerSetTitleRequest) (bool, error)
Use this method to set the title of a created sticker set. Returns True on success.
Returns True on success.
func (*TelegramBot) SetUserEmojiStatus ¶
func (b *TelegramBot) SetUserEmojiStatus(ctx context.Context, req *SetUserEmojiStatusRequest) (bool, error)
Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success.
Returns True on success.
func (*TelegramBot) SetWebhook ¶
func (b *TelegramBot) SetWebhook(ctx context.Context, req *SetWebhookRequest) (bool, error)
Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request (a request with response HTTP status code different from 2XY), we will repeat the request and give up after a reasonable amount of attempts. Returns True on success. If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.
Returns True on success.
func (*TelegramBot) StartHealthServer ¶
func (b *TelegramBot) StartHealthServer(ctx context.Context, addr string, gate ...HealthGate)
StartHealthServer starts the health check HTTP server in a goroutine. The server shuts down when ctx is canceled — tie it to the same context as Run so it dies with the bot instead of reporting health for a corpse.
/health and /healthz serve unauthenticated by default — fine on a private network, a footgun if addr ends up reachable from the public internet (LastError often contains chat/user IDs or upstream error text). Bind to localhost, put auth in front, or pass a HealthGate to reject requests that don't pass it (responds 403 instead of serving the status).
func (*TelegramBot) StartWorkers ¶
func (b *TelegramBot) StartWorkers(ctx context.Context)
StartWorkers starts the update-processing worker pool without either runtime — for embedding Handler(cfg) into your own HTTP server/mux instead of letting RunWebhook own the listener. You're still responsible for calling SetWebhook yourself; call StopWorkers on shutdown to drain in-flight handlers. Bots using Run or RunWebhook never need this.
One-shot, like Run/RunWebhook (see TelegramBot): calling it again after StopWorkers has run is a no-op, logged as an error, rather than a panic.
func (*TelegramBot) StopMessageLiveLocation ¶
func (b *TelegramBot) StopMessageLiveLocation(ctx context.Context, req *StopMessageLiveLocationRequest) (*Message, error)
Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
func (*TelegramBot) StopPoll ¶
func (b *TelegramBot) StopPoll(ctx context.Context, req *StopPollRequest) (*Poll, error)
Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.
On success, the stopped Poll is returned.
func (*TelegramBot) StopWorkers ¶
func (b *TelegramBot) StopWorkers()
StopWorkers stops accepting new updates and blocks until every in-flight handler has finished. Idempotent; called automatically by Run/RunWebhook on shutdown, needed directly only by StartWorkers users.
func (*TelegramBot) TransferBusinessAccountStars ¶
func (b *TelegramBot) TransferBusinessAccountStars(ctx context.Context, req *TransferBusinessAccountStarsRequest) (bool, error)
Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success.
Returns True on success.
func (*TelegramBot) TransferGift ¶
func (b *TelegramBot) TransferGift(ctx context.Context, req *TransferGiftRequest) (bool, error)
Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success.
Returns True on success.
func (*TelegramBot) UnbanChatMember ¶
func (b *TelegramBot) UnbanChatMember(ctx context.Context, req *UnbanChatMemberRequest) (bool, error)
Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.
The user will not return to the group or channel automatically, but will be able to join via link, etc. Returns True on success.
func (*TelegramBot) UnbanChatSenderChat ¶
func (b *TelegramBot) UnbanChatSenderChat(ctx context.Context, req *UnbanChatSenderChatRequest) (bool, error)
Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) UnhideGeneralForumTopic ¶
func (b *TelegramBot) UnhideGeneralForumTopic(ctx context.Context, req *UnhideGeneralForumTopicRequest) (bool, error)
Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
Returns True on success.
func (*TelegramBot) UnpinAllChatMessages ¶
func (b *TelegramBot) UnpinAllChatMessages(ctx context.Context, req *UnpinAllChatMessagesRequest) (bool, error)
Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success.
Returns True on success.
func (*TelegramBot) UnpinAllForumTopicMessages ¶
func (b *TelegramBot) UnpinAllForumTopicMessages(ctx context.Context, req *UnpinAllForumTopicMessagesRequest) (bool, error)
Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
Returns True on success.
func (*TelegramBot) UnpinAllGeneralForumTopicMessages ¶
func (b *TelegramBot) UnpinAllGeneralForumTopicMessages(ctx context.Context, req *UnpinAllGeneralForumTopicMessagesRequest) (bool, error)
Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
Returns True on success.
func (*TelegramBot) UnpinChatMessage ¶
func (b *TelegramBot) UnpinChatMessage(ctx context.Context, req *UnpinChatMessageRequest) (bool, error)
Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success.
Returns True on success.
func (*TelegramBot) UpgradeGift ¶
func (b *TelegramBot) UpgradeGift(ctx context.Context, req *UpgradeGiftRequest) (bool, error)
Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success.
Returns True on success.
func (*TelegramBot) UploadStickerFile ¶
func (b *TelegramBot) UploadStickerFile(ctx context.Context, req *UploadStickerFileRequest) (*File, error)
Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success.
Returns the uploaded File on success.
func (*TelegramBot) VerifyChat ¶
func (b *TelegramBot) VerifyChat(ctx context.Context, req *VerifyChatRequest) (bool, error)
Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.
Returns True on success.
func (*TelegramBot) VerifyUser ¶
func (b *TelegramBot) VerifyUser(ctx context.Context, req *VerifyUserRequest) (bool, error)
Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.
Returns True on success.
type TextChunk ¶
TextChunk is one sendable piece of a long message, as returned by SplitTextWithEntities: the text plus the entities that fall inside it, re-based so they can be passed straight to SendMessageOptions.Entities.
func SplitTextWithEntities ¶
SplitTextWithEntities splits text and its formatting entities into chunks that each fit Telegram's message length limit, without cutting through an entity: a split point that would land inside one (a link, a code block, ...) moves back to the entity's start so the whole entity carries over to the next chunk. Only an entity too long to fit any chunk on its own is split, into one valid entity per chunk — the formatting stays intact on both sides.
Each chunk's entities are clipped and re-based to that chunk, ready for SendMessageOptions.Entities. Offsets, lengths, and the limit are all in UTF-16 code units, matching MessageEntity's wire format.
type TextQuote ¶
type TextQuote struct {
// Text of the quoted part of a message that is replied to by the given message
Text string `json:"text"`
// Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are kept in quotes.
Entities []MessageEntity `json:"entities,omitempty"`
// Approximate quote position in the original message in UTF-16 code units as specified by the sender
Position int64 `json:"position"`
// Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server.
IsManual bool `json:"is_manual,omitempty"`
}
This object contains information about the quoted part of a message that is replied to by the given message.
type TransactionPartner ¶
type TransactionPartner interface {
GetType() string
// contains filtered or unexported methods
}
This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of
type TransactionPartnerAffiliateProgram ¶
type TransactionPartnerAffiliateProgram struct {
// Type of the transaction partner, always “affiliate_program”
Type string `json:"type"`
// Optional. Information about the bot that sponsored the affiliate program
SponsorUser *User `json:"sponsor_user,omitempty"`
// The number of Telegram Stars received by the bot for each 1000 Telegram Stars received by the affiliate program sponsor from referred users
CommissionPerMille int64 `json:"commission_per_mille"`
}
Describes the affiliate program that issued the affiliate commission received via this transaction.
func (*TransactionPartnerAffiliateProgram) GetType ¶
func (v *TransactionPartnerAffiliateProgram) GetType() string
type TransactionPartnerChat ¶
type TransactionPartnerChat struct {
// Type of the transaction partner, always “chat”
Type string `json:"type"`
// Information about the chat
Chat *Chat `json:"chat"`
// Optional. The gift sent to the chat by the bot
Gift *Gift `json:"gift,omitempty"`
}
Describes a transaction with a chat.
func (*TransactionPartnerChat) GetType ¶
func (v *TransactionPartnerChat) GetType() string
type TransactionPartnerFragment ¶
type TransactionPartnerFragment struct {
// Type of the transaction partner, always “fragment”
Type string `json:"type"`
// Optional. State of the transaction if the transaction is outgoing
WithdrawalState RevenueWithdrawalState `json:"withdrawal_state,omitempty"`
}
Describes a withdrawal transaction with Fragment.
func (*TransactionPartnerFragment) GetType ¶
func (v *TransactionPartnerFragment) GetType() string
func (*TransactionPartnerFragment) UnmarshalJSON ¶
func (v *TransactionPartnerFragment) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes TransactionPartnerFragment's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type TransactionPartnerOther ¶
type TransactionPartnerOther struct {
// Type of the transaction partner, always “other”
Type string `json:"type"`
}
Describes a transaction with an unknown source or recipient.
func (*TransactionPartnerOther) GetType ¶
func (v *TransactionPartnerOther) GetType() string
type TransactionPartnerTelegramAds ¶
type TransactionPartnerTelegramAds struct {
// Type of the transaction partner, always “telegram_ads”
Type string `json:"type"`
}
Describes a withdrawal transaction to the Telegram Ads platform.
func (*TransactionPartnerTelegramAds) GetType ¶
func (v *TransactionPartnerTelegramAds) GetType() string
type TransactionPartnerTelegramApi ¶
type TransactionPartnerTelegramApi struct {
// Type of the transaction partner, always “telegram_api”
Type string `json:"type"`
// The number of successful requests that exceeded regular limits and were therefore billed
RequestCount int64 `json:"request_count"`
}
Describes a transaction with payment for paid broadcasting.
func (*TransactionPartnerTelegramApi) GetType ¶
func (v *TransactionPartnerTelegramApi) GetType() string
type TransactionPartnerUser ¶
type TransactionPartnerUser struct {
// Type of the transaction partner, always “user”
Type string `json:"type"`
// Type of the transaction, currently one of “invoice_payment” for payments via invoices, “paid_media_payment” for payments for paid media, “gift_purchase” for gifts sent by the bot, “premium_purchase” for Telegram Premium subscriptions gifted by the bot, “business_account_transfer” for direct transfers from managed business accounts
TransactionType string `json:"transaction_type"`
// Information about the user
User *User `json:"user"`
// Optional. Information about the affiliate that received a commission via this transaction. Can be available only for “invoice_payment” and “paid_media_payment” transactions.
Affiliate *AffiliateInfo `json:"affiliate,omitempty"`
// Optional. Bot-specified invoice payload. Can be available only for “invoice_payment” transactions.
InvoicePayload string `json:"invoice_payload,omitempty"`
// Optional. The duration of the paid subscription. Can be available only for “invoice_payment” transactions.
SubscriptionPeriod int64 `json:"subscription_period,omitempty"`
// Optional. Information about the paid media bought by the user; for “paid_media_payment” transactions only
PaidMedia []PaidMedia `json:"paid_media,omitempty"`
// Optional. Bot-specified paid media payload. Can be available only for “paid_media_payment” transactions.
PaidMediaPayload string `json:"paid_media_payload,omitempty"`
// Optional. The gift sent to the user by the bot; for “gift_purchase” transactions only
Gift *Gift `json:"gift,omitempty"`
// Optional. Number of months the gifted Telegram Premium subscription will be active for; for “premium_purchase” transactions only
PremiumSubscriptionDuration int64 `json:"premium_subscription_duration,omitempty"`
}
Describes a transaction with a user.
func (*TransactionPartnerUser) GetType ¶
func (v *TransactionPartnerUser) GetType() string
The Get* methods below implement TransactionPartner: fields shared by every member, callable on the interface value directly without a type switch.
func (*TransactionPartnerUser) UnmarshalJSON ¶
func (v *TransactionPartnerUser) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes TransactionPartnerUser's union-typed fields polymorphically — encoding/json cannot unmarshal into a bare interface, so each is decoded through its union's discriminator-switching unmarshal function.
type TransferBusinessAccountStarsRequest ¶
type TransferBusinessAccountStarsRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Number of Telegram Stars to transfer; 1-10000
StarCount int64 `json:"star_count"`
}
TransferBusinessAccountStarsRequest holds the parameters for transferBusinessAccountStars.
type TransferGiftRequest ¶
type TransferGiftRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the regular gift that should be transferred
OwnedGiftID string `json:"owned_gift_id"`
// Unique identifier of the chat which will own the gift. The chat must be active in the last 24 hours.
NewOwnerChatID int64 `json:"new_owner_chat_id"`
// The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required.
StarCount int64 `json:"star_count,omitempty"`
}
TransferGiftRequest holds the parameters for transferGift.
type Translator ¶
type Translator interface {
// Translate renders the message for key in the given locale,
// formatting the template with args (fmt.Sprintf) when any are passed.
Translate(locale, key string, args ...any) string
// TranslateN renders the plural form of key selected by n. n picks
// the form only — templates still format from args, so pass n again
// there if the text shows it: TranslateN("en", "apples", 3, 3).
TranslateN(locale, key string, n int, args ...any) string
// DefaultLocale is the locale used when an update carries none.
DefaultLocale() string
}
Translator is what I18nMiddleware carries and Ctx.T / Ctx.TN call. I18n is the built-in map-based implementation; a gettext/go-i18n-backed one can be plugged in from outside, as a separate module, without this package depending on it.
type UnbanChatMemberRequest ¶
type UnbanChatMemberRequest struct {
// Unique identifier for the target group or username of the target supergroup or channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Do nothing if the user is not banned
OnlyIfBanned bool `json:"only_if_banned,omitempty"`
}
UnbanChatMemberRequest holds the parameters for unbanChatMember.
type UnbanChatSenderChatRequest ¶
type UnbanChatSenderChatRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the target sender chat
SenderChatID int64 `json:"sender_chat_id"`
}
UnbanChatSenderChatRequest holds the parameters for unbanChatSenderChat.
type UnhideGeneralForumTopicRequest ¶
type UnhideGeneralForumTopicRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
}
UnhideGeneralForumTopicRequest holds the parameters for unhideGeneralForumTopic.
type UniqueGift ¶
type UniqueGift struct {
// Identifier of the regular gift from which the gift was upgraded
GiftID string `json:"gift_id"`
// Human-readable name of the regular gift from which this unique gift was upgraded
BaseName string `json:"base_name"`
// Unique name of the gift. This name can be used in https://t.me/nft/... links and story areas.
Name string `json:"name"`
// Unique number of the upgraded gift among gifts upgraded from the same regular gift
Number int64 `json:"number"`
// Model of the gift
Model *UniqueGiftModel `json:"model"`
// Symbol of the gift
Symbol *UniqueGiftSymbol `json:"symbol"`
// Backdrop of the gift
Backdrop *UniqueGiftBackdrop `json:"backdrop"`
// Optional. True, if the original regular gift was exclusively purchaseable by Telegram Premium subscribers
IsPremium bool `json:"is_premium,omitempty"`
// Optional. True, if the gift was used to craft another gift and isn't available anymore
IsBurned bool `json:"is_burned,omitempty"`
// Optional. True, if the gift is assigned from the TON blockchain and can't be resold or transferred in Telegram
IsFromBlockchain bool `json:"is_from_blockchain,omitempty"`
// Optional. The color scheme that can be used by the gift's owner for the chat's name, replies to messages and link previews; for business account gifts and gifts that are currently on sale only
Colors *UniqueGiftColors `json:"colors,omitempty"`
// Optional. Information about the chat that published the gift
PublisherChat *Chat `json:"publisher_chat,omitempty"`
}
This object describes a unique gift that was upgraded from a regular gift.
type UniqueGiftBackdrop ¶
type UniqueGiftBackdrop struct {
// Name of the backdrop
Name string `json:"name"`
// Colors of the backdrop
Colors *UniqueGiftBackdropColors `json:"colors"`
// The number of unique gifts that receive this backdrop for every 1000 gifts upgraded
RarityPerMille int64 `json:"rarity_per_mille"`
}
This object describes the backdrop of a unique gift.
type UniqueGiftBackdropColors ¶
type UniqueGiftBackdropColors struct {
// The color in the center of the backdrop in RGB format
CenterColor int64 `json:"center_color"`
// The color on the edges of the backdrop in RGB format
EdgeColor int64 `json:"edge_color"`
// The color to be applied to the symbol in RGB format
SymbolColor int64 `json:"symbol_color"`
// The color for the text on the backdrop in RGB format
TextColor int64 `json:"text_color"`
}
This object describes the colors of the backdrop of a unique gift.
type UniqueGiftColors ¶
type UniqueGiftColors struct {
// Custom emoji identifier of the unique gift's model
ModelCustomEmojiID string `json:"model_custom_emoji_id"`
// Custom emoji identifier of the unique gift's symbol
SymbolCustomEmojiID string `json:"symbol_custom_emoji_id"`
// Main color used in light themes; RGB format
LightThemeMainColor int64 `json:"light_theme_main_color"`
// List of 1-3 additional colors used in light themes; RGB format
LightThemeOtherColors []int64 `json:"light_theme_other_colors"`
// Main color used in dark themes; RGB format
DarkThemeMainColor int64 `json:"dark_theme_main_color"`
// List of 1-3 additional colors used in dark themes; RGB format
DarkThemeOtherColors []int64 `json:"dark_theme_other_colors"`
}
This object contains information about the color scheme for a user's name, message replies and link previews based on a unique gift.
type UniqueGiftInfo ¶
type UniqueGiftInfo struct {
// Information about the gift
Gift *UniqueGift `json:"gift"`
// Origin of the gift. Currently, either “upgrade” for gifts upgraded from regular gifts, “transfer” for gifts transferred from other users or channels, “resale” for gifts bought from other users, “gifted_upgrade” for upgrades purchased after the gift was sent, or “offer” for gifts bought or sold through gift purchase offers.
Origin string `json:"origin"`
// Optional. For gifts bought from other users, the currency in which the payment for the gift was done. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins.
LastResaleCurrency string `json:"last_resale_currency,omitempty"`
// Optional. For gifts bought from other users, the price paid for the gift in either Telegram Stars or nanotoncoins
LastResaleAmount int64 `json:"last_resale_amount,omitempty"`
// Optional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts
OwnedGiftID string `json:"owned_gift_id,omitempty"`
// Optional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift
TransferStarCount int64 `json:"transfer_star_count,omitempty"`
// Optional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now.
NextTransferDate int64 `json:"next_transfer_date,omitempty"`
}
Describes a service message about a unique gift that was sent or received.
type UniqueGiftModel ¶
type UniqueGiftModel struct {
// Name of the model
Name string `json:"name"`
// The sticker that represents the unique gift
Sticker *Sticker `json:"sticker"`
// The number of unique gifts that receive this model for every 1000 gift upgrades. Always 0 for crafted gifts.
RarityPerMille int64 `json:"rarity_per_mille"`
// Optional. Rarity of the model if it is a crafted model. Currently, can be “uncommon”, “rare”, “epic”, or “legendary”.
Rarity string `json:"rarity,omitempty"`
}
This object describes the model of a unique gift.
type UniqueGiftSymbol ¶
type UniqueGiftSymbol struct {
// Name of the symbol
Name string `json:"name"`
// The sticker that represents the unique gift
Sticker *Sticker `json:"sticker"`
// The number of unique gifts that receive this model for every 1000 gifts upgraded
RarityPerMille int64 `json:"rarity_per_mille"`
}
This object describes the symbol shown on the pattern of a unique gift.
type UnpinAllChatMessagesRequest ¶
type UnpinAllChatMessagesRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
}
UnpinAllChatMessagesRequest holds the parameters for unpinAllChatMessages.
type UnpinAllForumTopicMessagesRequest ¶
type UnpinAllForumTopicMessagesRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier for the target message thread of the forum topic
MessageThreadID int64 `json:"message_thread_id"`
}
UnpinAllForumTopicMessagesRequest holds the parameters for unpinAllForumTopicMessages.
type UnpinAllGeneralForumTopicMessagesRequest ¶
type UnpinAllGeneralForumTopicMessagesRequest struct {
// Unique identifier for the target chat or username of the target supergroup in the format @username
ChatID ChatID `json:"chat_id"`
}
UnpinAllGeneralForumTopicMessagesRequest holds the parameters for unpinAllGeneralForumTopicMessages.
type UnpinChatMessageRequest ¶
type UnpinChatMessageRequest struct {
// Unique identifier for the target chat or username of the target channel in the format @username
ChatID ChatID `json:"chat_id"`
// Unique identifier of the business connection on behalf of which the message will be unpinned
BusinessConnectionID string `json:"business_connection_id,omitempty"`
// Identifier of the message to unpin. Required if business_connection_id is specified. If not specified, the most recent pinned message (by sending date) will be unpinned.
MessageID int64 `json:"message_id,omitempty"`
}
UnpinChatMessageRequest holds the parameters for unpinChatMessage.
type Update ¶
type Update struct {
// UpdateID is Telegram's own sequential identifier for this update —
// the value to resume getUpdates from (see [WithDropPendingUpdates]
// and the offset parameter it drives).
UpdateID int64 `json:"update_id"`
// Message is set for a new incoming message of any kind — text,
// photo, sticker, etc. See [Router.Message].
Message *Message `json:"message,omitempty"`
// EditedMessage is set when a known message was edited.
// See [Router.EditedMessage].
EditedMessage *Message `json:"edited_message,omitempty"`
// ChannelPost is set for a new post in a channel the bot can read.
// See [Router.ChannelPost].
ChannelPost *Message `json:"channel_post,omitempty"`
// EditedChannelPost is set when a channel post was edited.
// See [Router.EditedChannelPost].
EditedChannelPost *Message `json:"edited_channel_post,omitempty"`
// BusinessConnection is set when the bot was connected to or
// disconnected from a Telegram Business account, or the connection
// was edited. See [Router.BusinessConnection].
BusinessConnection *BusinessConnection `json:"business_connection,omitempty"`
// BusinessMessage is set for a new message received through a
// connected business account. See [Router.BusinessMessage].
BusinessMessage *Message `json:"business_message,omitempty"`
// EditedBusinessMessage is set when a business-account message was
// edited. See [Router.EditedBusinessMessage].
EditedBusinessMessage *Message `json:"edited_business_message,omitempty"`
// DeletedBusinessMessages is set when messages were deleted from a
// connected business account. See [Router.DeletedBusinessMessages].
DeletedBusinessMessages *BusinessMessagesDeleted `json:"deleted_business_messages,omitempty"`
// GuestMessage is set for a new guest message; reply via
// Message.guest_query_id and answerGuestQuery. See [Router.GuestMessage].
GuestMessage *Message `json:"guest_message,omitempty"`
// MessageReaction is set when a user's reaction to a message changed
// — requires the bot to be a chat admin and message_reaction to be in
// allowed_updates; never fires for reactions set by other bots. See
// [Router.MessageReaction].
MessageReaction *MessageReactionUpdated `json:"message_reaction,omitempty"`
// MessageReactionCount is set when anonymous reactions to a message
// changed — same admin/allowed_updates requirement as
// MessageReaction, but grouped and delivered with up to a few
// minutes' delay. See [Router.MessageReactionCount].
MessageReactionCount *MessageReactionCountUpdated `json:"message_reaction_count,omitempty"`
// InlineQuery is set for a new incoming inline query. See
// [Router.InlineQuery].
InlineQuery *InlineQuery `json:"inline_query,omitempty"`
// ChosenInlineResult is set when a user picked one of the bot's
// inline query results — only delivered if inline feedback collection
// is enabled for the bot. See [Router.ChosenInlineResult].
ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result,omitempty"`
// CallbackQuery is set for a new incoming callback query (an inline
// keyboard button press). See [Router.CallbackQuery].
CallbackQuery *CallbackQuery `json:"callback_query,omitempty"`
// ShippingQuery is set for a new shipping query — only for invoices
// with a flexible price. See [Router.ShippingQuery].
ShippingQuery *ShippingQuery `json:"shipping_query,omitempty"`
// PreCheckoutQuery is set for a new pre-checkout query, carrying full
// checkout details; must be answered within 10 seconds (see
// [Ctx.AnswerPreCheckout]). See [Router.PreCheckoutQuery].
PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query,omitempty"`
// PurchasedPaidMedia is set when a user purchased paid media with a
// non-empty payload the bot sent in a non-channel chat. See
// [Router.PurchasedPaidMedia].
PurchasedPaidMedia *PaidMediaPurchased `json:"purchased_paid_media,omitempty"`
// Poll is set for a poll's public state changing — only for polls the
// bot sent, or that were manually stopped; this is not one voter's
// answer (see PollAnswer). See [Router.Poll].
Poll *Poll `json:"poll,omitempty"`
// PollAnswer is set when a user (re)voted in a non-anonymous poll the
// bot sent. See [Router.PollAnswer].
PollAnswer *PollAnswer `json:"poll_answer,omitempty"`
// MyChatMember is set when the bot's own membership status changed in
// a chat — for private chats, only on block/unblock. See
// [Router.MyChatMember].
MyChatMember *ChatMemberUpdated `json:"my_chat_member,omitempty"`
// ChatMember is set when some other member's status changed —
// requires the bot to be a chat admin and chat_member to be in
// allowed_updates. See [Router.ChatMember].
ChatMember *ChatMemberUpdated `json:"chat_member,omitempty"`
// ChatJoinRequest is set for a new join request — requires the bot to
// have the can_invite_users admin right. See [Router.ChatJoinRequest].
ChatJoinRequest *ChatJoinRequest `json:"chat_join_request,omitempty"`
// ChatBoost is set when a chat boost was added or changed — requires
// the bot to be a chat admin. See [Router.ChatBoost].
ChatBoost *ChatBoostUpdated `json:"chat_boost,omitempty"`
// RemovedChatBoost is set when a boost was removed from a chat —
// requires the bot to be a chat admin. See [Router.RemovedChatBoost].
RemovedChatBoost *ChatBoostRemoved `json:"removed_chat_boost,omitempty"`
// ManagedBot is set when a bot managed by this bot was created, or a
// managed bot's token or owner changed. See [Router.ManagedBot].
ManagedBot *ManagedBotUpdated `json:"managed_bot,omitempty"`
}
Update mirrors one Telegram update. Updates are decoded into a zero value, so exactly one payload pointer is non-nil per update (see Update.Kind) — nil-checks are meaningful and routing keys off which field is present.
func (*Update) Kind ¶
Kind returns which of Update's 25 payload fields is set, as Telegram's own JSON field name (e.g. "message", "callback_query") — the same strings Router.UsedUpdateKinds and allowed_updates use. Returns "" for a zero-value Update (shouldn't happen for anything Telegram actually sends, but kept honest rather than panicking or guessing).
type UpgradeGiftRequest ¶
type UpgradeGiftRequest struct {
// Unique identifier of the business connection
BusinessConnectionID string `json:"business_connection_id"`
// Unique identifier of the regular gift that should be upgraded to a unique one
OwnedGiftID string `json:"owned_gift_id"`
// Pass True to keep the original gift text, sender and receiver in the upgraded gift
KeepOriginalDetails bool `json:"keep_original_details,omitempty"`
// The amount of Telegram Stars that will be paid for the upgrade from the business account balance. If gift.prepaid_upgrade_star_count > 0, then pass 0, otherwise, the can_transfer_stars business bot right is required and gift.upgrade_star_count must be passed.
StarCount int64 `json:"star_count,omitempty"`
}
UpgradeGiftRequest holds the parameters for upgradeGift.
type UploadStickerFileRequest ¶
type UploadStickerFileRequest struct {
// User identifier of sticker file owner
UserID int64 `json:"user_id"`
// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files »
Sticker InputFile `json:"sticker"`
// Format of the sticker, must be one of “static”, “animated”, “video”
StickerFormat string `json:"sticker_format"`
}
UploadStickerFileRequest holds the parameters for uploadStickerFile.
type User ¶
type User struct {
// Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
ID int64 `json:"id"`
// True, if this user is a bot
IsBot bool `json:"is_bot"`
// User's or bot's first name
FirstName string `json:"first_name"`
// Optional. User's or bot's last name
LastName string `json:"last_name,omitempty"`
// Optional. User's or bot's username
Username string `json:"username,omitempty"`
// Optional. IETF language tag of the user's language
LanguageCode string `json:"language_code,omitempty"`
// Optional. True, if this user is a Telegram Premium user
IsPremium bool `json:"is_premium,omitempty"`
// Optional. True, if this user added the bot to the attachment menu
AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"`
// Optional. True, if the bot can be invited to groups. Returned only in getMe.
CanJoinGroups bool `json:"can_join_groups,omitempty"`
// Optional. True, if privacy mode is disabled for the bot. Returned only in getMe.
CanReadAllGroupMessages bool `json:"can_read_all_group_messages,omitempty"`
// Optional. True, if the bot supports guest queries from chats it is not a member of. Returned only in getMe.
SupportsGuestQueries bool `json:"supports_guest_queries,omitempty"`
// Optional. True, if the bot supports inline queries. Returned only in getMe.
SupportsInlineQueries bool `json:"supports_inline_queries,omitempty"`
// Optional. True, if the bot can be connected to a user account to manage it. Returned only in getMe.
CanConnectToBusiness bool `json:"can_connect_to_business,omitempty"`
// Optional. True, if the bot has a main Web App. Returned only in getMe.
HasMainWebApp bool `json:"has_main_web_app,omitempty"`
// Optional. True, if the bot has forum topic mode enabled in private chats. Returned only in getMe.
HasTopicsEnabled bool `json:"has_topics_enabled,omitempty"`
// Optional. True, if the bot allows users to create and delete topics in private chats. Returned only in getMe.
AllowsUsersToCreateTopics bool `json:"allows_users_to_create_topics,omitempty"`
// Optional. True, if other bots can be created to be controlled by the bot. Returned only in getMe.
CanManageBots bool `json:"can_manage_bots,omitempty"`
// Optional. True, if the bot supports join request queries and can be assigned to process them. Returned only in getMe.
SupportsJoinRequestQueries bool `json:"supports_join_request_queries,omitempty"`
}
This object represents a Telegram user or bot.
type UserChatBoosts ¶
type UserChatBoosts struct {
// The list of boosts added to the chat by the user
Boosts []ChatBoost `json:"boosts"`
}
This object represents a list of boosts added to a chat by a user.
type UserProfileAudios ¶
type UserProfileAudios struct {
// Total number of profile audios for the target user
TotalCount int64 `json:"total_count"`
// Requested profile audios
Audios []Audio `json:"audios"`
}
This object represents the audios displayed on a user's profile.
type UserProfilePhotos ¶
type UserProfilePhotos struct {
// Total number of profile pictures the target user has
TotalCount int64 `json:"total_count"`
// Requested profile pictures (in up to 4 sizes each)
Photos [][]PhotoSize `json:"photos"`
}
This object represent a user's profile pictures.
type UserRating ¶
type UserRating struct {
// Current level of the user, indicating their reliability when purchasing digital goods and services. A higher level suggests a more trustworthy customer; a negative level is likely reason for concern.
Level int64 `json:"level"`
// Numerical value of the user's rating; the higher the rating, the better
Rating int64 `json:"rating"`
// The rating value required to get the current level
CurrentLevelRating int64 `json:"current_level_rating"`
// Optional. The rating value required to get to the next level; omitted if the maximum level was reached
NextLevelRating int64 `json:"next_level_rating,omitempty"`
}
This object describes the rating of a user based on their Telegram Star spendings.
type UsersShared ¶
type UsersShared struct {
RequestID int64 `json:"request_id"`
Users []SharedUser `json:"users"`
}
This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button.
type ValidationError ¶
ValidationError is returned by send methods when a request would be rejected by Telegram, before any network call is made.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
type Venue ¶
type Venue struct {
// Venue location. Can't be a live location.
Location *Location `json:"location"`
// Name of the venue
Title string `json:"title"`
// Address of the venue
Address string `json:"address"`
// Optional. Foursquare identifier of the venue
FoursquareID string `json:"foursquare_id,omitempty"`
// Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
FoursquareType string `json:"foursquare_type,omitempty"`
// Optional. Google Places identifier of the venue
GooglePlaceID string `json:"google_place_id,omitempty"`
// Optional. Google Places type of the venue. (See supported types.)
GooglePlaceType string `json:"google_place_type,omitempty"`
}
This object represents a venue.
type VerifyChatRequest ¶
type VerifyChatRequest struct {
// Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel direct messages chats can't be verified.
ChatID ChatID `json:"chat_id"`
// Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
CustomDescription string `json:"custom_description,omitempty"`
}
VerifyChatRequest holds the parameters for verifyChat.
type VerifyUserRequest ¶
type VerifyUserRequest struct {
// Unique identifier of the target user
UserID int64 `json:"user_id"`
// Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
CustomDescription string `json:"custom_description,omitempty"`
}
VerifyUserRequest holds the parameters for verifyUser.
type Video ¶
type Video struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Video width as defined by the sender
Width int64 `json:"width"`
// Video height as defined by the sender
Height int64 `json:"height"`
// Duration of the video in seconds as defined by the sender
Duration int64 `json:"duration"`
// Optional. Video thumbnail
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
// Optional. Available sizes of the cover of the video in the message
Cover []PhotoSize `json:"cover,omitempty"`
// Optional. Timestamp in seconds from which the video will play in the message
StartTimestamp int64 `json:"start_timestamp,omitempty"`
// Optional. List of available qualities of the video
Qualities []VideoQuality `json:"qualities,omitempty"`
// Optional. Original filename as defined by the sender
FileName string `json:"file_name,omitempty"`
// Optional. MIME type of the file as defined by the sender
MimeType string `json:"mime_type,omitempty"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a video file.
type VideoChatEnded ¶
type VideoChatEnded struct {
// Video chat duration in seconds
Duration int64 `json:"duration"`
}
This object represents a service message about a video chat ended in the chat.
type VideoChatParticipantsInvited ¶
type VideoChatParticipantsInvited struct {
// New members that were invited to the video chat
Users []User `json:"users"`
}
This object represents a service message about new members invited to a video chat.
type VideoChatScheduled ¶
type VideoChatScheduled struct {
// Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator
StartDate int64 `json:"start_date"`
}
This object represents a service message about a video chat scheduled in the chat.
type VideoChatStarted ¶
type VideoChatStarted struct {
}
This object represents a service message about a video chat started in the chat. Currently holds no information.
type VideoNote ¶
type VideoNote struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Video width and height (diameter of the video message) as defined by the sender
Length int64 `json:"length"`
// Duration of the video in seconds as defined by the sender
Duration int64 `json:"duration"`
// Optional. Video thumbnail
Thumbnail *PhotoSize `json:"thumbnail,omitempty"`
// Optional. File size in bytes
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a video message (available in Telegram apps as of v.4.0).
type VideoQuality ¶
type VideoQuality struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Video width
Width int64 `json:"width"`
// Video height
Height int64 `json:"height"`
// Codec that was used to encode the video, for example, “h264”, “h265”, or “av01”
Codec string `json:"codec"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a video file of a specific quality.
type Voice ¶
type Voice struct {
// Identifier for this file, which can be used to download or reuse the file
FileID string `json:"file_id"`
// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
FileUniqueID string `json:"file_unique_id"`
// Duration of the audio in seconds as defined by the sender
Duration int64 `json:"duration"`
// Optional. MIME type of the file as defined by the sender
MimeType string `json:"mime_type,omitempty"`
// Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
FileSize int64 `json:"file_size,omitempty"`
}
This object represents a voice note.
type WebAppChat ¶
type WebAppChat struct {
ID int64 `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
Username string `json:"username,omitempty"`
PhotoURL string `json:"photo_url,omitempty"`
}
WebAppChat is the chat object inside validated WebApp init data (present when the Mini App was launched from a group/supergroup/channel's attach menu).
type WebAppData ¶
type WebAppData struct {
// The data. Be aware that a bad client can send arbitrary data in this field.
Data string `json:"data"`
// Text of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field.
ButtonText string `json:"button_text"`
}
Describes data sent from a Web App to the bot.
type WebAppEnvironment ¶
type WebAppEnvironment int
WebAppEnvironment selects which of Telegram's published Ed25519 public keys ValidateWebAppInitDataThirdParty verifies a signature against — production bots and Telegram's test environment sign with different keys.
const ( // WebAppProd is Telegram's production environment. WebAppProd WebAppEnvironment = iota // WebAppTest is Telegram's test environment (a separate DC bots opt // into for development; see Telegram's docs on testing your bot). WebAppTest )
type WebAppInfo ¶
type WebAppInfo struct {
// An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps
URL string `json:"url"`
}
Describes a Web App.
type WebAppInitData ¶
type WebAppInitData struct {
QueryID string
User *WebAppUser
Receiver *WebAppUser
Chat *WebAppChat
ChatType string
ChatInstance string
StartParam string
// CanSendAfter is the delay after which [TelegramBot.AnswerWebAppQuery]
// may be called (zero if Telegram sent none).
CanSendAfter time.Duration
AuthDate time.Time
// Hash is the bot-token HMAC field — populated whichever validator ran,
// but only actually checked by [ValidateWebAppInitData].
Hash string
// Signature is the Ed25519 field — populated whichever validator ran,
// but only actually checked by [ValidateWebAppInitDataThirdParty].
Signature string
// Raw holds every field as received, including ones this struct
// doesn't model — all of them participated in the verified hash.
Raw url.Values
}
WebAppInitData is the parsed, verified payload of window.Telegram.WebApp.initData. Only ValidateWebAppInitData (bot-token HMAC) or ValidateWebAppInitDataThirdParty (Telegram's own Ed25519 key, no bot token needed) produce one — if you're holding a WebAppInitData, whichever of the two you called has confirmed the data came from Telegram.
func ValidateWebAppInitData ¶
func ValidateWebAppInitData(initData, botToken string, maxAge time.Duration) (*WebAppInitData, error)
ValidateWebAppInitData authenticates a Mini App's initData string (posted to your backend by the WebApp's own JavaScript) against the bot token, per the Mini Apps spec: secret = HMAC-SHA256(bot_token, key "WebAppData"); hash = hex(HMAC-SHA256(data-check-string, secret)). This is security-critical — never trust user/query_id from initData that hasn't passed here.
maxAge bounds how old the payload's auth_date may be (replay protection); pass 0 to skip the freshness check. Telegram recommends checking — an old but validly-signed payload can be replayed by anyone who once saw it.
func ValidateWebAppInitDataThirdParty ¶
func ValidateWebAppInitDataThirdParty(initData string, botID int64, env WebAppEnvironment, maxAge time.Duration) (*WebAppInitData, error)
ValidateWebAppInitDataThirdParty authenticates initData via Telegram's third-party Ed25519 flow instead of ValidateWebAppInitData's bot-token HMAC: it verifies the init data's "signature" field against one of Telegram's own published public keys (chosen by env), so a server that never holds the bot token at all — a separate backend behind the actual bot, for instance — can still confirm a payload really came from Telegram for botID. Per Telegram's Mini Apps docs, the signed message is "{botID}:WebAppData\n" followed by every field except hash and signature, sorted by key, as "key=value" lines joined with "\n"; the signature itself arrives base64url-encoded.
maxAge bounds how old auth_date may be, same as ValidateWebAppInitData; pass 0 to skip the freshness check.
type WebAppUser ¶
type WebAppUser struct {
ID int64 `json:"id"`
IsBot bool `json:"is_bot,omitempty"`
FirstName string `json:"first_name"`
LastName string `json:"last_name,omitempty"`
Username string `json:"username,omitempty"`
LanguageCode string `json:"language_code,omitempty"`
IsPremium bool `json:"is_premium,omitempty"`
AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"`
AllowsWriteToPM bool `json:"allows_write_to_pm,omitempty"`
PhotoURL string `json:"photo_url,omitempty"`
}
WebAppUser is the user object inside validated WebApp init data. It is defined by the Mini Apps docs, not the Bot API spec, so it is hand-written rather than generated.
type WebhookConfig ¶
type WebhookConfig struct {
// Addr is the local address to listen on, e.g. ":8443".
Addr string
// Path is the URL path Telegram will POST updates to, e.g.
// "/telegram/webhook". Must match the path component of PublicURL.
Path string
// PublicURL is the full HTTPS URL passed to setWebhook — the address
// Telegram itself will POST updates to. Required; must be reachable
// from Telegram's servers (a public HTTPS endpoint, or a tunnel to one
// in development).
PublicURL string
// SecretToken is verified against the X-Telegram-Bot-Api-Secret-Token
// header Telegram sends on every webhook request — this check is
// webhook mode's entire security model. Highly recommended: without
// it, anyone who finds PublicURL can feed the bot fake updates.
// 1-256 chars, A-Z a-z 0-9 _ - only (Telegram's constraint).
SecretToken string
// MaxConnections caps simultaneous HTTPS connections Telegram opens to
// deliver updates (1-100, Telegram default 40). Zero means "use
// Telegram's default".
MaxConnections int64
// DropPendingUpdates discards any updates queued before the webhook
// was (re-)set.
DropPendingUpdates bool
// DeleteOnStop calls deleteWebhook when RunWebhook's context is
// canceled. Off by default: most deployments (rolling restarts, brief
// redeploys) want the webhook to stay registered across a restart, not
// be torn down and lose updates in the gap.
DeleteOnStop bool
// Server, if non-nil, is used as the base *http.Server (for timeouts,
// custom TLSConfig, etc.) instead of a zero-value one. RunWebhook still
// sets Addr and Handler on it. Set CertFile/KeyFile (or a TLSConfig with
// Certificates/GetCertificate already populated) to actually serve TLS
// — see those fields' docs.
Server *http.Server
// CertFile and KeyFile, if both set, make RunWebhook listen with
// ListenAndServeTLS instead of plain ListenAndServe. Telegram requires
// HTTPS webhooks: without this (or a TLS-terminating reverse proxy in
// front of Addr), Telegram silently never delivers a single update —
// there's no error, the bot just looks idle. Leave both empty when a
// proxy already terminates TLS in front of this server. Alternatively,
// set Server.TLSConfig with Certificates or GetCertificate populated
// and leave these empty; RunWebhook detects that too.
CertFile string
KeyFile string
// UploadCertificate, if set, is the path to a certificate file read and
// sent as [SetWebhookRequest.Certificate] when registering the webhook
// — required so Telegram can verify a self-signed certificate's chain;
// leave empty for a CA-signed certificate (including one obtained via
// a reverse proxy).
UploadCertificate string
}
WebhookConfig configures TelegramBot.RunWebhook.
type WebhookInfo ¶
type WebhookInfo struct {
// Webhook URL, may be empty if webhook is not set up
URL string `json:"url"`
// True, if a custom certificate was provided for webhook certificate checks
HasCustomCertificate bool `json:"has_custom_certificate"`
// Number of updates awaiting delivery
PendingUpdateCount int64 `json:"pending_update_count"`
// Optional. Currently used webhook IP address
IpAddress string `json:"ip_address,omitempty"`
// Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook
LastErrorDate int64 `json:"last_error_date,omitempty"`
// Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
LastErrorMessage string `json:"last_error_message,omitempty"`
// Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters
LastSynchronizationErrorDate int64 `json:"last_synchronization_error_date,omitempty"`
// Optional. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
MaxConnections int64 `json:"max_connections,omitempty"`
// Optional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member, message_reaction, and message_reaction_count.
AllowedUpdates []string `json:"allowed_updates,omitempty"`
}
Describes the current status of a webhook.
type WebhookReply ¶
type WebhookReply struct {
// contains filtered or unexported fields
}
WebhookReply pairs a generated request with the Bot API method name it belongs to, built by Reply. Its JSON encoding is exactly the shape Telegram's reply-in-webhook-response optimization expects: the request's own fields, plus a top-level "method" field naming which Bot API method to invoke with them.
func AsWebhookReply ¶
func AsWebhookReply(err error) (*WebhookReply, bool)
AsWebhookReply extracts the *WebhookReply from err, if it is (or wraps) one returned by Reply. TelegramBot's own dispatch (bot.go) always resolves one before it could reach a caller; this is for code that drives Router directly instead of going through TelegramBot.
func (*WebhookReply) MarshalJSON ¶
func (wr *WebhookReply) MarshalJSON() ([]byte, error)
MarshalJSON renders wr as Telegram's webhook-response-body shape: params' own JSON fields with "method" added alongside them.
func (*WebhookReply) Method ¶
func (wr *WebhookReply) Method() string
Method returns the Bot API method name this reply calls (e.g. "sendMessage") — mainly for a custom dispatch loop that drives Router directly (see AsWebhookReply) and needs to perform the call itself.
func (*WebhookReply) Params ¶
func (wr *WebhookReply) Params() any
Params returns the request this reply calls Method with — the same value passed to Reply.
type Wizard ¶
type Wizard struct {
// contains filtered or unexported fields
}
Wizard is a linear, stateful conversation builder on top of the existing FSM primitives (see StateGroup, StateIs, FSMContext): each Wizard.Step becomes its own State under one StateGroup, auto-advanced by WizardCtx.Next/WizardCtx.Back/WizardCtx.GoTo, with a configurable cancel command and enter/exit/cancel hooks.
w := gg.NewWizard("register")
w.Step(func(wc *gg.WizardCtx) error {
gg.FSMSet(wc.FSM(), "name", wc.Text())
if _, err := wc.Answer("And your age?"); err != nil {
return err
}
return wc.Next()
})
// ... more steps ...
r.Include(w.Router())
r.Message(gg.FilterCommand("register")).Handle(func(c *gg.Ctx) error {
if err := w.Enter(c); err != nil {
return err
}
_, err := c.Answer("What's your name?")
return err
})
func NewWizard ¶
func NewWizard(name string, opts ...WizardOption) *Wizard
NewWizard creates a Wizard named name — name seeds the underlying StateGroup, so it must be unique among wizards sharing one FSMStorage. Registers the cancel command (default "cancel", see WithCancelCommand) on the wizard's own router immediately, before any Wizard.Step — guaranteeing it's tried before any step within the wizard's own router, regardless of how many steps are added later.
func (*Wizard) Cancel ¶
Cancel leaves the wizard as a cancellation: clears FSM state and data, then runs the WithOnCancel hook (falling back to WithOnExit's hook if unset). Works from any handler, not just a step's.
func (*Wizard) Enter ¶
Enter starts the wizard for c's conversation: clears any prior FSM state and data under this wizard's group (so a re-entered wizard never inherits stale data from an earlier abandoned attempt), sets state to step 0, and runs the WithOnEnter hook if set. Call this from whatever triggers the wizard (e.g. a command handler) — it works from any handler, not just a step's.
func (*Wizard) Exit ¶
Exit leaves the wizard normally: clears FSM state and data, then runs the WithOnExit hook if set. Works from any handler, not just a step's.
func (*Wizard) Router ¶
Router returns the wizard's steps (and cancel command) as a *Router, ready to Router.Include into a parent router. Include it before any handler that could otherwise shadow a step or the cancel command — registration order is priority, same as any other router.
func (*Wizard) State ¶
State returns step i's underlying State — for registering additional, non-Message-kind handlers (e.g. a CallbackQuery step) gated on the same step via StateIs, since Wizard.Step only wires Message updates. Panics if i is out of range.
func (*Wizard) Step ¶
func (w *Wizard) Step(handler WizardStepFunc, opts ...StepOption) int
Step appends a new step, gated on its own State: while that state is active, a text message runs handler wrapped in a WizardCtx. Returns the step's 0-based index, for WizardCtx.GoTo or Wizard.State.
By default a step doesn't match a command (see WithStepAllowCommands) or anything matched by a WithStepIgnore filter — both fall through to whatever's registered after this wizard instead of being swallowed as step input.
func (*Wizard) Use ¶
func (w *Wizard) Use(mw MiddlewareFunc)
Use registers scoped middleware run before every step's handler (including the built-in cancel command) — forwards to the wizard's internal router; see Router.Use.
type WizardCtx ¶
type WizardCtx struct {
*Ctx
// contains filtered or unexported fields
}
WizardCtx is the *Ctx handed to a Wizard step, plus step-advance sugar. Embeds *Ctx, so all of Ctx's own sugar (Answer, Reply, FSM, Text, ...) is available unchanged.
func (*WizardCtx) Back ¶
Back returns to the step before the current one. A no-op on the first step — there's nowhere to go back to.
func (*WizardCtx) Cancel ¶
Cancel leaves the wizard as a cancellation — see Wizard.Cancel.
func (*WizardCtx) Exit ¶
Exit leaves the wizard normally — see Wizard.Exit.
func (*WizardCtx) GoTo ¶
GoTo jumps directly to step i (0-based, in Wizard.Step registration order) — an escape hatch for non-linear flows, e.g. an "edit an earlier answer" menu. Panics if i is out of range: that's a caller-side bug to fix, not a runtime condition to handle gracefully.
func (*WizardCtx) Next ¶
Next advances to the step after the current one. If the current step is the last one, Next behaves like Wizard.Exit instead.
type WizardOption ¶
type WizardOption func(*Wizard)
WizardOption configures a Wizard built by NewWizard.
func WithCancelCommand ¶
func WithCancelCommand(command string) WizardOption
WithCancelCommand sets the command (without "/") that cancels the wizard from any step (default "cancel"). Pass "" to disable the built-in cancel route entirely.
func WithOnCancel ¶
func WithOnCancel(fn func(c *Ctx) error) WizardOption
WithOnCancel registers a hook run specifically on cancellation (the cancel command, or an explicit WizardCtx.Cancel/Wizard.Cancel call) — falls back to WithOnExit's hook if unset.
func WithOnEnter ¶
func WithOnEnter(fn func(c *Ctx) error) WizardOption
WithOnEnter registers a hook run by Wizard.Enter right after the wizard's state is set to its first step.
func WithOnExit ¶
func WithOnExit(fn func(c *Ctx) error) WizardOption
WithOnExit registers a hook run on Wizard.Exit — a step completing normally via WizardCtx.Next past the last step, or an explicit WizardCtx.Exit/Wizard.Exit call. Also runs on cancellation if WithOnCancel isn't set.
type WizardStepFunc ¶
WizardStepFunc is one step's handler in a Wizard.
type WriteAccessAllowed ¶
type WriteAccessAllowed struct {
// Optional. True, if the access was granted after the user accepted an explicit request from a Web App sent by the method requestWriteAccess
FromRequest bool `json:"from_request,omitempty"`
// Optional. Name of the Web App, if the access was granted when the Web App was launched from a link
WebAppName string `json:"web_app_name,omitempty"`
// Optional. True, if the access was granted when the bot was added to the attachment or side menu
FromAttachmentMenu bool `json:"from_attachment_menu,omitempty"`
}
This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess.
Source Files
¶
- admin_cache.go
- backoff.go
- bot.go
- broadcast.go
- callback_data.go
- callback_query.go
- chat_action.go
- commands.go
- common.go
- consts.gen.go
- ctx.go
- deeplink.go
- doc.go
- entity_text.go
- errors.go
- filters.go
- format.go
- format_entities.go
- fsm.go
- fsm_memory.go
- gen.go
- health.go
- i18n.go
- inline_keyboard.go
- input_file.go
- keyboard.go
- keyed_mutex.go
- media_group.go
- message.go
- message_options.go
- methods.gen.go
- middleware.go
- pagination.go
- payments.go
- reply_markup.go
- richmessage_builder.go
- richmessage_reader.go
- richtext.go
- router.go
- sender.go
- types.gen.go
- update.go
- validation.go
- version.go
- webapp.go
- webhook.go
- webhook_reply.go
- wizard.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
broadcast
command
Command broadcast shows gg.Broadcast: an in-memory subscriber list, a /subscribe command anyone can run, and an admin-only /broadcast <text> that pages through every subscriber at a paced rate with live progress logged to stdout.
|
Command broadcast shows gg.Broadcast: an in-memory subscriber list, a /subscribe command anyone can run, and an admin-only /broadcast <text> that pages through every subscriber at a paced rate with live progress logged to stdout. |
|
deeplink
command
Command deeplink shows a referral flow: plain /start hands back a shareable https://t.me/<bot>?start=<payload> link (CreateStartLink), and /start <payload> — the receiving side, opened via that link — reads the payload back while a live "typing..." indicator (KeepChatAction) covers a pretend lookup.
|
Command deeplink shows a referral flow: plain /start hands back a shareable https://t.me/<bot>?start=<payload> link (CreateStartLink), and /start <payload> — the receiving side, opened via that link — reads the payload back while a live "typing..." indicator (KeepChatAction) covers a pretend lookup. |
|
echo
command
Command echo is the smallest real golagram bot: /start plus a plain-text echo.
|
Command echo is the smallest real golagram bot: /start plus a plain-text echo. |
|
formatting
command
Command formatting shows the two questions every bot library eventually gets asked: /bio <text> proves untrusted input can't break HTML parsing (try "/bio <b>hi" — a naive bot would crash the parse_mode with a 400), and /lipsum proves a message far past Telegram's 4096-char limit still sends, split at word boundaries.
|
Command formatting shows the two questions every bot library eventually gets asked: /bio <text> proves untrusted input can't break HTML parsing (try "/bio <b>hi" — a naive bot would crash the parse_mode with a 400), and /lipsum proves a message far past Telegram's 4096-char limit still sends, split at word boundaries. |
|
fsm
command
Command fsm shows golagram's conversation model: a tiny /register wizard (name, then age, then confirm) built from a StateGroup and FSMGet/FSMSet.
|
Command fsm shows golagram's conversation model: a tiny /register wizard (name, then age, then confirm) built from a StateGroup and FSMGet/FSMSet. |
|
i18n
command
Command i18n shows locale-aware translations with real CLDR plural rules: /lang switches locale, /hello greets in it, and /apples <n> against Russian shows the one/few/many split (not just one/other) firing correctly for 1, 2, 5, 21.
|
Command i18n shows locale-aware translations with real CLDR plural rules: /lang switches locale, /hello greets in it, and /apples <n> against Russian shows the one/few/many split (not just one/other) firing correctly for 1, 2, 5, 21. |
|
keyboard
command
Command keyboard shows the core inline-keyboard loop: send a menu, answer the tap, edit the message in place.
|
Command keyboard shows the core inline-keyboard loop: send a menu, answer the tap, edit the message in place. |
|
media
command
Command media shows golagram's InputFile constructors: /photo sends an image by URL (no local file needed to run this example anywhere), and an incoming photo gets echoed back by file_id — no re-upload.
|
Command media shows golagram's InputFile constructors: /photo sends an image by URL (no local file needed to run this example anywhere), and an incoming photo gets echoed back by file_id — no re-upload. |
|
middleware
command
Command middleware shows composability: global logging + auto-answered callbacks on the root router, and an admin-only sub-router mounted with Router.Include that non-admins fall straight through (ErrSkipHandler).
|
Command middleware shows composability: global logging + auto-answered callbacks on the root router, and an admin-only sub-router mounted with Router.Include that non-admins fall straight through (ErrSkipHandler). |
|
pagination
command
Command pagination shows a paged catalog built from gg.NewPagination and gg.NewCallbackData[T] together: a full « ‹ n/total › » nav row and typed, 64-byte-safe callback payloads, with zero hand-rolled string parsing.
|
Command pagination shows a paged catalog built from gg.NewPagination and gg.NewCallbackData[T] together: a full « ‹ n/total › » nav row and typed, 64-byte-safe callback payloads, with zero hand-rolled string parsing. |
|
payments
command
Command payments shows a complete Telegram Stars purchase flow — no external payment provider to configure, since Stars are native to Telegram: /buy sends an invoice, a pre_checkout_query is approved automatically, a successful payment is acknowledged and its charge ID remembered, and /refund gives the Stars back.
|
Command payments shows a complete Telegram Stars purchase flow — no external payment provider to configure, since Stars are native to Telegram: /buy sends an invoice, a pre_checkout_query is approved automatically, a successful payment is acknowledged and its charge ID remembered, and /refund gives the Stars back. |
|
richmessage
command
Command richmessage demonstrates Bot API 10.1's Rich Messages (sendRichMessage/sendRichMessageDraft).
|
Command richmessage demonstrates Bot API 10.1's Rich Messages (sendRichMessage/sendRichMessageDraft). |
|
todo
command
Command todo is a small but complete bot — a per-user task list — split by responsibility: handlers.go has one method per route, routes.go is the route table, store.go is the data layer, and main.go just wires them together.
|
Command todo is a small but complete bot — a per-user task list — split by responsibility: handlers.go has one method per route, routes.go is the route table, store.go is the data layer, and main.go just wires them together. |
|
wizard
command
Command wizard is examples/fsm's same /register conversation (name, then age, then confirm), rebuilt with gg.Wizard instead of hand-wired StateGroup/StateIs registrations — diff the two files to see exactly what the sugar removes: no manual SetState per step, no hand-wired /cancel route, one declarative step list.
|
Command wizard is examples/fsm's same /register conversation (name, then age, then confirm), rebuilt with gg.Wizard instead of hand-wired StateGroup/StateIs registrations — diff the two files to see exactly what the sugar removes: no manual SetState per step, no hand-wired /cancel route, one declarative step list. |
|
Package fsmtest is a reusable conformance suite for FSMStorage implementations.
|
Package fsmtest is a reusable conformance suite for FSMStorage implementations. |
|
Package golagramtest provides first-class testing support for bots built on golagram.
|
Package golagramtest provides first-class testing support for bots built on golagram. |
|
internal
|
|
|
api
Package api is golagram's single HTTP path to the Telegram Bot API.
|
Package api is golagram's single HTTP path to the Telegram Bot API. |
|
gen
command
Gen is golagram's code generator (codegen stage 2): it reads scripts/api.json (produced by scripts/parse_botapi.py, stage 1) and emits types.gen.go and methods.gen.go at the repository root.
|
Gen is golagram's code generator (codegen stage 2): it reads scripts/api.json (produced by scripts/parse_botapi.py, stage 1) and emits types.gen.go and methods.gen.go at the repository root. |