From 797f683a71269be25db71133e60c82e96c8e0725 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 6 Nov 2022 01:32:26 +0200 Subject: [PATCH 01/70] Implement Bot API 6.3 changes. --- configs.go | 163 ++++++++++++++++++++++++++++++++++++++++++++++++++--- helpers.go | 4 +- types.go | 88 ++++++++++++++++++++++++++++- 3 files changed, 246 insertions(+), 9 deletions(-) diff --git a/configs.go b/configs.go index 1831337b..5d702d79 100644 --- a/configs.go +++ b/configs.go @@ -265,6 +265,7 @@ func (CloseConfig) params() (Params, error) { // BaseChat is base type for all chat config types. type BaseChat struct { ChatID int64 // required + MessageThreadID int ChannelUsername string ProtectContent bool ReplyToMessageID int @@ -277,6 +278,7 @@ func (chat *BaseChat) params() (Params, error) { params := make(Params) params.AddFirstValid("chat_id", chat.ChatID, chat.ChannelUsername) + params.AddNonZero("message_thread_id", chat.MessageThreadID) params.AddNonZero("reply_to_message_id", chat.ReplyToMessageID) params.AddBool("disable_notification", chat.DisableNotification) params.AddBool("allow_sending_without_reply", chat.AllowSendingWithoutReply) @@ -1383,6 +1385,7 @@ type PromoteChatMemberConfig struct { CanRestrictMembers bool CanPinMessages bool CanPromoteMembers bool + CanManageTopics bool } func (config PromoteChatMemberConfig) method() string { @@ -1406,6 +1409,7 @@ func (config PromoteChatMemberConfig) params() (Params, error) { params.AddBool("can_restrict_members", config.CanRestrictMembers) params.AddBool("can_pin_messages", config.CanPinMessages) params.AddBool("can_promote_members", config.CanPromoteMembers) + params.AddBool("can_manage_topics", config.CanManageTopics) return params, nil } @@ -2220,16 +2224,158 @@ func (config DeleteChatStickerSetConfig) params() (Params, error) { return params, nil } +// GetForumTopicIconStickersConfig allows you to get custom emoji stickers, +// which can be used as a forum topic icon by any user. +type GetForumTopicIconStickersConfig struct{} + +func (config GetForumTopicIconStickersConfig) method() string { + return "getForumTopicIconStickers" +} + +func (config GetForumTopicIconStickersConfig) params() (Params, error) { + return nil, nil +} + +// CreateForumTopicConfig allows you to create a topic +// in a forum supergroup chat. +type CreateForumTopicConfig struct { + ChatID int64 + Name string + IconColor int + IconCustomEmojiID string + SuperGroupUsername string +} + +func (config CreateForumTopicConfig) method() string { + return "createForumTopic" +} + +func (config CreateForumTopicConfig) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonEmpty("name", config.Name) + params.AddNonZero("icon_color", config.IconColor) + params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) + + return params, nil +} + +// EditForumTopicConfig allows you to edit +// name and icon of a topic in a forum supergroup chat. +type EditForumTopicConfig struct { + ChatID int64 + MessageThreadID int + Name string + IconCustomEmojiID string + SuperGroupUsername string +} + +func (config EditForumTopicConfig) method() string { + return "editForumTopic" +} + +func (config EditForumTopicConfig) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonZero("message_thread_id", config.MessageThreadID) + params.AddNonEmpty("icon_color", config.Name) + params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) + + return params, nil +} + +// CloseForumTopicConfig allows you to close +// an open topic in a forum supergroup chat. +type CloseForumTopicConfig struct { + ChatID int64 + MessageThreadID int + SuperGroupUsername string +} + +func (config CloseForumTopicConfig) method() string { + return "closeForumTopic" +} + +func (config CloseForumTopicConfig) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonZero("message_thread_id", config.MessageThreadID) + + return params, nil +} + +// ReopenForumTopicConfig allows you to reopen +// an closed topic in a forum supergroup chat. +type ReopenForumTopicConfig struct { + ChatID int64 + MessageThreadID int + SuperGroupUsername string +} + +func (config ReopenForumTopicConfig) method() string { + return "reopenForumTopic" +} + +func (config ReopenForumTopicConfig) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonZero("message_thread_id", config.MessageThreadID) + + return params, nil +} + +// DeleteForumTopicConfig allows you to delete a forum topic +// along with all its messages in a forum supergroup chat. +type DeleteForumTopicConfig struct { + ChatID int64 + MessageThreadID int + SuperGroupUsername string +} + +func (config DeleteForumTopicConfig) method() string { + return "deleteForumTopic" +} + +func (config DeleteForumTopicConfig) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonZero("message_thread_id", config.MessageThreadID) + + return params, nil +} + +// UnpinAllForumTopicMessagesConfig allows you to clear the list +// of pinned messages in a forum topic. +type UnpinAllForumTopicMessagesConfig struct { + ChatID int64 + MessageThreadID int + SuperGroupUsername string +} + +func (config UnpinAllForumTopicMessagesConfig) method() string { + return "unpinAllForumTopicMessages" +} + +func (config UnpinAllForumTopicMessagesConfig) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddNonZero("message_thread_id", config.MessageThreadID) + + return params, nil +} + // MediaGroupConfig allows you to send a group of media. // // Media consist of InputMedia items (InputMediaPhoto, InputMediaVideo). type MediaGroupConfig struct { - ChatID int64 - ChannelUsername string - + BaseChat Media []interface{} - DisableNotification bool - ReplyToMessageID int } func (config MediaGroupConfig) method() string { @@ -2237,13 +2383,16 @@ func (config MediaGroupConfig) method() string { } func (config MediaGroupConfig) params() (Params, error) { - params := make(Params) + params, err := config.BaseChat.params() + if err != nil { + return nil, err + } params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) params.AddBool("disable_notification", config.DisableNotification) params.AddNonZero("reply_to_message_id", config.ReplyToMessageID) - err := params.AddInterface("media", prepareInputMediaForParams(config.Media)) + err = params.AddInterface("media", prepareInputMediaForParams(config.Media)) return params, err } diff --git a/helpers.go b/helpers.go index 3a0e8187..bdf2ee97 100644 --- a/helpers.go +++ b/helpers.go @@ -178,7 +178,9 @@ func NewVoice(chatID int64, file RequestFileData) VoiceConfig { // two to ten InputMediaPhoto or InputMediaVideo. func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { return MediaGroupConfig{ - ChatID: chatID, + BaseChat: BaseChat{ + ChatID: chatID, + }, Media: files, } } diff --git a/types.go b/types.go index 36c174b8..ffe46a77 100644 --- a/types.go +++ b/types.go @@ -261,8 +261,22 @@ type Chat struct { // // optional LastName string `json:"last_name,omitempty"` + // IsForum is true if the supergroup chat is a forum (has topics enabled) + // + // optional + IsForum bool `json:"is_forum,omitempty"` // Photo is a chat photo Photo *ChatPhoto `json:"photo"` + // If non-empty, the list of all active chat usernames; + // for private chats, supergroups and channels. Returned only in getChat. + // + // optional + ActiveUsernames []string `json:"active_usernames,omitempty"` + // Custom emoji identifier of emoji status of the other party + // in a private chat. Returned only in getChat. + // + // optional + EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` // Bio is the bio of the other party in a private chat. Returned only in // getChat // @@ -361,6 +375,11 @@ func (c Chat) ChatConfig() ChatConfig { type Message struct { // MessageID is a unique message identifier inside this chat MessageID int `json:"message_id"` + // Unique identifier of a message thread to which the message belongs; + // for supergroups only + // + // optional + MessageThreadID int `json:"message_thread_id,omitempty"` // From is a sender, empty for messages sent to channels; // // optional @@ -404,6 +423,10 @@ type Message struct { // // optional ForwardDate int `json:"forward_date,omitempty"` + // IsTopicMessage true if the message is sent to a forum topic + // + // optional + IsTopicMessage bool `json:"is_topic_message,omitempty"` // IsAutomaticForward is true if the message is a channel post that was // automatically forwarded to the connected discussion group. // @@ -608,6 +631,18 @@ type Message struct { // // optional ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered,omitempty"` + // ForumTopicCreated is a service message: forum topic created + // + // optional + ForumTopicCreated *ForumTopicCreated `json:"forum_topic_created,omitempty"` + // ForumTopicClosed is a service message: forum topic closed + // + // optional + ForumTopicClosed *ForumTopicClosed `json:"forum_topic_closed,omitempty"` + // ForumTopicReopened is a service message: forum topic reopened + // + // optional + ForumTopicReopened *ForumTopicReopened `json:"forum_topic_reopened,omitempty"` // VideoChatScheduled is a service message: video chat scheduled. // // optional @@ -1181,6 +1216,30 @@ type MessageAutoDeleteTimerChanged struct { MessageAutoDeleteTime int `json:"message_auto_delete_time"` } +// ForumTopicCreated represents a service message about a new forum topic +// created in the chat. +type ForumTopicCreated struct { + // Name is the name of topic + Name string `json:"name"` + // IconColor is the color of the topic icon in RGB format + IconColor int `json:"icon_color"` + // IconCustomEmojiID is the unique identifier of the custom emoji + // shown as the topic icon + // + // optional + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + +// ForumTopicClosed represents a service message about a forum topic +// closed in the chat. Currently holds no information. +type ForumTopicClosed struct { +} + +// ForumTopicReopened represents a service message about a forum topic +// reopened in the chat. Currently holds no information. +type ForumTopicReopened struct { +} + // VideoChatScheduled represents a service message about a voice chat scheduled // in the chat. type VideoChatScheduled struct { @@ -1591,6 +1650,7 @@ type ChatAdministratorRights struct { CanPostMessages bool `json:"can_post_messages"` CanEditMessages bool `json:"can_edit_messages"` CanPinMessages bool `json:"can_pin_messages"` + CanManageTopics bool `json:"can_manage_topics"` } // ChatMember contains information about one member of a chat. @@ -1682,7 +1742,13 @@ type ChatMember struct { // True, if the user is allowed to pin messages; groups and supergroups only // // optional - CanPinMessages bool `json:"can_pin_messages,omitempty"` + CanPinMessages bool `json:"can_pin_messages,omitempty"` + // CanManageTopics administrators and restricted only. + // True, if the user is allowed to create, rename, + // close, and reopen forum topics; supergroups only + // + // optional + CanManageTopics bool `json:"can_manage_topics,omitempty"` // IsMember is true, if the user is a member of the chat at the moment of // the request IsMember bool `json:"is_member"` @@ -1806,6 +1872,11 @@ type ChatPermissions struct { // // optional CanPinMessages bool `json:"can_pin_messages,omitempty"` + // CanManageTopics is true, if the user is allowed to create forum topics. + // If omitted defaults to the value of can_pin_messages + // + // optional + CanManageTopics bool `json:"can_manage_topics,omitempty"` } // ChatLocation represents a location to which a chat is connected. @@ -1818,6 +1889,21 @@ type ChatLocation struct { Address string `json:"address"` } +// ForumTopic represents a forum topic. +type ForumTopic struct { + // MessageThreadID is the unique identifier of the forum topic + MessageThreadID int `json:"message_thread_id"` + // Name is the name of the topic + Name string `json:"name"` + // IconColor is the color of the topic icon in RGB format + IconColor int `json:"icon_color"` + // IconCustomEmojiID is the unique identifier of the custom emoji + // shown as the topic icon + // + // optional + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + // BotCommand represents a bot command. type BotCommand struct { // Command text of the command, 1-32 characters. From f7e326b02e008b78a79cd56f85786a5940d0939c Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 20 Nov 2022 21:55:30 +0200 Subject: [PATCH 02/70] Implement Bot API 6.2 changes. --- configs.go | 24 +++++++++++++++++++++--- types.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/configs.go b/configs.go index 1831337b..b3f01a69 100644 --- a/configs.go +++ b/configs.go @@ -2004,6 +2004,24 @@ func (config GetStickerSetConfig) params() (Params, error) { return params, nil } +// GetCustomEmojiStickersConfig get information about +// custom emoji stickers by their identifiers. +type GetCustomEmojiStickersConfig struct { + CustomEmojiIDs []string +} + +func (config GetCustomEmojiStickersConfig) params() (Params, error) { + params := make(Params) + + params.AddInterface("custom_emoji_ids", config.CustomEmojiIDs) + + return params, nil +} + +func (config GetCustomEmojiStickersConfig) method() string { + return "getCustomEmojiStickers" +} + // UploadStickerConfig allows you to upload a sticker for use in a set later. type UploadStickerConfig struct { UserID int64 @@ -2038,8 +2056,9 @@ type NewStickerSetConfig struct { Title string PNGSticker RequestFileData TGSSticker RequestFileData + StickerType string Emojis string - ContainsMasks bool + ContainsMasks bool // deprecated MaskPosition *MaskPosition } @@ -2053,11 +2072,10 @@ func (config NewStickerSetConfig) params() (Params, error) { params.AddNonZero64("user_id", config.UserID) params["name"] = config.Name params["title"] = config.Title - params["emojis"] = config.Emojis params.AddBool("contains_masks", config.ContainsMasks) - + params.AddNonEmpty("sticker_type", string(config.StickerType)) err := params.AddInterface("mask_position", config.MaskPosition) return params, err diff --git a/types.go b/types.go index 36c174b8..d1c84439 100644 --- a/types.go +++ b/types.go @@ -274,6 +274,12 @@ type Chat struct { // // optional HasPrivateForwards bool `json:"has_private_forwards,omitempty"` + // HasRestrictedVoiceAndVideoMessages if the privacy settings of the other party + // restrict sending voice and video note messages + // in the private chat. Returned only in getChat. + // + // optional + HasRestrictedVoiceAndVideoMessages bool `json:"has_restricted_voice_and_video_messages,omitempty"` // Description for groups, supergroups and channel chats // // optional @@ -730,6 +736,7 @@ type MessageEntity struct { // “pre” (monowidth block), // “text_link” (for clickable text URLs), // “text_mention” (for users without usernames) + // “text_mention” (for inline custom emoji stickers) Type string `json:"type"` // Offset in UTF-16 code units to the start of the entity Offset int `json:"offset"` @@ -747,6 +754,10 @@ type MessageEntity struct { // // optional Language string `json:"language,omitempty"` + // CustomEmojiID for “custom_emoji” only, unique identifier of the custom emoji + // + // optional + CustomEmojiID string `json:"custom_emoji_id"` } // ParseURL attempts to parse a URL contained within a MessageEntity. @@ -1984,6 +1995,13 @@ type InputMediaDocument struct { DisableContentTypeDetection bool `json:"disable_content_type_detection,omitempty"` } +// Constant values for sticker types +const ( + StickerTypeRegular = "regular" + StickerTypeMask = "mask" + StickerTypeCustomEmoji = "custom_emoji" +) + // Sticker represents a sticker. type Sticker struct { // FileID is an identifier for this file, which can be used to download or @@ -1993,6 +2011,10 @@ type Sticker struct { // 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 is a 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"` // Width sticker width Width int `json:"width"` // Height sticker height @@ -2036,6 +2058,21 @@ type Sticker struct { FileSize int `json:"file_size,omitempty"` } +// IsRegular returns if the Sticker is regular +func (s Sticker) IsRegular() bool { + return s.Type == StickerTypeRegular +} + +// IsMask returns if the Sticker is mask +func (s Sticker) IsMask() bool { + return s.Type == StickerTypeMask +} + +// IsCustomEmoji returns if the Sticker is custom emoji +func (s Sticker) IsCustomEmoji() bool { + return s.Type == StickerTypeCustomEmoji +} + // StickerSet represents a sticker set. type StickerSet struct { // Name sticker set name @@ -2049,6 +2086,8 @@ type StickerSet struct { // IsVideo true, if the sticker set contains video stickers IsVideo bool `json:"is_video"` // ContainsMasks true, if the sticker set contains masks + // + // deprecated. Use sticker_type instead ContainsMasks bool `json:"contains_masks"` // Stickers list of all set stickers Stickers []Sticker `json:"stickers"` @@ -2056,6 +2095,21 @@ type StickerSet struct { Thumbnail *PhotoSize `json:"thumb"` } +// IsRegular returns if the StickerSet is regular +func (s StickerSet) IsRegular() bool { + return s.StickerType == StickerTypeRegular +} + +// IsMask returns if the StickerSet is mask +func (s StickerSet) IsMask() bool { + return s.StickerType == StickerTypeMask +} + +// IsCustomEmoji returns if the StickerSet is custom emoji +func (s StickerSet) IsCustomEmoji() bool { + return s.StickerType == StickerTypeCustomEmoji +} + // MaskPosition describes the position on faces where a mask should be placed // by default. type MaskPosition struct { From a89ebaebf3fc161e6e8ef3f4ce65595ec49dd40e Mon Sep 17 00:00:00 2001 From: stdkhai Date: Sun, 20 Nov 2022 21:58:26 +0200 Subject: [PATCH 03/70] Implement Bot API 6.1 changes --- .gitignore | 1 + configs.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ types.go | 28 +++++++++++++++++++------ 3 files changed, 83 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index eb7a23b2..d3083e5f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ coverage.out tmp/ book/ +.vscode/ diff --git a/configs.go b/configs.go index 1831337b..d90f29ea 100644 --- a/configs.go +++ b/configs.go @@ -1164,6 +1164,7 @@ type WebhookConfig struct { MaxConnections int AllowedUpdates []string DropPendingUpdates bool + SecretToken string } func (config WebhookConfig) method() string { @@ -1181,6 +1182,7 @@ func (config WebhookConfig) params() (Params, error) { params.AddNonZero("max_connections", config.MaxConnections) err := params.AddInterface("allowed_updates", config.AllowedUpdates) params.AddBool("drop_pending_updates", config.DropPendingUpdates) + params.AddNonEmpty("secret_token", config.SecretToken) return params, err } @@ -1784,6 +1786,64 @@ func (config InvoiceConfig) method() string { return "sendInvoice" } +// InvoiceLinkConfig contains information for createInvoiceLink method +type InvoiceLinkConfig struct { + Title string //Required + Description string //Required + Payload string //Required + ProviderToken string //Required + Currency string //Required + Prices []LabeledPrice //Required + MaxTipAmount int + SuggestedTipAmounts []int + ProviderData string + PhotoURL string + PhotoSize int + PhotoWidth int + PhotoHeight int + NeedName bool + NeedPhoneNumber bool + NeedEmail bool + NeedShippingAddress bool + SendPhoneNumberToProvider bool + SendEmailToProvider bool + IsFlexible bool +} + +func (config InvoiceLinkConfig) params() (Params, error) { + params := make(Params) + + params["title"] = config.Title + params["description"] = config.Description + params["payload"] = config.Payload + params["provider_token"] = config.ProviderToken + params["currency"] = config.Currency + if err := params.AddInterface("prices", config.Prices); err != nil { + return params, err + } + + params.AddNonZero("max_tip_amount", config.MaxTipAmount) + err := params.AddInterface("suggested_tip_amounts", config.SuggestedTipAmounts) + params.AddNonEmpty("provider_data", config.ProviderData) + params.AddNonEmpty("photo_url", config.PhotoURL) + params.AddNonZero("photo_size", config.PhotoSize) + params.AddNonZero("photo_width", config.PhotoWidth) + params.AddNonZero("photo_height", config.PhotoHeight) + params.AddBool("need_name", config.NeedName) + params.AddBool("need_phone_number", config.NeedPhoneNumber) + params.AddBool("need_email", config.NeedEmail) + params.AddBool("need_shipping_address", config.NeedShippingAddress) + params.AddBool("send_phone_number_to_provider", config.SendPhoneNumberToProvider) + params.AddBool("send_email_to_provider", config.SendEmailToProvider) + params.AddBool("is_flexible", config.IsFlexible) + + return params, err +} + +func (config InvoiceLinkConfig) method() string { + return "createInvoiceLink" +} + // ShippingConfig contains information for answerShippingQuery request. type ShippingConfig struct { ShippingQueryID string // required diff --git a/types.go b/types.go index 36c174b8..8d44f588 100644 --- a/types.go +++ b/types.go @@ -187,6 +187,10 @@ type User struct { // // optional IsPremium bool `json:"is_premium,omitempty"` + // AddedToAttachmentMenu true, if this user added the bot to the attachment menu + // + // optional + AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"` // FirstName user's or bot's first name FirstName string `json:"first_name"` // LastName user's or bot's last name @@ -274,6 +278,18 @@ type Chat struct { // // optional HasPrivateForwards bool `json:"has_private_forwards,omitempty"` + // JoinToSendMessages is true, if users need to join the supergroup + // before they can send messages. + // Returned only in getChat + // + // optional + JoinToSendMessages bool `json:"join_to_send_messages,omitempty"` + // JoinByRequest is true, if all users directly joining the supergroup + // need to be approved by supergroup administrators. + // Returned only in getChat. + // + // optional + JoinByRequest bool `json:"join_by_request,omitempty"` // Description for groups, supergroups and channel chats // // optional @@ -863,7 +879,7 @@ type Animation struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` } // Audio represents an audio file to be treated as music by the Telegram clients. @@ -896,7 +912,7 @@ type Audio struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` // Thumbnail is the album cover to which the music file belongs // // optional @@ -927,7 +943,7 @@ type Document struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` } // Video represents a video file. @@ -960,7 +976,7 @@ type Video struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` } // VideoNote object represents a video message. @@ -1002,7 +1018,7 @@ type Voice struct { // FileSize file size // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` } // Contact represents a phone contact. @@ -1234,7 +1250,7 @@ type File struct { // FileSize file size, if known // // optional - FileSize int `json:"file_size,omitempty"` + FileSize int64 `json:"file_size,omitempty"` // FilePath file path // // optional From 5e115c98c785b5aefa00552c0c366eb6940078f1 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sat, 31 Dec 2022 02:15:29 +0200 Subject: [PATCH 04/70] Implement Bot API 6.4 changes --- configs.go | 191 ++++++++++++++++++++++++++++++++++++++++++-------- params.go | 7 ++ types.go | 91 ++++++++++++++++++++++-- types_test.go | 12 ++++ 4 files changed, 268 insertions(+), 33 deletions(-) diff --git a/configs.go b/configs.go index 77bb5060..5a8c71e8 100644 --- a/configs.go +++ b/configs.go @@ -323,6 +323,21 @@ func (edit BaseEdit) params() (Params, error) { return params, err } +// BaseSpoiler is base type of structures with spoilers. +type BaseSpoiler struct { + HasSpoiler bool +} + +func (spoiler BaseSpoiler) params() (Params, error) { + params := make(Params) + + if spoiler.HasSpoiler { + params.AddBool("has_spoiler", true) + } + + return params, nil +} + // MessageConfig contains information about a SendMessage request. type MessageConfig struct { BaseChat @@ -407,6 +422,7 @@ func (config CopyMessageConfig) method() string { // PhotoConfig contains information about a SendPhoto request. type PhotoConfig struct { BaseFile + BaseSpoiler Thumb RequestFileData Caption string ParseMode string @@ -422,6 +438,15 @@ func (config PhotoConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } + + p1, err := config.BaseSpoiler.params() + if err != nil { + return params, err + } + params.Merge(p1) return params, err } @@ -557,6 +582,7 @@ func (config StickerConfig) files() []RequestFile { // VideoConfig contains information about a SendVideo request. type VideoConfig struct { BaseFile + BaseSpoiler Thumb RequestFileData Duration int Caption string @@ -576,6 +602,15 @@ func (config VideoConfig) params() (Params, error) { params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("supports_streaming", config.SupportsStreaming) err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } + + p1, err := config.BaseSpoiler.params() + if err != nil { + return params, err + } + params.Merge(p1) return params, err } @@ -603,6 +638,7 @@ func (config VideoConfig) files() []RequestFile { // AnimationConfig contains information about a SendAnimation request. type AnimationConfig struct { BaseFile + BaseSpoiler Duration int Thumb RequestFileData Caption string @@ -620,6 +656,15 @@ func (config AnimationConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } + + p1, err := config.BaseSpoiler.params() + if err != nil { + return params, err + } + params.Merge(p1) return params, err } @@ -976,6 +1021,7 @@ func (config GetGameHighScoresConfig) method() string { // ChatActionConfig contains information about a SendChatAction request. type ChatActionConfig struct { BaseChat + MessageThreadID int Action string // required } @@ -983,6 +1029,7 @@ func (config ChatActionConfig) params() (Params, error) { params, err := config.BaseChat.params() params["action"] = config.Action + params.AddNonZero("message_thread_id", config.MessageThreadID) return params, err } @@ -2314,14 +2361,27 @@ func (config GetForumTopicIconStickersConfig) params() (Params, error) { return nil, nil } +// BaseForum is a base type for all forum config types. +type BaseForum struct { + ChatID int64 + SuperGroupUsername string +} + +func (config BaseForum) params() (Params, error) { + params := make(Params) + + params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + + return params, nil +} + // CreateForumTopicConfig allows you to create a topic // in a forum supergroup chat. type CreateForumTopicConfig struct { - ChatID int64 - Name string - IconColor int - IconCustomEmojiID string - SuperGroupUsername string + BaseForum + Name string + IconColor int + IconCustomEmojiID string } func (config CreateForumTopicConfig) method() string { @@ -2331,22 +2391,23 @@ func (config CreateForumTopicConfig) method() string { func (config CreateForumTopicConfig) params() (Params, error) { params := make(Params) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonEmpty("name", config.Name) params.AddNonZero("icon_color", config.IconColor) params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) + p1, _ := config.BaseForum.params() + params.Merge(p1) + return params, nil } // EditForumTopicConfig allows you to edit // name and icon of a topic in a forum supergroup chat. type EditForumTopicConfig struct { - ChatID int64 - MessageThreadID int - Name string - IconCustomEmojiID string - SuperGroupUsername string + BaseForum + MessageThreadID int + Name string + IconCustomEmojiID string } func (config EditForumTopicConfig) method() string { @@ -2356,20 +2417,21 @@ func (config EditForumTopicConfig) method() string { func (config EditForumTopicConfig) params() (Params, error) { params := make(Params) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("message_thread_id", config.MessageThreadID) - params.AddNonEmpty("icon_color", config.Name) + params.AddNonEmpty("name", config.Name) params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) + p1, _ := config.BaseForum.params() + params.Merge(p1) + return params, nil } // CloseForumTopicConfig allows you to close // an open topic in a forum supergroup chat. type CloseForumTopicConfig struct { - ChatID int64 - MessageThreadID int - SuperGroupUsername string + BaseForum + MessageThreadID int } func (config CloseForumTopicConfig) method() string { @@ -2379,18 +2441,19 @@ func (config CloseForumTopicConfig) method() string { func (config CloseForumTopicConfig) params() (Params, error) { params := make(Params) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("message_thread_id", config.MessageThreadID) + p1, _ := config.BaseForum.params() + params.Merge(p1) + return params, nil } // ReopenForumTopicConfig allows you to reopen // an closed topic in a forum supergroup chat. type ReopenForumTopicConfig struct { - ChatID int64 - MessageThreadID int - SuperGroupUsername string + BaseForum + MessageThreadID int } func (config ReopenForumTopicConfig) method() string { @@ -2403,15 +2466,17 @@ func (config ReopenForumTopicConfig) params() (Params, error) { params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("message_thread_id", config.MessageThreadID) + p1, _ := config.BaseForum.params() + params.Merge(p1) + return params, nil } // DeleteForumTopicConfig allows you to delete a forum topic // along with all its messages in a forum supergroup chat. type DeleteForumTopicConfig struct { - ChatID int64 - MessageThreadID int - SuperGroupUsername string + BaseForum + MessageThreadID int } func (config DeleteForumTopicConfig) method() string { @@ -2421,18 +2486,19 @@ func (config DeleteForumTopicConfig) method() string { func (config DeleteForumTopicConfig) params() (Params, error) { params := make(Params) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("message_thread_id", config.MessageThreadID) + p1, _ := config.BaseForum.params() + params.Merge(p1) + return params, nil } // UnpinAllForumTopicMessagesConfig allows you to clear the list // of pinned messages in a forum topic. type UnpinAllForumTopicMessagesConfig struct { - ChatID int64 - MessageThreadID int - SuperGroupUsername string + BaseForum + MessageThreadID int } func (config UnpinAllForumTopicMessagesConfig) method() string { @@ -2445,15 +2511,84 @@ func (config UnpinAllForumTopicMessagesConfig) params() (Params, error) { params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("message_thread_id", config.MessageThreadID) + p1, _ := config.BaseForum.params() + params.Merge(p1) + + return params, nil +} + +// UnpinAllForumTopicMessagesConfig allows you 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 can_manage_topics administrator rights. Returns True on success. +type EditGeneralForumTopicConfig struct { + BaseForum + Name string +} + +func (config EditGeneralForumTopicConfig) method() string { + return "editGeneralForumTopic" +} + +func (config EditGeneralForumTopicConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("name", config.Name) + + p1, _ := config.BaseForum.params() + params.Merge(p1) + return params, nil } +// CloseGeneralForumTopicConfig allows you to 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. +type CloseGeneralForumTopicConfig struct{ BaseForum } + +func (config CloseGeneralForumTopicConfig) method() string { + return "closeGeneralForumTopic" +} + +// CloseGeneralForumTopicConfig allows you 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. +type ReopenGeneralForumTopicConfig struct{ BaseForum } + +func (config ReopenGeneralForumTopicConfig) method() string { + return "reopenGeneralForumTopic" +} + +// HideGeneralForumTopicConfig allows you 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. +type HideGeneralForumTopicConfig struct{ BaseForum } + +func (config HideGeneralForumTopicConfig) method() string { + return "hideGeneralForumTopic" +} + +// UnhideGeneralForumTopicConfig allows you 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. +type UnhideGeneralForumTopicConfig struct{ BaseForum } + +func (config UnhideGeneralForumTopicConfig) method() string { + return "unhideGeneralForumTopic" +} + // MediaGroupConfig allows you to send a group of media. // // Media consist of InputMedia items (InputMediaPhoto, InputMediaVideo). type MediaGroupConfig struct { BaseChat - Media []interface{} + Media []interface{} } func (config MediaGroupConfig) method() string { diff --git a/params.go b/params.go index 134f85e4..118af364 100644 --- a/params.go +++ b/params.go @@ -95,3 +95,10 @@ func (p Params) AddFirstValid(key string, args ...interface{}) error { return nil } + +// Merge merges two sets of parameters. Overwrites old fields if present +func (p *Params) Merge(p1 Params) { + for k, v := range p1 { + (*p)[k] = v + } +} \ No newline at end of file diff --git a/types.go b/types.go index 8aceb913..8d9a67f4 100644 --- a/types.go +++ b/types.go @@ -276,7 +276,7 @@ type Chat struct { // // optional ActiveUsernames []string `json:"active_usernames,omitempty"` - // Custom emoji identifier of emoji status of the other party + // Custom emoji identifier of emoji status of the other party // in a private chat. Returned only in getChat. // // optional @@ -292,8 +292,8 @@ type Chat struct { // // optional HasPrivateForwards bool `json:"has_private_forwards,omitempty"` - // HasRestrictedVoiceAndVideoMessages if the privacy settings of the other party - // restrict sending voice and video note messages + // HasRestrictedVoiceAndVideoMessages if the privacy settings of the other party + // restrict sending voice and video note messages // in the private chat. Returned only in getChat. // // optional @@ -340,6 +340,17 @@ type Chat struct { // // optional MessageAutoDeleteTime int `json:"message_auto_delete_time,omitempty"` + // HasAggressiveAntiSpamEnabled is true if aggressive anti-spam checks are enabled + // in the supergroup. The field is only available to chat administrators. + // Returned only in getChat. + // + // optional + HasAggressiveAntiSpamEnabled bool `json:"has_aggressive_anti_spam_enabled,omitempty"` + // HasHiddenMembers is true if non-administrators can only get + // the list of bots and administrators in the chat. + // + // optional + HasHiddenMembers bool `json:"has_hidden_members,omitempty"` // HasProtectedContent is true if messages from the chat can't be forwarded // to other chats. Returned only in getChat. // @@ -535,6 +546,10 @@ type Message struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // HasSpoiler True, if the message media is covered by a spoiler animation + // + // optional + HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"` // Contact message is a shared contact, information about the contact; // // optional @@ -644,6 +659,11 @@ type Message struct { // // optional ConnectedWebsite string `json:"connected_website,omitempty"` + // WriteAccessAllowed is a service message: the user allowed the bot + // added to the attachment menu to write messages + // + // optional + WriteAccessAllowed *WriteAccessAllowed `json:"write_access_allowed,omitempty"` // PassportData is a Telegram Passport data; // // optional @@ -657,6 +677,10 @@ type Message struct { // // optional ForumTopicCreated *ForumTopicCreated `json:"forum_topic_created,omitempty"` + // ForumTopicClosed is a service message: forum topic edited + // + // optional + ForumTopicEdited *ForumTopicEdited `json:"forum_topic_edited,omitempty"` // ForumTopicClosed is a service message: forum topic closed // // optional @@ -665,6 +689,14 @@ type Message struct { // // optional ForumTopicReopened *ForumTopicReopened `json:"forum_topic_reopened,omitempty"` + // GeneralForumTopicHidden is a service message: the 'General' forum topic hidden + // + // optional + GeneralForumTopicHidden *GeneralForumTopicHidden `json:"general_forum_topic_hidden,omitempty"` + // GeneralForumTopicUnhidden is a service message: the 'General' forum topic unhidden + // + // optional + GeneralForumTopicUnhidden *GeneralForumTopicUnhidden `json:"general_forum_topic_unhidden,omitempty"` // VideoChatScheduled is a service message: video chat scheduled. // // optional @@ -1262,11 +1294,41 @@ type ForumTopicCreated struct { type ForumTopicClosed struct { } +// ForumTopicEdited object represents a service message about an edited forum topic. +type ForumTopicEdited struct { + // Name is the new name of the topic, if it was edited + // + // optional + Name string `json:"name,omitempty"` + // IconCustomEmojiID is the new identifier of the custom emoji + // shown as the topic icon, if it was edited; + // an empty string if the icon was removed + // + // optional + IconCustomEmojiID *string `json:"icon_custom_emoji_id,omitempty"` +} + // ForumTopicReopened represents a service message about a forum topic // reopened in the chat. Currently holds no information. type ForumTopicReopened struct { } +// GeneralForumTopicHidden represents a service message about General forum topic +// hidden in the chat. Currently holds no information. +type GeneralForumTopicHidden struct { +} + +// GeneralForumTopicUnhidden represents a service message about General forum topic +// unhidden in the chat. Currently holds no information. +type GeneralForumTopicUnhidden struct { +} + +// WriteAccessAllowed represents a service message about a user +// allowing a bot added to the attachment menu to write messages. +// Currently holds no information. +type WriteAccessAllowed struct { +} + // VideoChatScheduled represents a service message about a voice chat scheduled // in the chat. type VideoChatScheduled struct { @@ -1345,6 +1407,13 @@ type WebAppInfo struct { type ReplyKeyboardMarkup struct { // Keyboard is an array of button rows, each represented by an Array of KeyboardButton objects Keyboard [][]KeyboardButton `json:"keyboard"` + // IsPersistent 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. + // + // optional + IsPersistent bool `json:"is_persistent"` // ResizeKeyboard 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 @@ -1769,9 +1838,9 @@ type ChatMember struct { // True, if the user is allowed to pin messages; groups and supergroups only // // optional - CanPinMessages bool `json:"can_pin_messages,omitempty"` + CanPinMessages bool `json:"can_pin_messages,omitempty"` // CanManageTopics administrators and restricted only. - // True, if the user is allowed to create, rename, + // True, if the user is allowed to create, rename, // close, and reopen forum topics; supergroups only // // optional @@ -2004,6 +2073,10 @@ type BaseInputMedia struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // HasSpoiler pass True, if the photo needs to be covered with a spoiler animation + // + // optional + HasSpoiler bool `json:"has_spoiler,omitempty"` } // InputMediaPhoto is a photo to send as part of a media group. @@ -2035,6 +2108,10 @@ type InputMediaVideo struct { // // optional SupportsStreaming bool `json:"supports_streaming,omitempty"` + // HasSpoiler pass True, if the video needs to be covered with a spoiler animation + // + // optional + HasSpoiler bool `json:"has_spoiler,omitempty"` } // InputMediaAnimation is an animation to send as part of a media group. @@ -2057,6 +2134,10 @@ type InputMediaAnimation struct { // // optional Duration int `json:"duration,omitempty"` + // HasSpoiler pass True, if the photo needs to be covered with a spoiler animation + // + // optional + HasSpoiler bool `json:"has_spoiler,omitempty"` } // InputMediaAudio is an audio to send as part of a media group. diff --git a/types_test.go b/types_test.go index 0c6ba4ab..2dfe1d1a 100644 --- a/types_test.go +++ b/types_test.go @@ -347,6 +347,18 @@ var ( _ Chattable = VideoNoteConfig{} _ Chattable = VoiceConfig{} _ Chattable = WebhookConfig{} + _ Chattable = CreateForumTopicConfig{} + _ Chattable = EditForumTopicConfig{} + _ Chattable = CloseForumTopicConfig{} + _ Chattable = ReopenForumTopicConfig{} + _ Chattable = DeleteForumTopicConfig{} + _ Chattable = UnpinAllForumTopicMessagesConfig{} + _ Chattable = GetForumTopicIconStickersConfig{} + _ Chattable = EditGeneralForumTopicConfig{} + _ Chattable = CloseGeneralForumTopicConfig{} + _ Chattable = ReopenGeneralForumTopicConfig{} + _ Chattable = HideGeneralForumTopicConfig{} + _ Chattable = UnhideGeneralForumTopicConfig{} ) // Ensure all Fileable types are correct. From 16635e50ea30023ca1223b6320bafa885fa849d5 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sat, 4 Feb 2023 04:53:55 +0200 Subject: [PATCH 05/70] Implement Bot API 6.5 changes --- configs.go | 12 ++- types.go | 211 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 210 insertions(+), 13 deletions(-) diff --git a/configs.go b/configs.go index 5a8c71e8..09c9c468 100644 --- a/configs.go +++ b/configs.go @@ -1022,7 +1022,7 @@ func (config GetGameHighScoresConfig) method() string { type ChatActionConfig struct { BaseChat MessageThreadID int - Action string // required + Action string // required } func (config ChatActionConfig) params() (Params, error) { @@ -1400,8 +1400,9 @@ type KickChatMemberConfig = BanChatMemberConfig // RestrictChatMemberConfig contains fields to restrict members of chat type RestrictChatMemberConfig struct { ChatMemberConfig - UntilDate int64 - Permissions *ChatPermissions + UntilDate int64 + UseIndependentChatPermissions bool + Permissions *ChatPermissions } func (config RestrictChatMemberConfig) method() string { @@ -1413,6 +1414,7 @@ func (config RestrictChatMemberConfig) params() (Params, error) { params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) params.AddNonZero64("user_id", config.UserID) + params.AddBool("use_independent_chat_permissions", config.UseIndependentChatPermissions) err := params.AddInterface("permissions", config.Permissions) params.AddNonZero64("until_date", config.UntilDate) @@ -1578,7 +1580,8 @@ func (ChatAdministratorsConfig) method() string { // restrict members. type SetChatPermissionsConfig struct { ChatConfig - Permissions *ChatPermissions + UseIndependentChatPermissions bool + Permissions *ChatPermissions } func (SetChatPermissionsConfig) method() string { @@ -1589,6 +1592,7 @@ func (config SetChatPermissionsConfig) params() (Params, error) { params := make(Params) params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) + params.AddBool("use_independent_chat_permissions", config.UseIndependentChatPermissions) err := params.AddInterface("permissions", config.Permissions) return params, err diff --git a/types.go b/types.go index 8d9a67f4..bf3d62d6 100644 --- a/types.go +++ b/types.go @@ -340,8 +340,8 @@ type Chat struct { // // optional MessageAutoDeleteTime int `json:"message_auto_delete_time,omitempty"` - // HasAggressiveAntiSpamEnabled is true if aggressive anti-spam checks are enabled - // in the supergroup. The field is only available to chat administrators. + // HasAggressiveAntiSpamEnabled is true if aggressive anti-spam checks are enabled + // in the supergroup. The field is only available to chat administrators. // Returned only in getChat. // // optional @@ -654,6 +654,14 @@ type Message struct { // // optional SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"` + // UserShared is a service message: a user was shared with the bot + // + // optional + UserShared *UserShared `json:"user_shared,omitempty"` + // ChatShared is a service message: a chat was shared with the bot + // + // optional + ChatShared *ChatShared `json:"chat_shared,omitempty"` // ConnectedWebsite is the domain name of the website on which the user has // logged in; // @@ -1323,6 +1331,24 @@ type GeneralForumTopicHidden struct { type GeneralForumTopicUnhidden struct { } +// UserShared object contains information about the user whose identifier +// was shared with the bot using a KeyboardButtonRequestUser button. +type UserShared struct { + // RequestID is an indentifier of the request. + RequestID int `json:"request_id"` + // UserID in an identifier of the shared user. + UserID int64 +} + +// ChatShared contains information about the chat whose identifier +// was shared with the bot using a KeyboardButtonRequestChat button. +type ChatShared struct { + // RequestID is an indentifier of the request. + RequestID int `json:"request_id"` + // ChatID is an identifier of the shared chat. + ChatID int64 +} + // WriteAccessAllowed represents a service message about a user // allowing a bot added to the attachment menu to write messages. // Currently holds no information. @@ -1455,6 +1481,20 @@ type KeyboardButton struct { // Text of the button. If none of the optional fields are used, // it will be sent as a message when the button is pressed. Text string `json:"text"` + // RequestUser if specified, pressing the button will open + // a list of suitable users. Tapping on any user will send + // their identifier to the bot in a "user_shared" service message. + // Available in private chats only. + // + // optional + RequestUser *KeyboardButtonRequestUser `json:"request_user,omitempty"` + // RequestChat 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. + // + // optional + RequestChat *KeyboardButtonRequestChat `json:"request_chat,omitempty"` // RequestContact if True, the user's phone number will be sent // as a contact when the button is pressed. // Available in private chats only. @@ -1480,6 +1520,72 @@ type KeyboardButton struct { WebApp *WebAppInfo `json:"web_app,omitempty"` } +// KeyboardButtonRequestUser defines the criteria used to request +// a suitable user. The identifier of the selected user will be shared +// with the bot when the corresponding button is pressed. +type KeyboardButtonRequestUser struct { + // RequestID is a signed 32-bit identifier of the request. + RequestID int `json:"request_id"` + // UserIsBot pass True to request a bot, + // pass False to request a regular user. + // If not specified, no additional restrictions are applied. + // + // optional + UserIsBot bool `json:"user_is_bot,omitempty"` + // UserIsPremium pass True to request a premium user, + // pass False to request a non-premium user. + // If not specified, no additional restrictions are applied. + // + // optional + UserIsPremium bool `json:"user_is_premium,omitempty"` +} + +// KeyboardButtonRequestChat defines the criteria used to request +// a suitable chat. The identifier of the selected chat will be shared +// with the bot when the corresponding button is pressed. +type KeyboardButtonRequestChat struct { + // RequestID is a signed 32-bit identifier of the request. + RequestID int `json:"request_id"` + // ChatIsChannel pass True to request a channel chat, + // pass False to request a group or a supergroup chat. + ChatIsChannel bool `json:"chat_is_channel"` + // ChatIsForum pass True to request a forum supergroup, + // pass False to request a non-forum chat. + // If not specified, no additional restrictions are applied. + // + // optional + ChatIsForum bool `json:"chat_is_forum,omitempty"` + // ChatHasUsername 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. + // + // optional + ChatHasUsername bool `json:"chat_has_username,omitempty"` + // ChatIsCreated pass True to request a chat owned by the user. + // Otherwise, no additional restrictions are applied. + // + // optional + ChatIsCreated bool `json:"chat_is_created,omitempty"` + // UserAdministratorRights is a JSON-serialized object listing + // the required administrator rights of the user in the chat. + // If not specified, no additional restrictions are applied. + // + // optional + UserAdministratorRights *ChatAdministratorRights `json:"user_administrator_rights,omitempty"` + // BotAdministratorRights is 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. + // + // optional + BotAdministratorRights *ChatAdministratorRights `json:"bot_administrator_rights,omitempty"` + // BotIsMember pass True to request a chat with the bot as a member. + // Otherwise, no additional restrictions are applied. + // + // optional + BotIsMember bool `json:"bot_is_member,omitempty"` +} + // KeyboardButtonPollType represents type of poll, which is allowed to // be created and sent when the corresponding button is pressed. type KeyboardButtonPollType struct { @@ -1852,11 +1958,36 @@ type ChatMember struct { // // optional CanSendMessages bool `json:"can_send_messages,omitempty"` - // CanSendMediaMessages restricted only. - // True, if the user is allowed to send text messages, contacts, locations and venues + // CanSendAudios restricted only. + // True, if the user is allowed to send audios + // + // optional + CanSendAudios bool + // CanSendDocuments restricted only. + // True, if the user is allowed to send documents + // + // optional + CanSendDocuments bool + // CanSendPhotos is restricted only. + // True, if the user is allowed to send photos // // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` + CanSendPhotos bool + // CanSendVideos restricted only. + // True, if the user is allowed to send videos + // + // optional + CanSendVideos bool + // CanSendVideoNotes restricted only. + // True, if the user is allowed to send video notes + // + // optional + CanSendVideoNotes bool + // CanSendVoiceNotes restricted only. + // True, if the user is allowed to send voice notes + // + // optional + CanSendVoiceNotes bool // CanSendPolls restricted only. // True, if the user is allowed to send polls // @@ -1887,6 +2018,27 @@ func (chat ChatMember) HasLeft() bool { return chat.Status == "left" } // WasKicked returns if the ChatMember was kicked from the chat. func (chat ChatMember) WasKicked() bool { return chat.Status == "kicked" } +// SetCanSendMediaMessages is a method to replace field "can_send_media_messages". +// It sets CanSendAudio, CanSendDocuments, CanSendPhotos, CanSendVideos, +// CanSendVideoNotes, CanSendVoiceNotes to passed value. +func (chat *ChatMember) SetCanSendMediaMessages(b bool) { + chat.CanSendAudios = b + chat.CanSendDocuments = b + chat.CanSendPhotos = b + chat.CanSendVideos = b + chat.CanSendVideoNotes = b + chat.CanSendVoiceNotes = b +} + +// CanSendMediaMessages method to replace field "can_send_media_messages". +// It returns true if CanSendAudio and CanSendDocuments and CanSendPhotos and CanSendVideos and +// CanSendVideoNotes and CanSendVoiceNotes are true. +func (chat *ChatMember) CanSendMediaMessages() bool { + return chat.CanSendAudios && chat.CanSendDocuments && + chat.CanSendPhotos && chat.CanSendVideos && + chat.CanSendVideoNotes && chat.CanSendVoiceNotes +} + // ChatMemberUpdated represents changes in the status of a chat member. type ChatMemberUpdated struct { // Chat the user belongs to. @@ -1912,6 +2064,8 @@ type ChatJoinRequest struct { Chat Chat `json:"chat"` // User that sent the join request. From User `json:"from"` + // UserChatID identifier of a private chat with the user who sent the join request. + UserChatID int64 `json:"user_chat_id"` // Date the request was sent in Unix time. Date int `json:"date"` // Bio of the user. @@ -1932,12 +2086,30 @@ type ChatPermissions struct { // // optional CanSendMessages bool `json:"can_send_messages,omitempty"` - // CanSendMediaMessages is true, if the user is allowed to send audios, - // documents, photos, videos, video notes and voice notes, implies - // can_send_messages + // CanSendAudios is true, if the user is allowed to send audios + // + // optional + CanSendAudios bool + // CanSendDocuments is true, if the user is allowed to send documents + // + // optional + CanSendDocuments bool + // CanSendPhotos is true, if the user is allowed to send photos // // optional - CanSendMediaMessages bool `json:"can_send_media_messages,omitempty"` + CanSendPhotos bool + // CanSendVideos is true, if the user is allowed to send videos + // + // optional + CanSendVideos bool + // CanSendVideoNotes is true, if the user is allowed to send video notes + // + // optional + CanSendVideoNotes bool + // CanSendVoiceNotes is true, if the user is allowed to send voice notes + // + // optional + CanSendVoiceNotes bool // CanSendPolls is true, if the user is allowed to send polls, implies // can_send_messages // @@ -1975,6 +2147,27 @@ type ChatPermissions struct { CanManageTopics bool `json:"can_manage_topics,omitempty"` } +// SetCanSendMediaMessages is a method to replace field "can_send_media_messages". +// It sets CanSendAudio, CanSendDocuments, CanSendPhotos, CanSendVideos, +// CanSendVideoNotes, CanSendVoiceNotes to passed value. +func (c *ChatPermissions) SetCanSendMediaMessages(b bool) { + c.CanSendAudios = b + c.CanSendDocuments = b + c.CanSendPhotos = b + c.CanSendVideos = b + c.CanSendVideoNotes = b + c.CanSendVoiceNotes = b +} + +// CanSendMediaMessages method to replace field "can_send_media_messages". +// It returns true if CanSendAudio and CanSendDocuments and CanSendPhotos and CanSendVideos and +// CanSendVideoNotes and CanSendVoiceNotes are true. +func (c *ChatPermissions) CanSendMediaMessages() bool { + return c.CanSendAudios && c.CanSendDocuments && + c.CanSendPhotos && c.CanSendVideos && + c.CanSendVideoNotes && c.CanSendVoiceNotes +} + // ChatLocation represents a location to which a chat is connected. type ChatLocation struct { // Location is the location to which the supergroup is connected. Can't be a From 3ba8237c47b151719152756b24ee5cc0b0281174 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sat, 11 Feb 2023 19:11:26 +0200 Subject: [PATCH 06/70] Fix: missing json tag in UserShared and ChatShared --- types.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types.go b/types.go index bf3d62d6..97fce226 100644 --- a/types.go +++ b/types.go @@ -1337,7 +1337,7 @@ type UserShared struct { // RequestID is an indentifier of the request. RequestID int `json:"request_id"` // UserID in an identifier of the shared user. - UserID int64 + UserID int64 `json:"user_id"` } // ChatShared contains information about the chat whose identifier @@ -1346,7 +1346,7 @@ type ChatShared struct { // RequestID is an indentifier of the request. RequestID int `json:"request_id"` // ChatID is an identifier of the shared chat. - ChatID int64 + ChatID int64 `json:"chat_id"` } // WriteAccessAllowed represents a service message about a user From ef8307cc42d0aca04fcc928dc6b7d36859ef4858 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Tue, 4 Jul 2023 22:21:43 +0300 Subject: [PATCH 07/70] BOT API 6.6 implementation --- configs.go | 259 ++++++++++++++++++++++++++++++++++++++++++++++------- helpers.go | 55 +++++++++++- types.go | 94 ++++++++++++------- 3 files changed, 343 insertions(+), 65 deletions(-) diff --git a/configs.go b/configs.go index 09c9c468..c0074269 100644 --- a/configs.go +++ b/configs.go @@ -463,7 +463,7 @@ func (config PhotoConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -511,7 +511,7 @@ func (config AudioConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -551,7 +551,7 @@ func (config DocumentConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -561,11 +561,18 @@ func (config DocumentConfig) files() []RequestFile { // StickerConfig contains information about a SendSticker request. type StickerConfig struct { + //Emoji associated with the sticker; only for just uploaded stickers + Emoji string BaseFile } func (config StickerConfig) params() (Params, error) { - return config.BaseChat.params() + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + params.AddNonEmpty("emoji", config.Emoji) + return params, err } func (config StickerConfig) method() string { @@ -627,7 +634,7 @@ func (config VideoConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -681,7 +688,7 @@ func (config AnimationConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -718,7 +725,7 @@ func (config VideoNoteConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -762,7 +769,7 @@ func (config VoiceConfig) files() []RequestFile { if config.Thumb != nil { files = append(files, RequestFile{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }) } @@ -2139,8 +2146,9 @@ func (config GetCustomEmojiStickersConfig) method() string { // UploadStickerConfig allows you to upload a sticker for use in a set later. type UploadStickerConfig struct { - UserID int64 - PNGSticker RequestFileData + UserID int64 + Sticker RequestFile + StickerFormat string } func (config UploadStickerConfig) method() string { @@ -2151,6 +2159,7 @@ func (config UploadStickerConfig) params() (Params, error) { params := make(Params) params.AddNonZero64("user_id", config.UserID) + params["sticker_format"] = config.StickerFormat return params, nil } @@ -2166,15 +2175,12 @@ func (config UploadStickerConfig) files() []RequestFile { // // You must set either PNGSticker or TGSSticker. type NewStickerSetConfig struct { - UserID int64 - Name string - Title string - PNGSticker RequestFileData - TGSSticker RequestFileData - StickerType string - Emojis string - ContainsMasks bool // deprecated - MaskPosition *MaskPosition + UserID int64 + Name string + Title string + Stickers []InputSticker + StickerType string + NeedsRepainting bool //optional; 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 } func (config NewStickerSetConfig) method() string { @@ -2187,11 +2193,10 @@ func (config NewStickerSetConfig) params() (Params, error) { params.AddNonZero64("user_id", config.UserID) params["name"] = config.Name params["title"] = config.Title - params["emojis"] = config.Emojis - params.AddBool("contains_masks", config.ContainsMasks) + params.AddBool("needs_repainting", config.NeedsRepainting) params.AddNonEmpty("sticker_type", string(config.StickerType)) - err := params.AddInterface("mask_position", config.MaskPosition) + err := params.AddInterface("stickers", config.Stickers) return params, err } @@ -2212,12 +2217,9 @@ func (config NewStickerSetConfig) files() []RequestFile { // AddStickerConfig allows you to add a sticker to a set. type AddStickerConfig struct { - UserID int64 - Name string - PNGSticker RequestFileData - TGSSticker RequestFileData - Emojis string - MaskPosition *MaskPosition + UserID int64 + Name string + Sticker InputSticker } func (config AddStickerConfig) method() string { @@ -2229,10 +2231,7 @@ func (config AddStickerConfig) params() (Params, error) { params.AddNonZero64("user_id", config.UserID) params["name"] = config.Name - params["emojis"] = config.Emojis - - err := params.AddInterface("mask_position", config.MaskPosition) - + err := params.AddInterface("sticker", config.Sticker) return params, err } @@ -2270,6 +2269,61 @@ func (config SetStickerPositionConfig) params() (Params, error) { return params, nil } +// SetCustomEmojiStickerSetThumbnalConfig allows you to set the thumbnail of a custom emoji sticker set +type SetCustomEmojiStickerSetThumbnalConfig struct { + Name string + CustomEmojiID string +} + +func (config SetCustomEmojiStickerSetThumbnalConfig) method() string { + return "setCustomEmojiStickerSetThumbnail" +} + +func (config SetCustomEmojiStickerSetThumbnalConfig) params() (Params, error) { + params := make(Params) + + params["name"] = config.Name + params.AddNonEmpty("position", config.CustomEmojiID) + + return params, nil +} + +// SetStickerSetTitle allows you to set the title of a created sticker set +type SetStickerSetTitleConfig struct { + Name string + Title string +} + +func (config SetStickerSetTitleConfig) method() string { + return "setStickerSetTitle" +} + +func (config SetStickerSetTitleConfig) params() (Params, error) { + params := make(Params) + + params["name"] = config.Name + params["title"] = config.Title + + return params, nil +} + +// DeleteStickerSetConfig allows you to delete a sticker set that was created by the bot. +type DeleteStickerSetConfig struct { + Name string +} + +func (config DeleteStickerSetConfig) method() string { + return "deleteStickerSet" +} + +func (config DeleteStickerSetConfig) params() (Params, error) { + params := make(Params) + + params["name"] = config.Name + + return params, nil +} + // DeleteStickerConfig allows you to delete a sticker from a set. type DeleteStickerConfig struct { Sticker string @@ -2287,6 +2341,63 @@ func (config DeleteStickerConfig) params() (Params, error) { return params, nil } +// SetStickerEmojiListConfig allows you 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 +type SetStickerEmojiListConfig struct { + Sticker string + EmojiList []string +} + +func (config SetStickerEmojiListConfig) method() string { + return "setStickerEmojiList" +} + +func (config SetStickerEmojiListConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + err := params.AddInterface("emoji_list", config.EmojiList) + + return params, err +} + +// SetStickerKeywordsConfig allows you to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. +type SetStickerKeywordsConfig struct { + Sticker string + Keywords []string +} + +func (config SetStickerKeywordsConfig) method() string { + return "setStickerKeywords" +} + +func (config SetStickerKeywordsConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + err := params.AddInterface("keywords", config.Keywords) + + return params, err +} + +// SetStickerMaskPositionConfig allows you to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot +type SetStickerMaskPositionConfig struct { + Sticker string + MaskPosition *MaskPosition +} + +func (config SetStickerMaskPositionConfig) method() string { + return "setStickerMaskPosition" +} + +func (config SetStickerMaskPositionConfig) params() (Params, error) { + params := make(Params) + + params["sticker"] = config.Sticker + err := params.AddInterface("keywords", config.MaskPosition) + + return params, err +} + // SetStickerSetThumbConfig allows you to set the thumbnail for a sticker set. type SetStickerSetThumbConfig struct { Name string @@ -2295,7 +2406,7 @@ type SetStickerSetThumbConfig struct { } func (config SetStickerSetThumbConfig) method() string { - return "setStickerSetThumb" + return "setStickerSetThumbnail" } func (config SetStickerSetThumbConfig) params() (Params, error) { @@ -2309,7 +2420,7 @@ func (config SetStickerSetThumbConfig) params() (Params, error) { func (config SetStickerSetThumbConfig) files() []RequestFile { return []RequestFile{{ - Name: "thumb", + Name: "thumbnail", Data: config.Thumb, }} } @@ -2704,6 +2815,86 @@ func (config DeleteMyCommandsConfig) params() (Params, error) { return params, err } +// GetMyDescriptionConfig get the current bot description for the given user language +type GetMyDescriptionConfig struct { + LanguageCode string +} + +func (config GetMyDescriptionConfig) method() string { + return "getMyDescription" +} + +func (config GetMyDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// SetMyDescroptionConfig sets the bot's description, which is shown in the chat with the bot if the chat is empty +type SetMyDescriptionConfig struct { + // Pass an empty string to remove the dedicated description for the given language. + Description string + //If empty, the description will be applied to all users for whose language there is no dedicated description. + LanguageCode string +} + +func (config SetMyDescriptionConfig) method() string { + return "setMyDescription" +} + +func (config SetMyDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("description", config.Description) + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// GetMyShortDescriptionConfig get the current bot short description for the given user language +type GetMyShortDescriptionConfig struct { + LanguageCode string +} + +func (config GetMyShortDescriptionConfig) method() string { + return "getMyShortDescription" +} + +func (config GetMyShortDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +// SetMyDescroptionConfig sets 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. +type SetMyShortDescriptionConfig 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 + //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 +} + +func (config SetMyShortDescriptionConfig) method() string { + return "setMyDescription" +} + +func (config SetMyShortDescriptionConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("short_description", config.ShortDescription) + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + // SetChatMenuButtonConfig changes the bot's menu button in a private chat, // or the default menu button. type SetChatMenuButtonConfig struct { diff --git a/helpers.go b/helpers.go index bdf2ee97..79028392 100644 --- a/helpers.go +++ b/helpers.go @@ -130,6 +130,29 @@ func NewSticker(chatID int64, file RequestFileData) StickerConfig { } } +// NewCustomEmojiStickerSetThumbnal creates a new setCustomEmojiStickerSetThumbnal request +func NewCustomEmojiStickerSetThumbnal(name, customEmojiID string) SetCustomEmojiStickerSetThumbnalConfig { + return SetCustomEmojiStickerSetThumbnalConfig{ + Name: name, + CustomEmojiID: customEmojiID, + } +} + +// NewStickerSetTitle creates a new setStickerSetTitle request +func NewStickerSetTitle(name, title string) SetStickerSetTitleConfig { + return SetStickerSetTitleConfig{ + Name: name, + Title: title, + } +} + +// NewDeleteStickerSet creates a new deleteStickerSet request +func NewDeleteStickerSet(name, title string) DeleteStickerSetConfig { + return DeleteStickerSetConfig{ + Name: name, + } +} + // NewVideo creates a new sendVideo request. func NewVideo(chatID int64, file RequestFileData) VideoConfig { return VideoConfig{ @@ -181,7 +204,7 @@ func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { BaseChat: BaseChat{ ChatID: chatID, }, - Media: files, + Media: files, } } @@ -908,6 +931,36 @@ func NewBotCommandScopeChatMember(chatID, userID int64) BotCommandScope { } } +// NewSetMyDescription allows you to change the bot's description, which is shown in the chat with the bot if the chat is empty. +func NewSetMyDescription(description, languageCode string) SetMyDescriptionConfig { + return SetMyDescriptionConfig{ + Description: description, + LanguageCode: languageCode, + } +} + +// NewGetMyDescription returns the current bot description for the given user language +func NewGetMyDescription(languageCode string) GetMyDescriptionConfig { + return GetMyDescriptionConfig{ + LanguageCode: languageCode, + } +} + +// NewSetMyShortDescription allows you 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. +func NewSetMyShortDescription(shortDescription, languageCode string) SetMyShortDescriptionConfig { + return SetMyShortDescriptionConfig{ + ShortDescription: shortDescription, + LanguageCode: languageCode, + } +} + +// NewGetMyShortDescription returns the current bot short description for the given user language. +func NewGetMyShortDescription(languageCode string) GetMyShortDescriptionConfig { + return GetMyShortDescriptionConfig{ + LanguageCode: languageCode, + } +} + // NewGetMyCommandsWithScope allows you to set the registered commands for a // given scope. func NewGetMyCommandsWithScope(scope BotCommandScope) GetMyCommandsConfig { diff --git a/types.go b/types.go index 97fce226..780fd6ef 100644 --- a/types.go +++ b/types.go @@ -953,7 +953,7 @@ type Animation struct { // Thumbnail animation thumbnail as defined by sender // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileName original animation filename as defined by sender // // optional @@ -1002,7 +1002,7 @@ type Audio struct { // Thumbnail is the album cover to which the music file belongs // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` } // Document represents a general file. @@ -1017,7 +1017,7 @@ type Document struct { // Thumbnail document thumbnail as defined by sender // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileName original filename as defined by sender // // optional @@ -1050,7 +1050,7 @@ type Video struct { // Thumbnail video thumbnail // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileName is the original filename as defined by sender // // optional @@ -1080,7 +1080,7 @@ type VideoNote struct { // Thumbnail video thumbnail // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // FileSize file size // // optional @@ -2212,6 +2212,16 @@ type BotCommandScope struct { UserID int64 `json:"user_id,omitempty"` } +// BotDescription represents the bot's description. +type BotDescription struct { + Description string `json:"description"` +} + +// BotShortDescription represents the bot's short description +type BotShortDescription struct { + ShortDescription string `json:"short_description"` +} + // MenuButton describes the bot's menu button in a private chat. type MenuButton struct { // Type is the type of menu button, must be one of: @@ -2284,7 +2294,7 @@ type InputMediaVideo struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // Width video width // // optional @@ -2314,7 +2324,7 @@ type InputMediaAnimation struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // Width video width // // optional @@ -2340,7 +2350,7 @@ type InputMediaAudio struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // Duration of the audio in seconds // // optional @@ -2362,7 +2372,7 @@ type InputMediaDocument struct { // the file is supported server-side. // // optional - Thumb RequestFileData `json:"thumb,omitempty"` + Thumb RequestFileData `json:"thumbnail,omitempty"` // DisableContentTypeDetection 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 @@ -2406,7 +2416,7 @@ type Sticker struct { // Thumbnail sticker thumbnail in the .WEBP or .JPG format // // optional - Thumbnail *PhotoSize `json:"thumb,omitempty"` + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` // Emoji associated with the sticker // // optional @@ -2428,6 +2438,10 @@ type Sticker struct { // // optional CustomEmojiID string `json:"custom_emoji_id,omitempty"` + // NeedsRepainting 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 + // + //optional + NeedsRepainting bool `json:"needs_reainting,omitempty"` // FileSize // // optional @@ -2468,7 +2482,7 @@ type StickerSet struct { // Stickers list of all set stickers Stickers []Sticker `json:"stickers"` // Thumb is the sticker set thumbnail in the .WEBP or .TGS format - Thumbnail *PhotoSize `json:"thumb"` + Thumbnail *PhotoSize `json:"thumbnail"` } // IsRegular returns if the StickerSet is regular @@ -2504,6 +2518,22 @@ type MaskPosition struct { Scale float64 `json:"scale"` } +// InputSticker describes a sticker to be added to a sticker set. +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, upload a new one using multipart/form-data, or pass “attach://” to upload a new one using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. + Sticker RequestFile `json:"sticker"` + // List of 1-20 emoji associated with the sticker + EmojiList []string `json:"emoji_list"` + // Position where the mask should be placed on faces. For “mask” stickers only. + // + // optional + MaskPosition *MaskPosition `json:"mask_position"` + // List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only. + // + // optional + Keywords []string `json:"keywords"` +} + // Game represents a game. Use BotFather to create and edit games, their short // names will act as unique identifiers. type Game struct { @@ -2923,15 +2953,15 @@ type InlineQueryResultArticle struct { // ThumbURL url of the thumbnail for the result // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultAudio is an inline query response audio. @@ -2987,9 +3017,9 @@ type InlineQueryResultContact struct { VCard string `json:"vcard"` ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` InputMessageContent interface{} `json:"input_message_content,omitempty"` - ThumbURL string `json:"thumb_url"` - ThumbWidth int `json:"thumb_width"` - ThumbHeight int `json:"thumb_height"` + ThumbURL string `json:"thumbnail_url"` + ThumbWidth int `json:"thumbnail_width"` + ThumbHeight int `json:"thumbnail_height"` } // InlineQueryResultGame is an inline query response game. @@ -3037,15 +3067,15 @@ type InlineQueryResultDocument struct { // ThumbURL url of the thumbnail (jpeg only) for the file // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultGIF is an inline query response GIF. @@ -3057,7 +3087,9 @@ type InlineQueryResultGIF struct { // URL a valid URL for the GIF file. File size must not exceed 1MB. URL string `json:"gif_url"` // ThumbURL url of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result. - ThumbURL string `json:"thumb_url"` + ThumbURL string `json:"thumbnail_url"` + // MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” + ThumbMimeType string `json:"thumbnail_mime_type,omitempty"` // Width of the GIF // // optional @@ -3143,15 +3175,15 @@ type InlineQueryResultLocation struct { // ThumbURL url of the thumbnail for the result // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF. @@ -3175,7 +3207,9 @@ type InlineQueryResultMPEG4GIF struct { // optional Duration int `json:"mpeg4_duration,omitempty"` // ThumbURL url of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result. - ThumbURL string `json:"thumb_url"` + ThumbURL string `json:"thumbnail_url"` + // MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” + ThumbMimeType string `json:"thumbnail_mime_type,omitempty"` // Title for the result // // optional @@ -3227,7 +3261,7 @@ type InlineQueryResultPhoto struct { // ThumbURL url of the thumbnail for the photo. // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // Title for the result // // optional @@ -3303,15 +3337,15 @@ type InlineQueryResultVenue struct { // ThumbURL url of the thumbnail for the result // // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // ThumbWidth thumbnail width // // optional - ThumbWidth int `json:"thumb_width,omitempty"` + ThumbWidth int `json:"thumbnail_width,omitempty"` // ThumbHeight thumbnail height // // optional - ThumbHeight int `json:"thumb_height,omitempty"` + ThumbHeight int `json:"thumbnail_height,omitempty"` } // InlineQueryResultVideo is an inline query response video. @@ -3327,7 +3361,7 @@ type InlineQueryResultVideo struct { // // ThumbURL url of the thumbnail (jpeg only) for the video // optional - ThumbURL string `json:"thumb_url,omitempty"` + ThumbURL string `json:"thumbnail_url,omitempty"` // Title for the result Title string `json:"title"` // Caption of the video to be sent, 0-1024 characters after entities parsing From a4b5cdb16fde6853486990878f019251eca5c542 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Tue, 4 Jul 2023 22:38:56 +0300 Subject: [PATCH 08/70] add field --- configs.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/configs.go b/configs.go index c0074269..7973bacb 100644 --- a/configs.go +++ b/configs.go @@ -2179,6 +2179,7 @@ type NewStickerSetConfig struct { Name string Title string Stickers []InputSticker + StickerFormat string StickerType string NeedsRepainting bool //optional; 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 } @@ -2193,6 +2194,7 @@ func (config NewStickerSetConfig) params() (Params, error) { params.AddNonZero64("user_id", config.UserID) params["name"] = config.Name params["title"] = config.Title + params["sticker_format"] = config.StickerFormat params.AddBool("needs_repainting", config.NeedsRepainting) params.AddNonEmpty("sticker_type", string(config.StickerType)) From 2d0a34c34b2947e8f12372d6e1c56fd5bed01673 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Tue, 4 Jul 2023 23:00:35 +0300 Subject: [PATCH 09/70] Add types_tests for bot api 6.6 and replace PNGSticker and TGSSticker with the parameters sticker --- configs.go | 34 ++++++---------------------------- types_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+), 28 deletions(-) diff --git a/configs.go b/configs.go index 7973bacb..5ca9e43e 100644 --- a/configs.go +++ b/configs.go @@ -2165,15 +2165,10 @@ func (config UploadStickerConfig) params() (Params, error) { } func (config UploadStickerConfig) files() []RequestFile { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} + return []RequestFile{config.Sticker} } // NewStickerSetConfig allows creating a new sticker set. -// -// You must set either PNGSticker or TGSSticker. type NewStickerSetConfig struct { UserID int64 Name string @@ -2204,17 +2199,11 @@ func (config NewStickerSetConfig) params() (Params, error) { } func (config NewStickerSetConfig) files() []RequestFile { - if config.PNGSticker != nil { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} + requestFiles := []RequestFile{} + for _, v := range config.Stickers { + requestFiles = append(requestFiles, v.Sticker) } - - return []RequestFile{{ - Name: "tgs_sticker", - Data: config.TGSSticker, - }} + return requestFiles } // AddStickerConfig allows you to add a sticker to a set. @@ -2238,18 +2227,7 @@ func (config AddStickerConfig) params() (Params, error) { } func (config AddStickerConfig) files() []RequestFile { - if config.PNGSticker != nil { - return []RequestFile{{ - Name: "png_sticker", - Data: config.PNGSticker, - }} - } - - return []RequestFile{{ - Name: "tgs_sticker", - Data: config.TGSSticker, - }} - + return []RequestFile{config.Sticker.Sticker} } // SetStickerPositionConfig allows you to change the position of a sticker in a set. diff --git a/types_test.go b/types_test.go index 2dfe1d1a..e4e3da16 100644 --- a/types_test.go +++ b/types_test.go @@ -359,6 +359,16 @@ var ( _ Chattable = ReopenGeneralForumTopicConfig{} _ Chattable = HideGeneralForumTopicConfig{} _ Chattable = UnhideGeneralForumTopicConfig{} + _ Chattable = SetCustomEmojiStickerSetThumbnalConfig{} + _ Chattable = SetStickerSetTitleConfig{} + _ Chattable = DeleteStickerSetConfig{} + _ Chattable = SetStickerEmojiListConfig{} + _ Chattable = SetStickerKeywordsConfig{} + _ Chattable = SetStickerMaskPositionConfig{} + _ Chattable = GetMyDescriptionConfig{} + _ Chattable = SetMyDescriptionConfig{} + _ Chattable = GetMyShortDescriptionConfig{} + _ Chattable = SetMyShortDescriptionConfig{} ) // Ensure all Fileable types are correct. From 7d82083b039394e83ef7319853e29a3d4ef66b60 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Wed, 5 Jul 2023 11:23:14 +0300 Subject: [PATCH 10/70] BOT API 6.7 implementation --- configs.go | 71 ++++++++++++++++++++++++++++++++++++++++++------- helpers.go | 24 +++++++++++++++++ helpers_test.go | 19 +++++++++++++ types.go | 47 +++++++++++++++++++++++++++++--- types_test.go | 2 ++ 5 files changed, 150 insertions(+), 13 deletions(-) diff --git a/configs.go b/configs.go index 5ca9e43e..d2b22d9a 100644 --- a/configs.go +++ b/configs.go @@ -1271,15 +1271,29 @@ func (config DeleteWebhookConfig) params() (Params, error) { return params, nil } +// InlineQueryResultsButton represents a button to be shown above inline query results. You must use exactly one of the optional fields. +type InlineQueryResultsButton struct { + //Label 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 switch back to the inline mode using the method switchInlineQuery inside the Web App. + // + //Optional + WebApp *WebAppInfo `json:"web_app,omitempty"` + // 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. + // + //Optional + StartParam string `json:"start_parameter,omitempty"` +} + // InlineConfig contains information on making an InlineQuery response. type InlineConfig struct { - InlineQueryID string `json:"inline_query_id"` - Results []interface{} `json:"results"` - CacheTime int `json:"cache_time"` - IsPersonal bool `json:"is_personal"` - NextOffset string `json:"next_offset"` - SwitchPMText string `json:"switch_pm_text"` - SwitchPMParameter string `json:"switch_pm_parameter"` + InlineQueryID string `json:"inline_query_id"` + Results []interface{} `json:"results"` + CacheTime int `json:"cache_time"` + IsPersonal bool `json:"is_personal"` + NextOffset string `json:"next_offset"` + Button *InlineQueryResultsButton `json:"button,omitempty"` } func (config InlineConfig) method() string { @@ -1293,9 +1307,11 @@ func (config InlineConfig) params() (Params, error) { params.AddNonZero("cache_time", config.CacheTime) params.AddBool("is_personal", config.IsPersonal) params.AddNonEmpty("next_offset", config.NextOffset) - params.AddNonEmpty("switch_pm_text", config.SwitchPMText) - params.AddNonEmpty("switch_pm_parameter", config.SwitchPMParameter) - err := params.AddInterface("results", config.Results) + err := params.AddInterface("button", config.Button) + if err != nil { + return params, err + } + err = params.AddInterface("results", config.Results) return params, err } @@ -2795,6 +2811,41 @@ func (config DeleteMyCommandsConfig) params() (Params, error) { return params, err } +// SetMyNameConfig change the bot's name +type SetMyNameConfig struct { + Name string + LanguageCode string +} + +func (config SetMyNameConfig) method() string { + return "setMyName" +} + +func (config SetMyNameConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("name", config.Name) + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + +type GetMyNameConfig struct { + LanguageCode string +} + +func (config GetMyNameConfig) method() string { + return "getMyName" +} + +func (config GetMyNameConfig) params() (Params, error) { + params := make(Params) + + params.AddNonEmpty("language_code", config.LanguageCode) + + return params, nil +} + // GetMyDescriptionConfig get the current bot description for the given user language type GetMyDescriptionConfig struct { LanguageCode string diff --git a/helpers.go b/helpers.go index 79028392..4c7a0744 100644 --- a/helpers.go +++ b/helpers.go @@ -723,6 +723,15 @@ func NewInlineKeyboardButtonWebApp(text string, webapp WebAppInfo) InlineKeyboar } } +// NewInlineKeyboardButtonSwitchInlineQueryChoosenChat creates an inline keyboard button with text +// which goes to a SwitchInlineQueryChosenChat. +func NewInlineKeyboardButtonSwitchInlineQueryChoosenChat(text string, switchInlineQueryChosenChat SwitchInlineQueryChosenChat) InlineKeyboardButton { + return InlineKeyboardButton{ + Text: text, + SwitchInlineQueryChosenChat: &switchInlineQueryChosenChat, + } +} + // NewInlineKeyboardButtonLoginURL creates an inline keyboard button with text // which goes to a LoginURL. func NewInlineKeyboardButtonLoginURL(text string, loginURL LoginURL) InlineKeyboardButton { @@ -961,6 +970,21 @@ func NewGetMyShortDescription(languageCode string) GetMyShortDescriptionConfig { } } +// NewGetMyName get the current bot name for the given user language +func NewGetMyName(languageCode string) GetMyNameConfig { + return GetMyNameConfig{ + LanguageCode: languageCode, + } +} + +// NewSetMyName change the bot's name +func NewSetMyName(languageCode, name string) SetMyNameConfig { + return SetMyNameConfig{ + Name: name, + LanguageCode: languageCode, + } +} + // NewGetMyCommandsWithScope allows you to set the registered commands for a // given scope. func NewGetMyCommandsWithScope(scope BotCommandScope) GetMyCommandsConfig { diff --git a/helpers_test.go b/helpers_test.go index 9119543d..fe8098e0 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -178,6 +178,25 @@ func TestNewInlineKeyboardButtonLoginURL(t *testing.T) { } } +func TestNewInlineKeyboardButtonSwitchInlineQueryChoosenChat(t *testing.T) { + result := NewInlineKeyboardButtonSwitchInlineQueryChoosenChat("text", SwitchInlineQueryChosenChat{ + Query: "query", + AllowUserChats: false, + AllowBotChats: false, + AllowGroupChats: false, + AllowChannelChats: false, + }) + + if result.Text != "text" || + result.SwitchInlineQueryChosenChat.Query != "query" || + result.SwitchInlineQueryChosenChat.AllowUserChats != false || + result.SwitchInlineQueryChosenChat.AllowBotChats != false || + result.SwitchInlineQueryChosenChat.AllowGroupChats != false || + result.SwitchInlineQueryChosenChat.AllowChannelChats != false { + t.Fail() + } +} + func TestNewEditMessageText(t *testing.T) { edit := NewEditMessageText(ChatID, ReplyToMessageID, "new text") diff --git a/types.go b/types.go index 780fd6ef..c97b176e 100644 --- a/types.go +++ b/types.go @@ -1349,10 +1349,14 @@ type ChatShared struct { ChatID int64 `json:"chat_id"` } -// WriteAccessAllowed represents a service message about a user -// allowing a bot added to the attachment menu to write messages. -// Currently holds no information. +// WriteAccessAllowed represents a service message about a user allowing a bot +// to write messages after adding the bot to the attachment menu or launching +// a Web App from a link. type WriteAccessAllowed struct { + //Name of the Web App which was launched from a link + // + // Optional + WebAppName string `json:"web_app_name"` } // VideoChatScheduled represents a service message about a voice chat scheduled @@ -1677,6 +1681,12 @@ type InlineKeyboardButton struct { // // optional SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` + //SwitchInlineQueryChosenChat 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 + // + //optional + SwitchInlineQueryChosenChat *SwitchInlineQueryChosenChat `json:"switch_inline_query_chosen_chat,omitempty"` // CallbackGame description of the game that will be launched when the user presses the button. // // optional @@ -2056,6 +2066,11 @@ type ChatMemberUpdated struct { // // optional InviteLink *ChatInviteLink `json:"invite_link,omitempty"` + // ViaChatFolderInviteLink is True, if the user joined the chat + // via a chat folder invite link + // + // optional + ViaChatFolderInviteLink bool `json:"via_chat_folder_invite_link,omitempty"` } // ChatJoinRequest represents a join request sent to a chat. @@ -2573,6 +2588,32 @@ type GameHighScore struct { // CallbackGame is for starting a game in an inline keyboard button. type CallbackGame struct{} +// SwitchInlineQueryChosenChat represents an inline button that switches the current +// user to inline mode in a chosen chat, with an optional default inline query. +type SwitchInlineQueryChosenChat struct { + // Query is default inline query to be inserted in the input field. + // If left empty, only the bot's username will be inserted + // + // optional + Query string `json:"query,omitempty"` + // AllowUserChats is True, if private chats with users can be chosen + // + // optional + AllowUserChats bool `json:"allow_user_chats,omitempty"` + // AllowBotChats is True, if private chats with bots can be chosen + // + // optional + AllowBotChats bool `json:"allow_bot_chats,omitempty"` + // AllowGroupChats is True, if group and supergroup chats can be chosen + // + // optional + AllowGroupChats bool `json:"allow_group_chats,omitempty"` + // AllowChannelChats is True, if channel chats can be chosen + // + // optional + AllowChannelChats bool `json:"allow_channel_chats,omitempty"` +} + // WebhookInfo is information about a currently set webhook. type WebhookInfo struct { // URL webhook URL, may be empty if webhook is not set up. diff --git a/types_test.go b/types_test.go index e4e3da16..69c05937 100644 --- a/types_test.go +++ b/types_test.go @@ -369,6 +369,8 @@ var ( _ Chattable = SetMyDescriptionConfig{} _ Chattable = GetMyShortDescriptionConfig{} _ Chattable = SetMyShortDescriptionConfig{} + _ Chattable = GetMyNameConfig{} + _ Chattable = SetMyNameConfig{} ) // Ensure all Fileable types are correct. From 45f563879fbcfee2a821f03039e4eaf16074033e Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Wed, 5 Jul 2023 12:13:57 +0300 Subject: [PATCH 11/70] Add omitempty to optional fields --- configs.go | 1 - types.go | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/configs.go b/configs.go index d2b22d9a..87e16334 100644 --- a/configs.go +++ b/configs.go @@ -1274,7 +1274,6 @@ func (config DeleteWebhookConfig) params() (Params, error) { // InlineQueryResultsButton represents a button to be shown above inline query results. You must use exactly one of the optional fields. type InlineQueryResultsButton struct { //Label 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 switch back to the inline mode using the method switchInlineQuery inside the Web App. // diff --git a/types.go b/types.go index c97b176e..7cf3b060 100644 --- a/types.go +++ b/types.go @@ -1356,7 +1356,7 @@ type WriteAccessAllowed struct { //Name of the Web App which was launched from a link // // Optional - WebAppName string `json:"web_app_name"` + WebAppName string `json:"web_app_name,omitempty"` } // VideoChatScheduled represents a service message about a voice chat scheduled From dcd469ffa55d2df26d583b5474bf54cbc4ca2f06 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Tue, 11 Jul 2023 12:04:24 +0300 Subject: [PATCH 12/70] Add nil check in method '(*Update).FromChat', for type CallbackQuery. --- types.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types.go b/types.go index 7cf3b060..b70d6140 100644 --- a/types.go +++ b/types.go @@ -158,7 +158,7 @@ func (u *Update) FromChat() *Chat { return u.ChannelPost.Chat case u.EditedChannelPost != nil: return u.EditedChannelPost.Chat - case u.CallbackQuery != nil: + case u.CallbackQuery != nil && u.CallbackQuery.Message != nil: return u.CallbackQuery.Message.Chat default: return nil From 10078d149287c57e4eb9bf34848ebf872324b001 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Tue, 11 Jul 2023 12:12:23 +0300 Subject: [PATCH 13/70] Fix typo in the name of config struct SetCustomEmojiStickerSetThumbnailConfig. --- configs.go | 8 ++++---- helpers.go | 4 ++-- types_test.go | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/configs.go b/configs.go index 87e16334..523c5395 100644 --- a/configs.go +++ b/configs.go @@ -2264,17 +2264,17 @@ func (config SetStickerPositionConfig) params() (Params, error) { return params, nil } -// SetCustomEmojiStickerSetThumbnalConfig allows you to set the thumbnail of a custom emoji sticker set -type SetCustomEmojiStickerSetThumbnalConfig struct { +// SetCustomEmojiStickerSetThumbnailConfig allows you to set the thumbnail of a custom emoji sticker set +type SetCustomEmojiStickerSetThumbnailConfig struct { Name string CustomEmojiID string } -func (config SetCustomEmojiStickerSetThumbnalConfig) method() string { +func (config SetCustomEmojiStickerSetThumbnailConfig) method() string { return "setCustomEmojiStickerSetThumbnail" } -func (config SetCustomEmojiStickerSetThumbnalConfig) params() (Params, error) { +func (config SetCustomEmojiStickerSetThumbnailConfig) params() (Params, error) { params := make(Params) params["name"] = config.Name diff --git a/helpers.go b/helpers.go index 4c7a0744..4001d432 100644 --- a/helpers.go +++ b/helpers.go @@ -131,8 +131,8 @@ func NewSticker(chatID int64, file RequestFileData) StickerConfig { } // NewCustomEmojiStickerSetThumbnal creates a new setCustomEmojiStickerSetThumbnal request -func NewCustomEmojiStickerSetThumbnal(name, customEmojiID string) SetCustomEmojiStickerSetThumbnalConfig { - return SetCustomEmojiStickerSetThumbnalConfig{ +func NewCustomEmojiStickerSetThumbnal(name, customEmojiID string) SetCustomEmojiStickerSetThumbnailConfig { + return SetCustomEmojiStickerSetThumbnailConfig{ Name: name, CustomEmojiID: customEmojiID, } diff --git a/types_test.go b/types_test.go index 69c05937..90d01eae 100644 --- a/types_test.go +++ b/types_test.go @@ -359,7 +359,7 @@ var ( _ Chattable = ReopenGeneralForumTopicConfig{} _ Chattable = HideGeneralForumTopicConfig{} _ Chattable = UnhideGeneralForumTopicConfig{} - _ Chattable = SetCustomEmojiStickerSetThumbnalConfig{} + _ Chattable = SetCustomEmojiStickerSetThumbnailConfig{} _ Chattable = SetStickerSetTitleConfig{} _ Chattable = DeleteStickerSetConfig{} _ Chattable = SetStickerEmojiListConfig{} From 32982cf4333523632cbfda5b6bd9bea958124010 Mon Sep 17 00:00:00 2001 From: OvyFlash <46941696+OvyFlash@users.noreply.github.com> Date: Sun, 13 Aug 2023 13:34:33 +0300 Subject: [PATCH 14/70] Wrong method for SetMyShortDescriptionConfig Co-authored-by: Paolo Rossi --- configs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs.go b/configs.go index 523c5395..3bde6fa8 100644 --- a/configs.go +++ b/configs.go @@ -2913,7 +2913,7 @@ type SetMyShortDescriptionConfig struct { } func (config SetMyShortDescriptionConfig) method() string { - return "setMyDescription" + return "setMyShortDescription" } func (config SetMyShortDescriptionConfig) params() (Params, error) { From 48d380a129adde957c62c2d75b4a0f0a88aa6cf9 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Mon, 16 Oct 2023 20:24:40 +0300 Subject: [PATCH 15/70] Add 'BotName' type to available types. --- types.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types.go b/types.go index b70d6140..476e904c 100644 --- a/types.go +++ b/types.go @@ -2227,6 +2227,11 @@ type BotCommandScope struct { UserID int64 `json:"user_id,omitempty"` } +//BotName represents the bot's name. +type BotName struct { + Name string `json:"name"` +} + // BotDescription represents the bot's description. type BotDescription struct { Description string `json:"description"` From 371d8b695f367525262fa97a8833a1bc0ed814e0 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Mon, 30 Oct 2023 16:04:47 +0200 Subject: [PATCH 16/70] Add const for 'chat_join_request' update type --- configs.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/configs.go b/configs.go index 3bde6fa8..301f4388 100644 --- a/configs.go +++ b/configs.go @@ -92,6 +92,10 @@ const ( // UpdateTypeChatMember is when the bot must be an administrator in the chat and must explicitly specify // this update in the list of allowed_updates to receive these updates. UpdateTypeChatMember = "chat_member" + + // UpdateTypeChatJoinRequest is request to join the chat has been sent. + // The bot must have the can_invite_users administrator right in the chat to receive these updates. + UpdateTypeChatJoinRequest = "chat_join_request" ) // Library errors From 17d3e395d52d40e76b22f043424937a4e8d2f58c Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sat, 30 Dec 2023 16:55:43 +0200 Subject: [PATCH 17/70] BOT API 6.8 implementation --- configs.go | 13 ++++++++++++- types.go | 28 ++++++++++++++++++++++++---- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/configs.go b/configs.go index 301f4388..a6adaac7 100644 --- a/configs.go +++ b/configs.go @@ -93,7 +93,7 @@ const ( // this update in the list of allowed_updates to receive these updates. UpdateTypeChatMember = "chat_member" - // UpdateTypeChatJoinRequest is request to join the chat has been sent. + // UpdateTypeChatJoinRequest is request to join the chat has been sent. // The bot must have the can_invite_users administrator right in the chat to receive these updates. UpdateTypeChatJoinRequest = "chat_join_request" ) @@ -2697,6 +2697,17 @@ func (config UnhideGeneralForumTopicConfig) method() string { return "unhideGeneralForumTopic" } +// UnpinAllGeneralForumTopicMessagesConfig allows you to 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. +type UnpinAllGeneralForumTopicMessagesConfig struct{ BaseForum } + +func (config UnpinAllGeneralForumTopicMessagesConfig) method() string { + return "unpinAllGeneralForumTopicMessages" +} + // MediaGroupConfig allows you to send a group of media. // // Media consist of InputMedia items (InputMediaPhoto, InputMediaVideo). diff --git a/types.go b/types.go index 476e904c..ba26ebe2 100644 --- a/types.go +++ b/types.go @@ -281,6 +281,11 @@ type Chat struct { // // optional EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` + // Expiration date of the emoji status of the chat or the other party + // in a private chat, in Unix time, if any. Returned only in getChat. + // + // optional + EmojiStatusCustomEmojiDate int64 `json:"emoji_status_expiration_date,omitempty"` // Bio is the bio of the other party in a private chat. Returned only in // getChat // @@ -526,6 +531,10 @@ type Message struct { // // optional Sticker *Sticker `json:"sticker,omitempty"` + // Story message is a forwarded story; + // + // optional + Story *Story `json:"story,omitempty"` // Video message is a video, information about the video; // // optional @@ -1032,6 +1041,9 @@ type Document struct { FileSize int64 `json:"file_size,omitempty"` } +// Story represents a message about a forwarded story in the chat. +type Story struct{} + // Video represents a video file. type Video struct { // FileID identifier for this file, which can be used to download or reuse @@ -1149,8 +1161,16 @@ type PollOption struct { type PollAnswer struct { // PollID is the unique poll identifier PollID string `json:"poll_id"` - // User who changed the answer to the poll - User User `json:"user"` + // Chat that changed the answer to the poll, if the voter is anonymous. + // + // Optional + VoterChat *Chat `json:"voter_chat,omitempty"` + // User who changed the answer to the poll, if the voter isn't anonymous + // For backward compatibility, the field user in such objects + // will contain the user 136817688 (@Channel_Bot). + // + // Optional + User *User `json:"user,omitempty"` // OptionIDs is the 0-based identifiers of poll options chosen by the user. // May be empty if user retracted vote. OptionIDs []int `json:"option_ids"` @@ -2066,7 +2086,7 @@ type ChatMemberUpdated struct { // // optional InviteLink *ChatInviteLink `json:"invite_link,omitempty"` - // ViaChatFolderInviteLink is True, if the user joined the chat + // ViaChatFolderInviteLink is True, if the user joined the chat // via a chat folder invite link // // optional @@ -2227,7 +2247,7 @@ type BotCommandScope struct { UserID int64 `json:"user_id,omitempty"` } -//BotName represents the bot's name. +// BotName represents the bot's name. type BotName struct { Name string `json:"name"` } From 6d16deaa376eaab7ed713feec2ebfb9070c759ef Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sat, 30 Dec 2023 17:18:27 +0200 Subject: [PATCH 18/70] BOT API 6.9 implementation --- configs.go | 6 ++++++ types.go | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/configs.go b/configs.go index a6adaac7..be49680d 100644 --- a/configs.go +++ b/configs.go @@ -1462,6 +1462,9 @@ type PromoteChatMemberConfig struct { CanRestrictMembers bool CanPinMessages bool CanPromoteMembers bool + CanPostStories bool + CanEditStories bool + CanDeleteStories bool CanManageTopics bool } @@ -1486,6 +1489,9 @@ func (config PromoteChatMemberConfig) params() (Params, error) { params.AddBool("can_restrict_members", config.CanRestrictMembers) params.AddBool("can_pin_messages", config.CanPinMessages) params.AddBool("can_promote_members", config.CanPromoteMembers) + params.AddBool("can_post_stories", config.CanPostStories) + params.AddBool("can_edit_stories", config.CanEditStories) + params.AddBool("can_delete_stories", config.CanDeleteStories) params.AddBool("can_manage_topics", config.CanManageTopics) return params, nil diff --git a/types.go b/types.go index ba26ebe2..a907bada 100644 --- a/types.go +++ b/types.go @@ -281,7 +281,7 @@ type Chat struct { // // optional EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` - // Expiration date of the emoji status of the chat or the other party + // Expiration date of the emoji status of the chat or the other party // in a private chat, in Unix time, if any. Returned only in getChat. // // optional @@ -1373,10 +1373,21 @@ type ChatShared struct { // to write messages after adding the bot to the attachment menu or launching // a Web App from a link. type WriteAccessAllowed struct { - //Name of the Web App which was launched from a link + // FromRequest is true, if the access was granted after + // the user accepted an explicit request from a Web App + // sent by the method requestWriteAccess. + // + // Optional + FromRequest bool `json:"from_request,omitempty"` + // Name of the Web App which was launched from a link // // Optional WebAppName string `json:"web_app_name,omitempty"` + // FromAttachmentMenu is true, if the access was granted when + // the bot was added to the attachment or side menu + // + // Optional + FromAttachmentMenu bool `json:"from_attachment_menu,omitempty"` } // VideoChatScheduled represents a service message about a voice chat scheduled @@ -1882,6 +1893,9 @@ type ChatAdministratorRights struct { CanPostMessages bool `json:"can_post_messages"` CanEditMessages bool `json:"can_edit_messages"` CanPinMessages bool `json:"can_pin_messages"` + CanPostStories bool `json:"can_post_stories"` + CanEditStories bool `json:"can_edit_stories"` + CanDeleteStories bool `json:"can_delete_stories"` CanManageTopics bool `json:"can_manage_topics"` } @@ -1975,6 +1989,21 @@ type ChatMember struct { // // optional CanPinMessages bool `json:"can_pin_messages,omitempty"` + // CanPostStories administrators only. + // True, if the administrator can post stories in the channel; channels only + // + // optional + CanPostStories bool `json:"can_post_stories,omitempty"` + // CanEditStories administrators only. + // True, if the administrator can edit stories posted by other users; channels only + // + // optional + CanEditStories bool `json:"can_edit_stories,omitempty"` + // CanDeleteStories administrators only. + // True, if the administrator can delete stories posted by other users; channels only + // + // optional + CanDeleteStories bool `json:"can_delete_stories,omitempty"` // CanManageTopics administrators and restricted only. // True, if the user is allowed to create, rename, // close, and reopen forum topics; supergroups only From bd151fc816ab8ce79c75bd79bca576536dd3c47f Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Fri, 5 Jan 2024 22:05:00 +0200 Subject: [PATCH 19/70] Start implementing 7.0 Bot API changes --- bot_test.go | 48 ++- configs.go | 676 +++++++++++++++----------------- helpers.go => helper_methods.go | 134 ++++--- helper_structs.go | 127 ++++++ params.go | 2 +- types.go | 519 +++++++++++++++++++++++- types_test.go | 2 + 7 files changed, 1073 insertions(+), 435 deletions(-) rename helpers.go => helper_methods.go (92%) create mode 100644 helper_structs.go diff --git a/bot_test.go b/bot_test.go index 7abd790a..40633d62 100644 --- a/bot_test.go +++ b/bot_test.go @@ -84,7 +84,7 @@ func TestSendWithMessageReply(t *testing.T) { bot, _ := getBot(t) msg := NewMessage(ChatID, "A test message from the test library in telegram-bot-api") - msg.ReplyToMessageID = ReplyToMessageID + msg.ReplyParameters.MessageID = ReplyToMessageID _, err := bot.Send(msg) if err != nil { @@ -169,7 +169,7 @@ func TestSendWithNewPhotoReply(t *testing.T) { bot, _ := getBot(t) msg := NewPhoto(ChatID, FilePath("tests/image.jpg")) - msg.ReplyToMessageID = ReplyToMessageID + msg.ReplyParameters.MessageID = ReplyToMessageID _, err := bot.Send(msg) @@ -699,7 +699,7 @@ func ExampleNewBotAPI() { log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) msg := NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID + msg.ReplyParameters.MessageID = update.Message.MessageID bot.Send(msg) } @@ -827,8 +827,12 @@ func TestDeleteMessage(t *testing.T) { message, _ := bot.Send(msg) deleteMessageConfig := DeleteMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, } _, err := bot.Request(deleteMessageConfig) @@ -845,8 +849,12 @@ func TestPinChatMessage(t *testing.T) { message, _ := bot.Send(msg) pinChatMessageConfig := PinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: ChatID, + }, + MessageID: message.MessageID, + }, DisableNotification: false, } _, err := bot.Request(pinChatMessageConfig) @@ -865,8 +873,12 @@ func TestUnpinChatMessage(t *testing.T) { // We need pin message to unpin something pinChatMessageConfig := PinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, DisableNotification: false, } @@ -875,8 +887,12 @@ func TestUnpinChatMessage(t *testing.T) { } unpinChatMessageConfig := UnpinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, } if _, err := bot.Request(unpinChatMessageConfig); err != nil { @@ -892,8 +908,12 @@ func TestUnpinAllChatMessages(t *testing.T) { message, _ := bot.Send(msg) pinChatMessageConfig := PinChatMessageConfig{ - ChatID: message.Chat.ID, - MessageID: message.MessageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: message.Chat.ID, + }, + MessageID: message.MessageID, + }, DisableNotification: true, } @@ -902,7 +922,7 @@ func TestUnpinAllChatMessages(t *testing.T) { } unpinAllChatMessagesConfig := UnpinAllChatMessagesConfig{ - ChatID: message.Chat.ID, + ChatConfig: ChatConfig{ChatID: message.Chat.ID}, } if _, err := bot.Request(unpinAllChatMessagesConfig); err != nil { diff --git a/configs.go b/configs.go index be49680d..268c9372 100644 --- a/configs.go +++ b/configs.go @@ -60,6 +60,12 @@ const ( // UpdateTypeEditedChannelPost is new version of a channel post that is known to the bot and was edited UpdateTypeEditedChannelPost = "edited_channel_post" + // UpdateTypeMessageReactionis is a reaction to a message was changed by a user + UpdateTypeMessageReaction = "message_reaction" + + // UpdateTypeMessageReactionCount are reactions to a message with anonymous reactions were changed + UpdateTypeMessageReactionCount = "message_reaction_count" + // UpdateTypeInlineQuery is new incoming inline query UpdateTypeInlineQuery = "inline_query" @@ -96,6 +102,14 @@ const ( // UpdateTypeChatJoinRequest is request to join the chat has been sent. // The bot must have the can_invite_users administrator right in the chat to receive these updates. UpdateTypeChatJoinRequest = "chat_join_request" + + // UpdateTypeChatBoost is chat boost was added or changed. + // The bot must be an administrator in the chat to receive these updates. + UpdateTypeChatBoost = "chat_boost" + + // UpdateTypeRemovedChatBoost is boost was removed from a chat. + // The bot must be an administrator in the chat to receive these updates. + UpdateTypeRemovedChatBoost = "removed_chat_boost" ) // Library errors @@ -266,89 +280,13 @@ func (CloseConfig) params() (Params, error) { return nil, nil } -// BaseChat is base type for all chat config types. -type BaseChat struct { - ChatID int64 // required - MessageThreadID int - ChannelUsername string - ProtectContent bool - ReplyToMessageID int - ReplyMarkup interface{} - DisableNotification bool - AllowSendingWithoutReply bool -} - -func (chat *BaseChat) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", chat.ChatID, chat.ChannelUsername) - params.AddNonZero("message_thread_id", chat.MessageThreadID) - params.AddNonZero("reply_to_message_id", chat.ReplyToMessageID) - params.AddBool("disable_notification", chat.DisableNotification) - params.AddBool("allow_sending_without_reply", chat.AllowSendingWithoutReply) - params.AddBool("protect_content", chat.ProtectContent) - - err := params.AddInterface("reply_markup", chat.ReplyMarkup) - - return params, err -} - -// BaseFile is a base type for all file config types. -type BaseFile struct { - BaseChat - File RequestFileData -} - -func (file BaseFile) params() (Params, error) { - return file.BaseChat.params() -} - -// BaseEdit is base type of all chat edits. -type BaseEdit struct { - ChatID int64 - ChannelUsername string - MessageID int - InlineMessageID string - ReplyMarkup *InlineKeyboardMarkup -} - -func (edit BaseEdit) params() (Params, error) { - params := make(Params) - - if edit.InlineMessageID != "" { - params["inline_message_id"] = edit.InlineMessageID - } else { - params.AddFirstValid("chat_id", edit.ChatID, edit.ChannelUsername) - params.AddNonZero("message_id", edit.MessageID) - } - - err := params.AddInterface("reply_markup", edit.ReplyMarkup) - - return params, err -} - -// BaseSpoiler is base type of structures with spoilers. -type BaseSpoiler struct { - HasSpoiler bool -} - -func (spoiler BaseSpoiler) params() (Params, error) { - params := make(Params) - - if spoiler.HasSpoiler { - params.AddBool("has_spoiler", true) - } - - return params, nil -} - // MessageConfig contains information about a SendMessage request. type MessageConfig struct { BaseChat - Text string - ParseMode string - Entities []MessageEntity - DisableWebPagePreview bool + Text string + ParseMode string + Entities []MessageEntity + LinkPreviewOptions LinkPreviewOptions } func (config MessageConfig) params() (Params, error) { @@ -358,9 +296,12 @@ func (config MessageConfig) params() (Params, error) { } params.AddNonEmpty("text", config.Text) - params.AddBool("disable_web_page_preview", config.DisableWebPagePreview) params.AddNonEmpty("parse_mode", config.ParseMode) err = params.AddInterface("entities", config.Entities) + if err != nil { + return params, err + } + err = params.AddInterface("link_preview_options", config.LinkPreviewOptions) return params, err } @@ -372,9 +313,8 @@ func (config MessageConfig) method() string { // ForwardConfig contains information about a ForwardMessage request. type ForwardConfig struct { BaseChat - FromChatID int64 // required - FromChannelUsername string - MessageID int // required + FromChat ChatConfig + MessageID int // required } func (config ForwardConfig) params() (Params, error) { @@ -382,8 +322,11 @@ func (config ForwardConfig) params() (Params, error) { if err != nil { return params, err } - - params.AddNonZero64("from_chat_id", config.FromChatID) + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) params.AddNonZero("message_id", config.MessageID) return params, nil @@ -393,15 +336,41 @@ func (config ForwardConfig) method() string { return "forwardMessage" } +// ForwardMessagesConfig contains information about a ForwardMessages request. +type ForwardMessagesConfig struct { + BaseChat + FromChat ChatConfig + MessageIDs []int // required +} + +func (config ForwardMessagesConfig) params() (Params, error) { + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) + err = params.AddInterface("message_ids", config.MessageIDs) + + return params, err +} + +func (config ForwardMessagesConfig) method() string { + return "forwardMessages" +} + // CopyMessageConfig contains information about a copyMessage request. type CopyMessageConfig struct { BaseChat - FromChatID int64 - FromChannelUsername string - MessageID int - Caption string - ParseMode string - CaptionEntities []MessageEntity + FromChat ChatConfig + MessageID int + Caption string + ParseMode string + CaptionEntities []MessageEntity } func (config CopyMessageConfig) params() (Params, error) { @@ -410,7 +379,11 @@ func (config CopyMessageConfig) params() (Params, error) { return params, err } - params.AddFirstValid("from_chat_id", config.FromChatID, config.FromChannelUsername) + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) params.AddNonZero("message_id", config.MessageID) params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) @@ -423,6 +396,35 @@ func (config CopyMessageConfig) method() string { return "copyMessage" } +// CopyMessagesConfig contains information about a copyMessages request. +type CopyMessagesConfig struct { + BaseChat + FromChat ChatConfig + MessageIDs []int + RemoveCaption bool +} + +func (config CopyMessagesConfig) params() (Params, error) { + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + + p1, err := config.FromChat.paramsWithKey("from_chat_id") + if err != nil { + return params, err + } + params.Merge(p1) + params.AddBool("remove_caption", config.RemoveCaption) + err = params.AddInterface("message_ids", config.MessageIDs) + + return params, err +} + +func (config CopyMessagesConfig) method() string { + return "copyMessages" +} + // PhotoConfig contains information about a SendPhoto request. type PhotoConfig struct { BaseFile @@ -970,13 +972,12 @@ func (config GameConfig) method() string { // SetGameScoreConfig allows you to update the game score in a chat. type SetGameScoreConfig struct { + BaseChatMessage + UserID int64 Score int Force bool DisableEditMessage bool - ChatID int64 - ChannelUsername string - MessageID int InlineMessageID string } @@ -990,8 +991,11 @@ func (config SetGameScoreConfig) params() (Params, error) { if config.InlineMessageID != "" { params["inline_message_id"] = config.InlineMessageID } else { - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) + p1, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } + params.Merge(p1) } return params, nil @@ -1003,10 +1007,9 @@ func (config SetGameScoreConfig) method() string { // GetGameHighScoresConfig allows you to fetch the high scores for a game. type GetGameHighScoresConfig struct { + BaseChatMessage + UserID int64 - ChatID int64 - ChannelUsername string - MessageID int InlineMessageID string } @@ -1018,8 +1021,11 @@ func (config GetGameHighScoresConfig) params() (Params, error) { if config.InlineMessageID != "" { params["inline_message_id"] = config.InlineMessageID } else { - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) + p1, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } + params.Merge(p1) } return params, nil @@ -1052,10 +1058,10 @@ func (config ChatActionConfig) method() string { // EditMessageTextConfig allows you to modify the text in a message. type EditMessageTextConfig struct { BaseEdit - Text string - ParseMode string - Entities []MessageEntity - DisableWebPagePreview bool + Text string + ParseMode string + Entities []MessageEntity + LinkPreviewOptions LinkPreviewOptions } func (config EditMessageTextConfig) params() (Params, error) { @@ -1066,8 +1072,11 @@ func (config EditMessageTextConfig) params() (Params, error) { params["text"] = config.Text params.AddNonEmpty("parse_mode", config.ParseMode) - params.AddBool("disable_web_page_preview", config.DisableWebPagePreview) err = params.AddInterface("entities", config.Entities) + if err != nil { + return params, err + } + err = params.AddInterface("link_preview_options", config.LinkPreviewOptions) return params, err } @@ -1154,6 +1163,28 @@ func (StopPollConfig) method() string { return "stopPoll" } +// SetMessageReactionConfig changes reactions on a message. Returns true on success. +type SetMessageReactionConfig struct { + BaseChatMessage + Reaction []ReactionType + IsBig bool +} + +func (config SetMessageReactionConfig) params() (Params, error) { + params, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } + params.AddBool("is_big", config.IsBig) + err = params.AddInterface("reaction", config.Reaction) + + return params, err +} + +func (SetMessageReactionConfig) method() string { + return "setMessageReaction" +} + // UserProfilePhotosConfig contains information about a // GetUserProfilePhotos request. type UserProfilePhotosConfig struct { @@ -1370,10 +1401,17 @@ func (config CallbackConfig) params() (Params, error) { // ChatMemberConfig contains information about a user in a chat for use // with administrative functions such as kicking or unbanning a user. type ChatMemberConfig struct { - ChatID int64 - SuperGroupUsername string - ChannelUsername string - UserID int64 + ChatConfig + UserID int64 +} + +func (config ChatMemberConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero64("user_id", config.UserID) + return params, nil } // UnbanChatMemberConfig allows you to unban a user. @@ -1387,10 +1425,11 @@ func (config UnbanChatMemberConfig) method() string { } func (config UnbanChatMemberConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) params.AddBool("only_if_banned", config.OnlyIfBanned) return params, nil @@ -1408,10 +1447,11 @@ func (config BanChatMemberConfig) method() string { } func (config BanChatMemberConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero64("user_id", config.UserID) params.AddNonZero64("until_date", config.UntilDate) params.AddBool("revoke_messages", config.RevokeMessages) @@ -1436,14 +1476,14 @@ func (config RestrictChatMemberConfig) method() string { } func (config RestrictChatMemberConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) params.AddBool("use_independent_chat_permissions", config.UseIndependentChatPermissions) - - err := params.AddInterface("permissions", config.Permissions) params.AddNonZero64("until_date", config.UntilDate) + err = params.AddInterface("permissions", config.Permissions) return params, err } @@ -1473,10 +1513,10 @@ func (config PromoteChatMemberConfig) method() string { } func (config PromoteChatMemberConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } params.AddBool("is_anonymous", config.IsAnonymous) params.AddBool("can_manage_chat", config.CanManageChat) @@ -1509,10 +1549,10 @@ func (SetChatAdministratorCustomTitle) method() string { } func (config SetChatAdministratorCustomTitle) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername, config.ChannelUsername) - params.AddNonZero64("user_id", config.UserID) + params, err := config.ChatMemberConfig.params() + if err != nil { + return params, err + } params.AddNonEmpty("custom_title", config.CustomTitle) return params, nil @@ -1524,10 +1564,9 @@ func (config SetChatAdministratorCustomTitle) params() (Params, error) { // administrator in the supergroup or channel for this to work and must have the // appropriate administrator rights. type BanChatSenderChatConfig struct { - ChatID int64 - ChannelUsername string - SenderChatID int64 - UntilDate int + ChatConfig + SenderChatID int64 + UntilDate int } func (config BanChatSenderChatConfig) method() string { @@ -1535,9 +1574,10 @@ func (config BanChatSenderChatConfig) method() string { } func (config BanChatSenderChatConfig) params() (Params, error) { - params := make(Params) - - _ = params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonZero64("sender_chat_id", config.SenderChatID) params.AddNonZero("until_date", config.UntilDate) @@ -1548,9 +1588,8 @@ func (config BanChatSenderChatConfig) params() (Params, error) { // supergroup or channel. The bot must be an administrator for this to work and // must have the appropriate administrator rights. type UnbanChatSenderChatConfig struct { - ChatID int64 - ChannelUsername string - SenderChatID int64 + ChatConfig + SenderChatID int64 } func (config UnbanChatSenderChatConfig) method() string { @@ -1558,28 +1597,15 @@ func (config UnbanChatSenderChatConfig) method() string { } func (config UnbanChatSenderChatConfig) params() (Params, error) { - params := make(Params) - - _ = params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonZero64("sender_chat_id", config.SenderChatID) return params, nil } -// ChatConfig contains information about getting information on a chat. -type ChatConfig struct { - ChatID int64 - SuperGroupUsername string -} - -func (config ChatConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} - // ChatInfoConfig contains information about getting chat information. type ChatInfoConfig struct { ChatConfig @@ -1621,11 +1647,13 @@ func (SetChatPermissionsConfig) method() string { } func (config SetChatPermissionsConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddBool("use_independent_chat_permissions", config.UseIndependentChatPermissions) - err := params.AddInterface("permissions", config.Permissions) + err = params.AddInterface("permissions", config.Permissions) return params, err } @@ -1642,11 +1670,7 @@ func (ChatInviteLinkConfig) method() string { } func (config ChatInviteLinkConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil + return config.ChatConfig.params() } // CreateChatInviteLinkConfig allows you to create an additional invite link for @@ -1666,10 +1690,12 @@ func (CreateChatInviteLinkConfig) method() string { } func (config CreateChatInviteLinkConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonEmpty("name", config.Name) - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero("expire_date", config.ExpireDate) params.AddNonZero("member_limit", config.MemberLimit) params.AddBool("creates_join_request", config.CreatesJoinRequest) @@ -1694,9 +1720,11 @@ func (EditChatInviteLinkConfig) method() string { } func (config EditChatInviteLinkConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonEmpty("name", config.Name) params["invite_link"] = config.InviteLink params.AddNonZero("expire_date", config.ExpireDate) @@ -1720,9 +1748,11 @@ func (RevokeChatInviteLinkConfig) method() string { } func (config RevokeChatInviteLinkConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params["invite_link"] = config.InviteLink return params, nil @@ -1739,10 +1769,12 @@ func (ApproveChatJoinRequestConfig) method() string { } func (config ApproveChatJoinRequestConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("user_id", int(config.UserID)) + params.AddNonZero64("user_id", config.UserID) return params, nil } @@ -1758,18 +1790,18 @@ func (DeclineChatJoinRequest) method() string { } func (config DeclineChatJoinRequest) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("user_id", int(config.UserID)) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero64("user_id", config.UserID) return params, nil } // LeaveChatConfig allows you to leave a chat. type LeaveChatConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config LeaveChatConfig) method() string { @@ -1777,24 +1809,21 @@ func (config LeaveChatConfig) method() string { } func (config LeaveChatConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil + return config.ChatConfig.params() } // ChatConfigWithUser contains information about a chat and a user. type ChatConfigWithUser struct { - ChatID int64 - SuperGroupUsername string - UserID int64 + ChatConfig + UserID int64 } func (config ChatConfigWithUser) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params.AddNonZero64("user_id", config.UserID) return params, nil @@ -1977,9 +2006,7 @@ func (config PreCheckoutConfig) params() (Params, error) { // DeleteMessageConfig contains information of a message in a chat to delete. type DeleteMessageConfig struct { - ChannelUsername string - ChatID int64 - MessageID int + BaseChatMessage } func (config DeleteMessageConfig) method() string { @@ -1987,19 +2014,25 @@ func (config DeleteMessageConfig) method() string { } func (config DeleteMessageConfig) params() (Params, error) { - params := make(Params) + return config.BaseChatMessage.params() +} - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) +// DeleteMessageConfig contains information of a messages in a chat to delete. +type DeleteMessagesConfig struct { + BaseChatMessages +} - return params, nil +func (config DeleteMessagesConfig) method() string { + return "deleteMessages" +} + +func (config DeleteMessagesConfig) params() (Params, error) { + return config.BaseChatMessages.params() } // PinChatMessageConfig contains information of a message in a chat to pin. type PinChatMessageConfig struct { - ChatID int64 - ChannelUsername string - MessageID int + BaseChatMessage DisableNotification bool } @@ -2008,10 +2041,11 @@ func (config PinChatMessageConfig) method() string { } func (config PinChatMessageConfig) params() (Params, error) { - params := make(Params) + params, err := config.BaseChatMessage.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) params.AddBool("disable_notification", config.DisableNotification) return params, nil @@ -2021,9 +2055,7 @@ func (config PinChatMessageConfig) params() (Params, error) { // // If MessageID is not specified, it will unpin the most recent pin. type UnpinChatMessageConfig struct { - ChatID int64 - ChannelUsername string - MessageID int + BaseChatMessage } func (config UnpinChatMessageConfig) method() string { @@ -2031,19 +2063,13 @@ func (config UnpinChatMessageConfig) method() string { } func (config UnpinChatMessageConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddNonZero("message_id", config.MessageID) - - return params, nil + return config.BaseChatMessage.params() } // UnpinAllChatMessagesConfig contains information of all messages to unpin in // a chat. type UnpinAllChatMessagesConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config UnpinAllChatMessagesConfig) method() string { @@ -2051,11 +2077,7 @@ func (config UnpinAllChatMessagesConfig) method() string { } func (config UnpinAllChatMessagesConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil + return config.ChatConfig.params() } // SetChatPhotoConfig allows you to set a group, supergroup, or channel's photo. @@ -2076,8 +2098,7 @@ func (config SetChatPhotoConfig) files() []RequestFile { // DeleteChatPhotoConfig allows you to delete a group, supergroup, or channel's photo. type DeleteChatPhotoConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config DeleteChatPhotoConfig) method() string { @@ -2085,18 +2106,12 @@ func (config DeleteChatPhotoConfig) method() string { } func (config DeleteChatPhotoConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, nil + return config.ChatConfig.params() } // SetChatTitleConfig allows you to set the title of something other than a private chat. type SetChatTitleConfig struct { - ChatID int64 - ChannelUsername string - + ChatConfig Title string } @@ -2105,9 +2120,11 @@ func (config SetChatTitleConfig) method() string { } func (config SetChatTitleConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) params["title"] = config.Title return params, nil @@ -2115,9 +2132,7 @@ func (config SetChatTitleConfig) params() (Params, error) { // SetChatDescriptionConfig allows you to set the description of a supergroup or channel. type SetChatDescriptionConfig struct { - ChatID int64 - ChannelUsername string - + ChatConfig Description string } @@ -2126,9 +2141,11 @@ func (config SetChatDescriptionConfig) method() string { } func (config SetChatDescriptionConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) params["description"] = config.Description return params, nil @@ -2432,8 +2449,7 @@ func (config SetStickerSetThumbConfig) files() []RequestFile { // SetChatStickerSetConfig allows you to set the sticker set for a supergroup. type SetChatStickerSetConfig struct { - ChatID int64 - SuperGroupUsername string + ChatConfig StickerSetName string } @@ -2443,9 +2459,11 @@ func (config SetChatStickerSetConfig) method() string { } func (config SetChatStickerSetConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) params["sticker_set_name"] = config.StickerSetName return params, nil @@ -2453,8 +2471,7 @@ func (config SetChatStickerSetConfig) params() (Params, error) { // DeleteChatStickerSetConfig allows you to remove a supergroup's sticker set. type DeleteChatStickerSetConfig struct { - ChatID int64 - SuperGroupUsername string + ChatConfig } func (config DeleteChatStickerSetConfig) method() string { @@ -2462,11 +2479,7 @@ func (config DeleteChatStickerSetConfig) method() string { } func (config DeleteChatStickerSetConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil + return config.ChatConfig.params() } // GetForumTopicIconStickersConfig allows you to get custom emoji stickers, @@ -2481,24 +2494,10 @@ func (config GetForumTopicIconStickersConfig) params() (Params, error) { return nil, nil } -// BaseForum is a base type for all forum config types. -type BaseForum struct { - ChatID int64 - SuperGroupUsername string -} - -func (config BaseForum) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - - return params, nil -} - // CreateForumTopicConfig allows you to create a topic // in a forum supergroup chat. type CreateForumTopicConfig struct { - BaseForum + ChatConfig Name string IconColor int IconCustomEmojiID string @@ -2509,14 +2508,29 @@ func (config CreateForumTopicConfig) method() string { } func (config CreateForumTopicConfig) params() (Params, error) { - params := make(Params) + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } params.AddNonEmpty("name", config.Name) params.AddNonZero("icon_color", config.IconColor) params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) - p1, _ := config.BaseForum.params() - params.Merge(p1) + return params, nil +} + +type BaseForum struct { + ChatConfig + MessageThreadID int +} + +func (base BaseForum) params() (Params, error) { + params, err := base.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero("message_thread_id", base.MessageThreadID) return params, nil } @@ -2525,7 +2539,6 @@ func (config CreateForumTopicConfig) params() (Params, error) { // name and icon of a topic in a forum supergroup chat. type EditForumTopicConfig struct { BaseForum - MessageThreadID int Name string IconCustomEmojiID string } @@ -2535,108 +2548,48 @@ func (config EditForumTopicConfig) method() string { } func (config EditForumTopicConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero("message_thread_id", config.MessageThreadID) + params, err := config.BaseForum.params() + if err != nil { + return params, err + } params.AddNonEmpty("name", config.Name) params.AddNonEmpty("icon_custom_emoji_id", config.IconCustomEmojiID) - p1, _ := config.BaseForum.params() - params.Merge(p1) - return params, nil } // CloseForumTopicConfig allows you to close // an open topic in a forum supergroup chat. -type CloseForumTopicConfig struct { - BaseForum - MessageThreadID int -} +type CloseForumTopicConfig struct{ BaseForum } func (config CloseForumTopicConfig) method() string { return "closeForumTopic" } -func (config CloseForumTopicConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero("message_thread_id", config.MessageThreadID) - - p1, _ := config.BaseForum.params() - params.Merge(p1) - - return params, nil -} - // ReopenForumTopicConfig allows you to reopen // an closed topic in a forum supergroup chat. -type ReopenForumTopicConfig struct { - BaseForum - MessageThreadID int -} +type ReopenForumTopicConfig struct{ BaseForum } func (config ReopenForumTopicConfig) method() string { return "reopenForumTopic" } -func (config ReopenForumTopicConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("message_thread_id", config.MessageThreadID) - - p1, _ := config.BaseForum.params() - params.Merge(p1) - - return params, nil -} - // DeleteForumTopicConfig allows you to delete a forum topic // along with all its messages in a forum supergroup chat. -type DeleteForumTopicConfig struct { - BaseForum - MessageThreadID int -} +type DeleteForumTopicConfig struct{ BaseForum } func (config DeleteForumTopicConfig) method() string { return "deleteForumTopic" } -func (config DeleteForumTopicConfig) params() (Params, error) { - params := make(Params) - - params.AddNonZero("message_thread_id", config.MessageThreadID) - - p1, _ := config.BaseForum.params() - params.Merge(p1) - - return params, nil -} - // UnpinAllForumTopicMessagesConfig allows you to clear the list // of pinned messages in a forum topic. -type UnpinAllForumTopicMessagesConfig struct { - BaseForum - MessageThreadID int -} +type UnpinAllForumTopicMessagesConfig struct{ BaseForum } func (config UnpinAllForumTopicMessagesConfig) method() string { return "unpinAllForumTopicMessages" } -func (config UnpinAllForumTopicMessagesConfig) params() (Params, error) { - params := make(Params) - - params.AddFirstValid("chat_id", config.ChatID, config.SuperGroupUsername) - params.AddNonZero("message_thread_id", config.MessageThreadID) - - p1, _ := config.BaseForum.params() - params.Merge(p1) - - return params, nil -} - // UnpinAllForumTopicMessagesConfig allows you 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 @@ -2651,13 +2604,12 @@ func (config EditGeneralForumTopicConfig) method() string { } func (config EditGeneralForumTopicConfig) params() (Params, error) { - params := make(Params) - + params, err := config.BaseForum.params() + if err != nil { + return params, err + } params.AddNonEmpty("name", config.Name) - p1, _ := config.BaseForum.params() - params.Merge(p1) - return params, nil } @@ -2732,10 +2684,6 @@ func (config MediaGroupConfig) params() (Params, error) { return nil, err } - params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - params.AddBool("disable_notification", config.DisableNotification) - params.AddNonZero("reply_to_message_id", config.ReplyToMessageID) - err = params.AddInterface("media", prepareInputMediaForParams(config.Media)) return params, err @@ -2771,6 +2719,26 @@ func (config DiceConfig) params() (Params, error) { return params, err } +type GetUserChatBoostsConfig struct { + ChatConfig + UserID int64 +} + +func (config GetUserChatBoostsConfig) method() string { + return "getUserChatBoosts" +} + +func (config GetUserChatBoostsConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params.AddNonZero64("user_id", config.UserID) + + return params, err +} + // GetMyCommandsConfig gets a list of the currently registered commands. type GetMyCommandsConfig struct { Scope *BotCommandScope @@ -2949,8 +2917,7 @@ func (config SetMyShortDescriptionConfig) params() (Params, error) { // SetChatMenuButtonConfig changes the bot's menu button in a private chat, // or the default menu button. type SetChatMenuButtonConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig MenuButton *MenuButton } @@ -2960,19 +2927,18 @@ func (config SetChatMenuButtonConfig) method() string { } func (config SetChatMenuButtonConfig) params() (Params, error) { - params := make(Params) - - if err := params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername); err != nil { + params, err := config.ChatConfig.params() + if err != nil { return params, err } - err := params.AddInterface("menu_button", config.MenuButton) + + err = params.AddInterface("menu_button", config.MenuButton) return params, err } type GetChatMenuButtonConfig struct { - ChatID int64 - ChannelUsername string + ChatConfig } func (config GetChatMenuButtonConfig) method() string { @@ -2980,11 +2946,7 @@ func (config GetChatMenuButtonConfig) method() string { } func (config GetChatMenuButtonConfig) params() (Params, error) { - params := make(Params) - - err := params.AddFirstValid("chat_id", config.ChatID, config.ChannelUsername) - - return params, err + return config.ChatConfig.params() } type SetMyDefaultAdministratorRightsConfig struct { diff --git a/helpers.go b/helper_methods.go similarity index 92% rename from helpers.go rename to helper_methods.go index 4001d432..de2dd8ae 100644 --- a/helpers.go +++ b/helper_methods.go @@ -17,19 +17,26 @@ import ( func NewMessage(chatID int64, text string) MessageConfig { return MessageConfig{ BaseChat: BaseChat{ - ChatID: chatID, - ReplyToMessageID: 0, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + }, + Text: text, + LinkPreviewOptions: LinkPreviewOptions{ + IsDisabled: false, }, - Text: text, - DisableWebPagePreview: false, } } // NewDeleteMessage creates a request to delete a message. func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { return DeleteMessageConfig{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, } } @@ -41,8 +48,9 @@ func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { func NewMessageToChannel(username string, text string) MessageConfig { return MessageConfig{ BaseChat: BaseChat{ - ChannelUsername: username, - }, + ChatConfig: ChatConfig{ + ChannelUsername: username, + }}, Text: text, } } @@ -53,9 +61,9 @@ func NewMessageToChannel(username string, text string) MessageConfig { // and messageID is the ID of the original message. func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { return ForwardConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, + FromChat: ChatConfig{ChatID: fromChatID}, + MessageID: messageID, } } @@ -65,9 +73,9 @@ func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig { // and messageID is the ID of the original message. func NewCopyMessage(chatID int64, fromChatID int64, messageID int) CopyMessageConfig { return CopyMessageConfig{ - BaseChat: BaseChat{ChatID: chatID}, - FromChatID: fromChatID, - MessageID: messageID, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, + FromChat: ChatConfig{ChatID: fromChatID}, + MessageID: messageID, } } @@ -80,7 +88,7 @@ func NewCopyMessage(chatID int64, fromChatID int64, messageID int) CopyMessageCo func NewPhoto(chatID int64, file RequestFileData) PhotoConfig { return PhotoConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -92,10 +100,8 @@ func NewPhoto(chatID int64, file RequestFileData) PhotoConfig { func NewPhotoToChannel(username string, file RequestFileData) PhotoConfig { return PhotoConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ - ChannelUsername: username, - }, - File: file, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChannelUsername: username}}, + File: file, }, } } @@ -104,7 +110,7 @@ func NewPhotoToChannel(username string, file RequestFileData) PhotoConfig { func NewAudio(chatID int64, file RequestFileData) AudioConfig { return AudioConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -114,7 +120,7 @@ func NewAudio(chatID int64, file RequestFileData) AudioConfig { func NewDocument(chatID int64, file RequestFileData) DocumentConfig { return DocumentConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -124,7 +130,7 @@ func NewDocument(chatID int64, file RequestFileData) DocumentConfig { func NewSticker(chatID int64, file RequestFileData) StickerConfig { return StickerConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -157,7 +163,7 @@ func NewDeleteStickerSet(name, title string) DeleteStickerSetConfig { func NewVideo(chatID int64, file RequestFileData) VideoConfig { return VideoConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -167,7 +173,7 @@ func NewVideo(chatID int64, file RequestFileData) VideoConfig { func NewAnimation(chatID int64, file RequestFileData) AnimationConfig { return AnimationConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -180,7 +186,7 @@ func NewAnimation(chatID int64, file RequestFileData) AnimationConfig { func NewVideoNote(chatID int64, length int, file RequestFileData) VideoNoteConfig { return VideoNoteConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, Length: length, @@ -191,7 +197,7 @@ func NewVideoNote(chatID int64, length int, file RequestFileData) VideoNoteConfi func NewVoice(chatID int64, file RequestFileData) VoiceConfig { return VoiceConfig{ BaseFile: BaseFile{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, File: file, }, } @@ -202,7 +208,7 @@ func NewVoice(chatID int64, file RequestFileData) VoiceConfig { func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { return MediaGroupConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Media: files, } @@ -262,7 +268,7 @@ func NewInputMediaDocument(media RequestFileData) InputMediaDocument { func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { return ContactConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, PhoneNumber: phoneNumber, FirstName: firstName, @@ -275,7 +281,7 @@ func NewContact(chatID int64, phoneNumber, firstName string) ContactConfig { func NewLocation(chatID int64, latitude float64, longitude float64) LocationConfig { return LocationConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Latitude: latitude, Longitude: longitude, @@ -286,7 +292,7 @@ func NewLocation(chatID int64, latitude float64, longitude float64) LocationConf func NewVenue(chatID int64, title, address string, latitude, longitude float64) VenueConfig { return VenueConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Title: title, Address: address, @@ -301,7 +307,7 @@ func NewVenue(chatID int64, title, address string, latitude, longitude float64) // chatID is where to send it, action should be set via Chat constants. func NewChatAction(chatID int64, action string) ChatActionConfig { return ChatActionConfig{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ChatConfig: ChatConfig{ChatID: chatID}}, Action: action, } } @@ -592,8 +598,12 @@ func NewInlineQueryResultVenue(id, title, address string, latitude, longitude fl func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTextConfig { return EditMessageTextConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, }, Text: text, } @@ -603,8 +613,12 @@ func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTex func NewEditMessageTextAndMarkup(chatID int64, messageID int, text string, replyMarkup InlineKeyboardMarkup) EditMessageTextConfig { return EditMessageTextConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, ReplyMarkup: &replyMarkup, }, Text: text, @@ -615,8 +629,12 @@ func NewEditMessageTextAndMarkup(chatID int64, messageID int, text string, reply func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMessageCaptionConfig { return EditMessageCaptionConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, }, Caption: caption, } @@ -627,8 +645,12 @@ func NewEditMessageCaption(chatID int64, messageID int, caption string) EditMess func NewEditMessageReplyMarkup(chatID int64, messageID int, replyMarkup InlineKeyboardMarkup) EditMessageReplyMarkupConfig { return EditMessageReplyMarkupConfig{ BaseEdit: BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, ReplyMarkup: &replyMarkup, }, } @@ -801,7 +823,9 @@ func NewCallbackWithAlert(id, text string) CallbackConfig { // NewInvoice creates a new Invoice request to the user. func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices []LabeledPrice) InvoiceConfig { return InvoiceConfig{ - BaseChat: BaseChat{ChatID: chatID}, + BaseChat: BaseChat{ + ChatConfig: ChatConfig{ChatID: chatID}, + }, Title: title, Description: description, Payload: payload, @@ -814,15 +838,19 @@ func NewInvoice(chatID int64, title, description, payload, providerToken, startP // NewChatTitle allows you to update the title of a chat. func NewChatTitle(chatID int64, title string) SetChatTitleConfig { return SetChatTitleConfig{ - ChatID: chatID, - Title: title, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + Title: title, } } // NewChatDescription allows you to update the description of a chat. func NewChatDescription(chatID int64, description string) SetChatDescriptionConfig { return SetChatDescriptionConfig{ - ChatID: chatID, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, Description: description, } } @@ -832,7 +860,7 @@ func NewChatPhoto(chatID int64, photo RequestFileData) SetChatPhotoConfig { return SetChatPhotoConfig{ BaseFile: BaseFile{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, File: photo, }, @@ -842,7 +870,9 @@ func NewChatPhoto(chatID int64, photo RequestFileData) SetChatPhotoConfig { // NewDeleteChatPhoto allows you to delete the photo for a chat. func NewDeleteChatPhoto(chatID int64) DeleteChatPhotoConfig { return DeleteChatPhotoConfig{ - ChatID: chatID, + ChatConfig: ChatConfig{ + ChatID: chatID, + }, } } @@ -850,7 +880,7 @@ func NewDeleteChatPhoto(chatID int64) DeleteChatPhotoConfig { func NewPoll(chatID int64, question string, options ...string) SendPollConfig { return SendPollConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Question: question, Options: options, @@ -862,8 +892,12 @@ func NewPoll(chatID int64, question string, options ...string) SendPollConfig { func NewStopPoll(chatID int64, messageID int) StopPollConfig { return StopPollConfig{ BaseEdit{ - ChatID: chatID, - MessageID: messageID, + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, }, } } @@ -872,7 +906,7 @@ func NewStopPoll(chatID int64, messageID int) StopPollConfig { func NewDice(chatID int64) DiceConfig { return DiceConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, } } @@ -883,7 +917,7 @@ func NewDice(chatID int64) DiceConfig { func NewDiceWithEmoji(chatID int64, emoji string) DiceConfig { return DiceConfig{ BaseChat: BaseChat{ - ChatID: chatID, + ChatConfig: ChatConfig{ChatID: chatID}, }, Emoji: emoji, } diff --git a/helper_structs.go b/helper_structs.go new file mode 100644 index 00000000..008fc474 --- /dev/null +++ b/helper_structs.go @@ -0,0 +1,127 @@ +package tgbotapi + +// ChatConfig is a base type for all chat identifiers +type ChatConfig struct { + ChatID int64 + ChannelUsername string + SuperGroupUsername string +} + +func (base ChatConfig) params() (Params, error) { + return base.paramsWithKey("chat_id") +} + +func (base ChatConfig) paramsWithKey(key string) (Params, error) { + params := make(Params) + return params, params.AddFirstValid(key, base.ChatID, base.ChannelUsername, base.SuperGroupUsername) +} + +// BaseChat is base type for all chat config types. +type BaseChat struct { + ChatConfig + MessageThreadID int + ProtectContent bool + ReplyMarkup interface{} + DisableNotification bool + ReplyParameters ReplyParameters +} + +func (chat *BaseChat) params() (Params, error) { + params, err := chat.ChatConfig.params() + if err != nil { + return params, err + } + + params.AddNonZero("message_thread_id", chat.MessageThreadID) + params.AddBool("disable_notification", chat.DisableNotification) + params.AddBool("protect_content", chat.ProtectContent) + + err = params.AddInterface("reply_markup", chat.ReplyMarkup) + if err != nil { + return params, err + } + err = params.AddInterface("reply_parameters", chat.ReplyParameters) + return params, err +} + +// BaseFile is a base type for all file config types. +type BaseFile struct { + BaseChat + File RequestFileData +} + +func (file BaseFile) params() (Params, error) { + return file.BaseChat.params() +} + +// BaseEdit is base type of all chat edits. +type BaseEdit struct { + BaseChatMessage + InlineMessageID string + ReplyMarkup *InlineKeyboardMarkup +} + +func (edit BaseEdit) params() (Params, error) { + params := make(Params) + + if edit.InlineMessageID != "" { + params["inline_message_id"] = edit.InlineMessageID + } else { + p1, err := edit.BaseChatMessage.params() + if err != nil { + return params, err + } + params.Merge(p1) + } + + err := params.AddInterface("reply_markup", edit.ReplyMarkup) + + return params, err +} + +// BaseSpoiler is base type of structures with spoilers. +type BaseSpoiler struct { + HasSpoiler bool +} + +func (spoiler BaseSpoiler) params() (Params, error) { + params := make(Params) + + if spoiler.HasSpoiler { + params.AddBool("has_spoiler", true) + } + + return params, nil +} + +// BaseChatMessage is a base type for all messages in chats. +type BaseChatMessage struct { + ChatConfig + MessageID int +} + +func (base BaseChatMessage) params() (Params, error) { + params, err := base.ChatConfig.params() + if err != nil { + return params, err + } + params.AddNonZero("message_id", base.MessageID) + + return params, nil +} + +// BaseChatMessages is a base type for all messages in chats. +type BaseChatMessages struct { + ChatConfig + MessageIDs []int +} + +func (base BaseChatMessages) params() (Params, error) { + params, err := base.ChatConfig.params() + if err != nil { + return params, err + } + err = params.AddInterface("message_ids", base.MessageIDs) + + return params, err +} diff --git a/params.go b/params.go index 118af364..9afd07df 100644 --- a/params.go +++ b/params.go @@ -101,4 +101,4 @@ func (p *Params) Merge(p1 Params) { for k, v := range p1 { (*p)[k] = v } -} \ No newline at end of file +} diff --git a/types.go b/types.go index a907bada..93c7fab1 100644 --- a/types.go +++ b/types.go @@ -61,6 +61,14 @@ type Update struct { // // optional EditedChannelPost *Message `json:"edited_channel_post,omitempty"` + // MessageReaction is a reaction to a message was changed by a user. + // + // optional + MessageReaction *MessageReactionUpdated `json:"message_reaction,omitempty"` + // MessageReactionCount reactions to a message with anonymous reactions were changed. + // + // optional + MessageReactionCount *MessageReactionCountUpdated `json:"message_reaction_count,omitempty"` // InlineQuery new incoming inline query // // optional @@ -276,6 +284,11 @@ type Chat struct { // // optional ActiveUsernames []string `json:"active_usernames,omitempty"` + // AvailableReactions is a list of available reactions allowed in the chat. + // If omitted, then all emoji reactions are allowed. Returned only in getChat. + // + // optional + AvailableReactions []ReactionType `json:"available_reactions,omitempty"` // Custom emoji identifier of emoji status of the other party // in a private chat. Returned only in getChat. // @@ -476,6 +489,15 @@ type Message struct { // // optional ReplyToMessage *Message `json:"reply_to_message,omitempty"` + // ExternalReply is an information about the message that is being replied to, + // which may come from another chat or forum topic. + // + // optional + ExternalReply *ExternalReplyInfo `json:"external_reply,omitempty"` + // Quote for replies that quote part of the original message, the quoted part of the message + // + // optional + Quote *TextQuote `json:"text_quote,omitempty"` // ViaBot through which the message was sent; // // optional @@ -505,6 +527,11 @@ type Message struct { // // optional Entities []MessageEntity `json:"entities,omitempty"` + // LinkPreviewOptions are options used for link preview generation for the message, + // if it is a text message and link preview options were changed + // + // Optional + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` // Animation message is an animation, information about the animation. // For backward compatibility, when this field is set, the document field will also be set; // @@ -663,10 +690,10 @@ type Message struct { // // optional SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"` - // UserShared is a service message: a user was shared with the bot + // UsersShared is a service message: the users were shared with the bot // // optional - UserShared *UserShared `json:"user_shared,omitempty"` + UsersShared *UsersShared `json:"users_shared,omitempty"` // ChatShared is a service message: a chat was shared with the bot // // optional @@ -832,6 +859,7 @@ type MessageEntity struct { // “underline” (underlined text), // “strikethrough” (strikethrough text), // "spoiler" (spoiler message), + // “blockquote” (block quotation), // “code” (monowidth string), // “pre” (monowidth block), // “text_link” (for clickable text URLs), @@ -925,6 +953,214 @@ func (e MessageEntity) IsTextLink() bool { return e.Type == "text_link" } +// TextQuote contains information about the quoted part of a message +// that is replied to by the given message +type TextQuote struct { + // Text of the quoted part of a message that is replied to by the given message + Text string `json:"text"` + // Entities special entities that appear in the quote. + // Currently, only bold, italic, underline, strikethrough, spoiler, + // and custom_emoji entities are kept in quotes. + // + // optional + Entities []MessageEntity `json:"entities,omitempty"` + // Position is approximate quote position in the original message + // in UTF-16 code units as specified by the sender + Position int `json:"position"` + // IsManual True, if the quote was chosen manually by the message sender. + // Otherwise, the quote was added automatically by the server. + // + // optional + IsManual bool `json:"is_manual,omitempty"` +} + +// ExternalReplyInfo contains information about a message that is being replied to, +// which may come from another chat or forum topic. +type ExternalReplyInfo struct { + // Origin of the message replied to by the given message + Origin MessageOrigin `json:"origin"` + // Chat is the conversation the message belongs to + Chat *Chat `json:"chat"` + // MessageID is a unique message identifier inside this chat + MessageID int `json:"message_id"` + // LinkPreviewOptions used for link preview generation for the original message, + // if it is a text message + // + // Optional + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // Animation message is an animation, information about the animation. + // For backward compatibility, when this field is set, the document field will also be set; + // + // optional + Animation *Animation `json:"animation,omitempty"` + // Audio message is an audio file, information about the file; + // + // optional + Audio *Audio `json:"audio,omitempty"` + // Document message is a general file, information about the file; + // + // optional + Document *Document `json:"document,omitempty"` + // Photo message is a photo, available sizes of the photo; + // + // optional + Photo []PhotoSize `json:"photo,omitempty"` + // Sticker message is a sticker, information about the sticker; + // + // optional + Sticker *Sticker `json:"sticker,omitempty"` + // Story message is a forwarded story; + // + // optional + Story *Story `json:"story,omitempty"` + // Video message is a video, information about the video; + // + // optional + Video *Video `json:"video,omitempty"` + // VideoNote message is a video note, information about the video message; + // + // optional + VideoNote *VideoNote `json:"video_note,omitempty"` + // Voice message is a voice message, information about the file; + // + // optional + Voice *Voice `json:"voice,omitempty"` + // HasMediaSpoiler True, if the message media is covered by a spoiler animation + // + // optional + HasMediaSpoiler bool `json:"has_media_spoiler,omitempty"` + // Contact message is a shared contact, information about the contact; + // + // optional + Contact *Contact `json:"contact,omitempty"` + // Dice is a dice with random value; + // + // optional + Dice *Dice `json:"dice,omitempty"` + // Game message is a game, information about the game; + // + // optional + Game *Game `json:"game,omitempty"` + // Giveaway is information about the giveaway + // + // optional + Giveaway *Giveaway `json:"giveaway,omitempty"` + // GiveawayWinners a giveaway with public winners was completed + // + // optional + GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` + // Invoice message is an invoice for a payment; + // + // optional + Invoice *Invoice `json:"invoice,omitempty"` + // Location message is a shared location, information about the location; + // + // optional + Location *Location `json:"location,omitempty"` + // Poll is a native poll, information about the poll; + // + // optional + Poll *Poll `json:"poll,omitempty"` + // Venue message is a venue, information about the venue. + // For backward compatibility, when this field is set, the location field + // will also be set; + // + // optional + Venue *Venue `json:"venue,omitempty"` +} + +// ReplyParameters describes reply parameters for the message that is being sent. +type ReplyParameters struct { + // MessageID identifier of the message that will be replied to in + // the current chat, or in the chat chat_id if it is specified + MessageID int `json:"message_id"` + // ChatID if the message to be replied to is from a different chat, + // unique identifier for the chat or username of the channel (in the format @channelusername) + // + // optional + ChatID interface{} `json:"chat_id,omitempty"` + // AllowSendingWithoutReply true if the message should be sent even + // if the specified message to be replied to is not found; + // can be used only for replies in the same chat and forum topic. + // + // optional + AllowSendingWithoutReply bool `json:"allow_sending_without_reply,omitempty"` + // Quote is a 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, and custom_emoji entities. + // The message will fail to send if the quote isn't found in the original message. + // + // optional + Quote string `json:"quote,omitempty"` + // QuoteParseMode mode for parsing entities in the quote. + // + // optional + QuoteParseMode string `json:"quote_parse_mode,omitempty"` + // QuoteEntities a JSON-serialized list of special entities that appear in the quote. + // It can be specified instead of quote_parse_mode. + // + // optional + QuoteEntities []MessageEntity `json:"quote_entities,omitempty"` + // QuotePosition is a position of the quote in the original message in UTF-16 code units + // + // optional + QuotePosition int `json:"quote_position,omitempty"` +} + +const ( + MessageOriginUser = "user" + MessageOriginHiddenUser = "hidden_user" + MessageOriginChat = "chat" + MessageOriginChannel = "channel" +) + +// MessageOrigin describes the origin of a message. It can be one of: "user", "hidden_user", "origin_chat", "origin_channel" +type MessageOrigin struct { + // Type of the message origin. + Type string `json:"type"` + // Date the message was sent originally in Unix time + Date int64 `json:"date"` + // SenderUser "user" only. + // Is a user that sent the message originally + SenderUser *User `json:"sender_user,omitempty"` + // SenderUserName "hidden_user" only. + // Name of the user that sent the message originally + SenderUserName string `json:"sender_user_name,omitempty"` + // SenderChat "chat" and "channel". + // For "chat": Chat that sent the message originally + // For "channel": Channel chat to which the message was originally sent + SenderChat *Chat `json:"sender_chat,omitempty"` + // AuthorSignature "chat" and "channel". + // For "chat": For messages originally sent by an anonymous chat administrator, + // original message author signature. + // For "channel": Signature of the original post author + // + // Optional + AuthorSignature string `json:"author_signature,omitempty"` + // MessageID "channel" only. + // Unique message identifier inside the chat + // + // Optional + MessageID int `json:"message_id,omitempty"` +} + +func (m MessageOrigin) IsUser() bool { + return m.Type == MessageOriginUser +} + +func (m MessageOrigin) IsHiddenUser() bool { + return m.Type == MessageOriginHiddenUser +} + +func (m MessageOrigin) IsChat() bool { + return m.Type == MessageOriginChat +} + +func (m MessageOrigin) IsChannel() bool { + return m.Type == MessageOriginChannel +} + // PhotoSize represents one size of a photo or a file / sticker thumbnail. type PhotoSize struct { // FileID identifier for this file, which can be used to download or reuse @@ -1351,13 +1587,13 @@ type GeneralForumTopicHidden struct { type GeneralForumTopicUnhidden struct { } -// UserShared object contains information about the user whose identifier +// UsersShared object contains information about the user whose identifier // was shared with the bot using a KeyboardButtonRequestUser button. -type UserShared struct { +type UsersShared struct { // RequestID is an indentifier of the request. RequestID int `json:"request_id"` - // UserID in an identifier of the shared user. - UserID int64 `json:"user_id"` + // UserIDs are identifiers of the shared user. + UserIDs []int64 `json:"user_ids"` } // ChatShared contains information about the chat whose identifier @@ -1423,6 +1659,115 @@ type VideoChatParticipantsInvited struct { Users []User `json:"users,omitempty"` } +// Giveaway represents a message about a scheduled giveaway. +type Giveaway struct { + // Chats is the list of chats which the user must join to participate in the giveaway + Chats []Chat `json:"chats"` + // WinnersSelectionDate is point in time (Unix timestamp) when + // winners of the giveaway will be selected + WinnersSelectionDate int64 `json:"winners_selection_date"` + // WinnerCount is the number of users which are supposed + // to be selected as winners of the giveaway + WinnerCount int `json:"winner_count"` + // OnlyNewMembers True, if only users who join the chats after + // the giveaway started should be eligible to win + // + // optional + OnlyNewMembers bool `json:"only_new_members,omitempty"` + // HasPublicWinners True, if the list of giveaway winners will be visible to everyone + // + // optional + HasPublicWinners bool `json:"has_public_winners,omitempty"` + // PrizeDescription is description of additional giveaway prize + // + // optional + PrizeDescription string `json:"prize_description,omitempty"` + // CountryCodes is 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. + // + // optional + CountryCodes []string `json:"country_codes,omitempty"` + // PremiumSubscriptionMonthCount the number of months the Telegram Premium + // subscription won from the giveaway will be active for + // + // optional + PremiumSubscriptionMonthCount int `json:"premium_subscription_month_count,omitempty"` +} + +// Giveaway represents a message about a scheduled giveaway. +type GiveawayWinners struct { + // Chat that created the giveaway + Chat Chat `json:"chat"` + // GiveawayMessageID is the identifier of the messsage with the giveaway in the chat + GiveawayMessageID int `json:"giveaway_message_id"` + // WinnersSelectionDate is point in time (Unix timestamp) when + // winners of the giveaway will be selected + WinnersSelectionDate int64 `json:"winners_selection_date"` + // WinnerCount is the number of users which are supposed + // to be selected as winners of the giveaway + WinnerCount int `json:"winner_count"` + // Winners is a list of up to 100 winners of the giveaway + Winners []User `json:"winners"` + // AdditionalChatCount is the number of other chats + // the user had to join in order to be eligible for the giveaway + // + // optional + AdditionalChatCount int `json:"additional_chat_count,omitempty"` + // PremiumSubscriptionMonthCount the number of months the Telegram Premium + // subscription won from the giveaway will be active for + // + // optional + PremiumSubscriptionMonthCount int `json:"premium_subscription_month_count,omitempty"` + // UnclaimedPrizeCount is the number of undistributed prizes + // + // optional + UnclaimedPrizeCount int `json:"unclaimed_prize_count,omitempty"` + // OnlyNewMembers True, if only users who join the chats after + // the giveaway started should be eligible to win + // + // optional + OnlyNewMembers bool `json:"only_new_members,omitempty"` + // WasRefunded True, if the giveaway was canceled because the payment for it was refunded + // + // optional + WasRefunded bool `json:"was_refunded,omitempty"` + // PrizeDescription is description of additional giveaway prize + // + // optional + PrizeDescription string `json:"prize_description,omitempty"` +} + +// LinkPreviewOptions describes the options used for link preview generation. +type LinkPreviewOptions struct { + // IsDisabled True, if the link preview is disabled + // + // optional + IsDisabled bool `json:"is_disabled,omitempty"` + // URL to use for the link preview. If empty, + // then the first URL found in the message text will be used + // + // optional + URL string `json:"url,omitempty"` + // PreferSmallMedia True, if the media in the link preview is suppposed + // to be shrunk; ignored if the URL isn't explicitly specified + // or media size change isn't supported for the preview + // + // optional + PreferSmallMedia bool `json:"prefer_small_media,omitempty"` + // PreferLargeMedia True, if the media in the link preview is suppposed + // to be enlarged; ignored if the URL isn't explicitly specified + // or media size change isn't supported for the preview + // + // optional + PreferLargeMedia bool `json:"prefer_large_media,omitempty"` + // ShowAboveText True, if the link preview must be shown above the message text; + // otherwise, the link preview will be shown below the message text + // + // optional + ShowAboveText bool `json:"show_above_text,omitempty"` +} + // UserProfilePhotos contains a set of user profile photos. type UserProfilePhotos struct { // TotalCount total number of profile pictures the target user has @@ -1516,13 +1861,13 @@ type KeyboardButton struct { // Text of the button. If none of the optional fields are used, // it will be sent as a message when the button is pressed. Text string `json:"text"` - // RequestUser if specified, pressing the button will open + // RequestUsers if specified, pressing the button will open // a list of suitable users. Tapping on any user will send // their identifier to the bot in a "user_shared" service message. // Available in private chats only. // // optional - RequestUser *KeyboardButtonRequestUser `json:"request_user,omitempty"` + RequestUsers *KeyboardButtonRequestUsers `json:"request_users,omitempty"` // RequestChat 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. @@ -1555,10 +1900,10 @@ type KeyboardButton struct { WebApp *WebAppInfo `json:"web_app,omitempty"` } -// KeyboardButtonRequestUser defines the criteria used to request +// KeyboardButtonRequestUsers defines the criteria used to request // a suitable user. The identifier of the selected user will be shared // with the bot when the corresponding button is pressed. -type KeyboardButtonRequestUser struct { +type KeyboardButtonRequestUsers struct { // RequestID is a signed 32-bit identifier of the request. RequestID int `json:"request_id"` // UserIsBot pass True to request a bot, @@ -1573,6 +1918,11 @@ type KeyboardButtonRequestUser struct { // // optional UserIsPremium bool `json:"user_is_premium,omitempty"` + // MaxQuantity is the maximum number of users to be selected. + // 1-10. Defaults to 1 + // + // optional + MaxQuantity int `json:"max_quantity,omitempty"` } // KeyboardButtonRequestChat defines the criteria used to request @@ -2242,6 +2592,72 @@ type ChatLocation struct { Address string `json:"address"` } +const ( + ReactionTypeEmoji = "emoji" + ReactionTypeCustomEmoji = "custom_emoji" +) + +// ReactionType describes the type of a reaction. Currently, it can be one of: "emoji", "custom_emoji" +type ReactionType struct { + // Type of the reaction. Can be "emoji", "custom_emoji" + Type string `json:"type"` + // Emoji type "emoji" only. Is a reaction emoji. + Emoji string `json:"emoji"` + // CustomEmoji type "custom_emoji" only. Is a custom emoji identifier. + CustomEmoji string `json:"custom_emoji"` +} + +func (r ReactionType) IsEmoji() bool { + return r.Type == ReactionTypeEmoji +} + +func (r ReactionType) IsCustomEmoji() bool { + return r.Type == ReactionTypeCustomEmoji +} + +// ReactionCount represents a reaction added to a message along with the number of times it was added. +type ReactionCount struct { + // Type of the reaction + Type ReactionType `json:"type"` + // TotalCount number of times the reaction was added + TotalCount int `json:"total_count"` +} + +// MessageReactionUpdated represents a change of a reaction on a message performed by a user. +type MessageReactionUpdated struct { + // Chat containing the message the user reacted to. + Chat Chat `json:"chat"` + // MessageID unique identifier of the message inside the chat. + MessageID int `json:"message_id"` + // User that changed the reaction, if the user isn't anonymous. + // + // optional + User *User `json:"user"` + // ActorChat the chat on behalf of which the reaction was changed, + // if the user is anonymous. + // + // optional + ActorChat *Chat `json:"actor_chat"` + // Date of the change in Unix time. + Date int64 `json:"date"` + // OldReaction is a previous list of reaction types that were set by the user. + OldReaction []ReactionType `json:"old_reaction"` + // NewReaction is a new list of reaction types that have been set by the user. + NewReaction []ReactionType `json:"new_reaction"` +} + +// MessageReactionCountUpdated represents reaction changes on a message with anonymous reactions. +type MessageReactionCountUpdated struct { + // Chat containing the message. + Chat Chat `json:"chat"` + // MessageID unique identifier of the message inside the chat. + MessageID int `json:"message_id"` + // Date of the change in Unix time. + Date int64 `json:"date"` + // Reactions is a list of reactions that are present on the message. + Reactions []ReactionCount `json:"reactions"` +} + // ForumTopic represents a forum topic. type ForumTopic struct { // MessageThreadID is the unique identifier of the forum topic @@ -2305,6 +2721,83 @@ type MenuButton struct { WebApp *WebAppInfo `json:"web_app,omitempty"` } +const ( + ChatBoostSourcePremium = "premium" + ChatBoostSourceGiftCode = "gift_code" + ChatBoostSourceGiveaway = "giveaway" +) + +// ChatBoostSource describes the source of a chat boost +type ChatBoostSource struct { + // Source of the boost, It can be one of: + // "premium", "gift_code", "giveaway" + Source string `json:"source"` + // For "premium": User that boosted the chat + // For "gift_code": User for which the gift code was created + // Optional for "giveaway": User that won the prize in the giveaway if any + User *User `json:"user,omitempty"` + // GiveawayMessageID "giveaway" only. + // Is an 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 int `json:"giveaway_message_id,omitempty"` + // IsUnclaimed "giveaway" only. + // True, if the giveaway was completed, but there was no user to win the prize + // + // optional + IsUnclaimed bool `json:"is_unclaimed,omitempty"` +} + +func (c ChatBoostSource) IsPremium() bool { + return c.Source == ChatBoostSourcePremium +} + +func (c ChatBoostSource) IsGiftCode() bool { + return c.Source == ChatBoostSourceGiftCode +} + +func (c ChatBoostSource) IsGiveaway() bool { + return c.Source == ChatBoostSourceGiveaway +} + +// ChatBoost contains information about a chat boost. +type ChatBoost struct { + // BoostID is an unique identifier of the boost + BoostID string `json:"boost_id"` + // AddDate is a point in time (Unix timestamp) when the chat was boosted + AddDate int64 `json:"add_date"` + // ExpirationDate is a 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"` +} + +// ChatBoostUpdated represents a boost added to a chat or changed. +type ChatBoostUpdated struct { + // Chat which was boosted + Chat Chat `json:"chat"` + // Boost infomation about the chat boost + Boost ChatBoost `json:"boost"` +} + +// ChatBoostRemoved represents a boost removed from a chat. +type ChatBoostRemoved struct { + // Chat which was boosted + Chat Chat `json:"chat"` + // BoostID unique identifier of the boost + BoostID string `json:"boost_id"` + // RemoveDate point in time (Unix timestamp) when the boost was removed + RemoveDate int64 `json:"remove_date"` + // Source of the removed boost + Source ChatBoostSource `json:"source"` +} + +// UserChatBoosts represents a list of boosts added to a chat by a user. +type UserChatBoosts struct { + // Boosts is the list of boosts added to the chat by the user + Boosts []ChatBoost `json:"boosts"` +} + // ResponseParameters are various errors that can be returned in APIResponse. type ResponseParameters struct { // The group has been migrated to a supergroup with the specified identifier. @@ -3576,10 +4069,10 @@ type InputTextMessageContent struct { // // optional Entities []MessageEntity `json:"entities,omitempty"` - // DisableWebPagePreview disables link previews for links in the sent message + // LinkPreviewOptions used for link preview generation for the original message // - // optional - DisableWebPagePreview bool `json:"disable_web_page_preview,omitempty"` + // Optional + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` } // InputLocationMessageContent contains a location for displaying diff --git a/types_test.go b/types_test.go index 90d01eae..4fd9e440 100644 --- a/types_test.go +++ b/types_test.go @@ -341,6 +341,7 @@ var ( _ Chattable = UnbanChatSenderChatConfig{} _ Chattable = UnpinChatMessageConfig{} _ Chattable = UpdateConfig{} + _ Chattable = SetMessageReactionConfig{} _ Chattable = UserProfilePhotosConfig{} _ Chattable = VenueConfig{} _ Chattable = VideoConfig{} @@ -359,6 +360,7 @@ var ( _ Chattable = ReopenGeneralForumTopicConfig{} _ Chattable = HideGeneralForumTopicConfig{} _ Chattable = UnhideGeneralForumTopicConfig{} + _ Chattable = UnpinAllGeneralForumTopicMessagesConfig{} _ Chattable = SetCustomEmojiStickerSetThumbnailConfig{} _ Chattable = SetStickerSetTitleConfig{} _ Chattable = DeleteStickerSetConfig{} From e06de39556c0d2b2696c8c1c148b46dffdcd2831 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Sat, 6 Jan 2024 16:02:14 +0200 Subject: [PATCH 20/70] giveaway implementation --- types.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/types.go b/types.go index 93c7fab1..b8e780cb 100644 --- a/types.go +++ b/types.go @@ -741,6 +741,22 @@ type Message struct { // // optional GeneralForumTopicUnhidden *GeneralForumTopicUnhidden `json:"general_forum_topic_unhidden,omitempty"` + // Service message: a scheduled giveaway was created + // + // optional + GiveawayCreated *GiveawayCreated `json:"giveaway_created,omitempty"` + // The message is a scheduled giveaway message + // + // optional + Giveaway *Giveaway `json:"giveaway,omitempty"` + // A giveaway with public winners was completed + // + // optional + GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` + // Service message: a giveaway without public winners was completed + // + // optional + GiveawayCompleted *GiveawayCompleted `json:"giveaway_completed,omitempty"` // VideoChatScheduled is a service message: video chat scheduled. // // optional @@ -1659,6 +1675,9 @@ type VideoChatParticipantsInvited struct { Users []User `json:"users,omitempty"` } +// This object represents a service message about the creation of a scheduled giveaway. Currently holds no information. +type GiveawayCreated struct{} + // Giveaway represents a message about a scheduled giveaway. type Giveaway struct { // Chats is the list of chats which the user must join to participate in the giveaway @@ -1738,6 +1757,20 @@ type GiveawayWinners struct { PrizeDescription string `json:"prize_description,omitempty"` } +// This object represents a service message about the completion of a giveaway without public winners. +type GiveawayCompleted struct { + // Number of winners in the giveaway + WinnerCount int `json:"winner_count"` + // Number of undistributed prizes + // + // optional + UnclaimedprizeCounr int `json:"unclaimed_prize_count,omitempty"` + // Message with the giveaway that was completed, if it wasn't deleted + // + // optional + GiveawayMessage *Message `json:"giveaway_message,omitempty"` +} + // LinkPreviewOptions describes the options used for link preview generation. type LinkPreviewOptions struct { // IsDisabled True, if the link preview is disabled From 8db24a9981e18884b13b55c77f7d6e8fd4217557 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Sat, 6 Jan 2024 16:11:09 +0200 Subject: [PATCH 21/70] fix typo --- types.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types.go b/types.go index b8e780cb..9ee9659a 100644 --- a/types.go +++ b/types.go @@ -1764,7 +1764,7 @@ type GiveawayCompleted struct { // Number of undistributed prizes // // optional - UnclaimedprizeCounr int `json:"unclaimed_prize_count,omitempty"` + UnclaimedPrizeCount int `json:"unclaimed_prize_count,omitempty"` // Message with the giveaway that was completed, if it wasn't deleted // // optional From 92b9f7c7cf5f23b474904cf7a2006942ecc3bb75 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Sat, 6 Jan 2024 17:12:42 +0200 Subject: [PATCH 22/70] other changes implementation; MaybeInaccessibleMessage not used --- types.go | 85 +++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 53 insertions(+), 32 deletions(-) diff --git a/types.go b/types.go index 9ee9659a..a3665d4c 100644 --- a/types.go +++ b/types.go @@ -289,6 +289,28 @@ type Chat struct { // // optional AvailableReactions []ReactionType `json:"available_reactions,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. Returned only in getChat. + // Always returned in getChat. + // + // optional + AccentColorID int `json:"accent_color_id,omitempty"` + // Custom emoji identifier of emoji chosen by the chat for the reply header and link preview background. + // Returned only in getChat. + // + // optional + BackgroundCustomEmojiID string `json:"background_custom_emoji_id,omitempty"` + // Identifier of the accent color for the chat's profile background. + // See profile accent colors for more details. Returned only in getChat. + // + // optional + ProfileAccentColorID int `json:"profile_accent_color_id,omitempty"` + // Custom emoji identifier of the emoji chosen by the chat for its profile background. + // Returned only in getChat. + // + // optional + ProfileBackgroundCustomEmojiID string `json:"profile_background_custom_emoji_id,omitempty"` // Custom emoji identifier of emoji status of the other party // in a private chat. Returned only in getChat. // @@ -374,6 +396,11 @@ type Chat struct { // // optional HasProtectedContent bool `json:"has_protected_content,omitempty"` + // True, if new chat members will have access to old messages; available only to chat administrators. + // Returned only in getChat. + // + // optional + HasVisibleHistory bool `json:"has_visible_history,omitempty"` // StickerSetName is for supergroups, name of group sticker set.Returned // only in getChat. // @@ -422,6 +449,26 @@ func (c Chat) ChatConfig() ChatConfig { return ChatConfig{ChatID: c.ID} } +// This object describes a message that can be inaccessible to the bot. +// It can be one of +// +// Message +// InaccessibleMessage +type MaybeInaccessibleMessage struct { + Message + InaccessibleMessage +} + +// InaccessibleMessage describes a message that was deleted or is otherwise inaccessible to the bot. +type InaccessibleMessage struct { + // Chat the message belonged to + Chat Chat `json:"chat"` + // Unique message identifier inside the chat + MessageID int `json:"message_id"` + // Always 0. The field can be used to differentiate regular and inaccessible messages. + Date int `json:"date"` +} + // Message represents a message. type Message struct { // MessageID is a unique message identifier inside this chat @@ -446,34 +493,10 @@ type Message struct { Date int `json:"date"` // Chat is the conversation the message belongs to Chat *Chat `json:"chat"` - // ForwardFrom for forwarded messages, sender of the original message; - // - // optional - ForwardFrom *User `json:"forward_from,omitempty"` - // ForwardFromChat for messages forwarded from channels, - // information about the original channel; - // - // optional - ForwardFromChat *Chat `json:"forward_from_chat,omitempty"` - // ForwardFromMessageID for messages forwarded from channels, - // identifier of the original message in the channel; - // - // optional - ForwardFromMessageID int `json:"forward_from_message_id,omitempty"` - // ForwardSignature for messages forwarded from channels, signature of the - // post author if present - // - // optional - ForwardSignature string `json:"forward_signature,omitempty"` - // ForwardSenderName is the sender's name for messages forwarded from users - // who disallow adding a link to their account in forwarded messages - // - // optional - ForwardSenderName string `json:"forward_sender_name,omitempty"` - // ForwardDate for forwarded messages, date the original message was sent in Unix time; + // Information about the original message for forwarded messages // // optional - ForwardDate int `json:"forward_date,omitempty"` + ForwardOrigin *MessageOrigin `json:"forward_origin,omitempty"` // IsTopicMessage true if the message is sent to a forum topic // // optional @@ -675,9 +698,9 @@ type Message struct { // // optional MigrateFromChatID int64 `json:"migrate_from_chat_id,omitempty"` - // PinnedMessage is a specified message was pinned. - // Note that the Message object in this field will not contain further ReplyToMessage - // fields even if it is itself a reply; + // 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. // // optional PinnedMessage *Message `json:"pinned_message,omitempty"` @@ -2158,9 +2181,7 @@ type CallbackQuery struct { ID string `json:"id"` // From sender From *User `json:"from"` - // Message with the callback button that originated the query. - // Note that message content and message date will not be available if the - // message is too old. + // Message sent by the bot with the callback button that originated the query // // optional Message *Message `json:"message,omitempty"` From 678ff6fe454b136b3b34266ac183dbcf8a129ab1 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 7 Jan 2024 09:10:18 +0200 Subject: [PATCH 23/70] Finish implementing Bot API 7.0 changes --- types.go | 74 ++++++++++++++++++++++++++++++-------------------------- 1 file changed, 40 insertions(+), 34 deletions(-) diff --git a/types.go b/types.go index a3665d4c..2c4d8567 100644 --- a/types.go +++ b/types.go @@ -159,15 +159,15 @@ func (u *Update) CallbackData() string { func (u *Update) FromChat() *Chat { switch { case u.Message != nil: - return u.Message.Chat + return &u.Message.Chat case u.EditedMessage != nil: - return u.EditedMessage.Chat + return &u.EditedMessage.Chat case u.ChannelPost != nil: - return u.ChannelPost.Chat + return &u.ChannelPost.Chat case u.EditedChannelPost != nil: - return u.EditedChannelPost.Chat + return &u.EditedChannelPost.Chat case u.CallbackQuery != nil && u.CallbackQuery.Message != nil: - return u.CallbackQuery.Message.Chat + return &u.CallbackQuery.Message.Chat default: return nil } @@ -289,38 +289,39 @@ type Chat struct { // // optional AvailableReactions []ReactionType `json:"available_reactions,omitempty"` - // Identifier of the accent color for the chat name and backgrounds of the chat photo, - // reply header, and link preview. + // AccentColorID is an 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. Returned only in getChat. // Always returned in getChat. // // optional AccentColorID int `json:"accent_color_id,omitempty"` - // Custom emoji identifier of emoji chosen by the chat for the reply header and link preview background. + // BackgroundCustomEmojiID is a custom emoji identifier of emoji chosen by + // the chat for the reply header and link preview background. // Returned only in getChat. // // optional BackgroundCustomEmojiID string `json:"background_custom_emoji_id,omitempty"` - // Identifier of the accent color for the chat's profile background. + // ProfileAccentColorID is ani dentifier of the accent color for the chat's profile background. // See profile accent colors for more details. Returned only in getChat. // // optional ProfileAccentColorID int `json:"profile_accent_color_id,omitempty"` - // Custom emoji identifier of the emoji chosen by the chat for its profile background. - // Returned only in getChat. + // ProfileBackgroundCustomEmojiID is a custom emoji identifier of the emoji chosen by + // the chat for its profile background. Returned only in getChat. // // optional ProfileBackgroundCustomEmojiID string `json:"profile_background_custom_emoji_id,omitempty"` - // Custom emoji identifier of emoji status of the other party + // EmojiStatusCustomEmojiID is a custom emoji identifier of emoji status of the other party // in a private chat. Returned only in getChat. // // optional EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` - // Expiration date of the emoji status of the chat or the other party + // EmojiStatusExpirationDate is a date of the emoji status of the chat or the other party // in a private chat, in Unix time, if any. Returned only in getChat. // // optional - EmojiStatusCustomEmojiDate int64 `json:"emoji_status_expiration_date,omitempty"` + EmojiStatusExpirationDate int64 `json:"emoji_status_expiration_date,omitempty"` // Bio is the bio of the other party in a private chat. Returned only in // getChat // @@ -396,8 +397,8 @@ type Chat struct { // // optional HasProtectedContent bool `json:"has_protected_content,omitempty"` - // True, if new chat members will have access to old messages; available only to chat administrators. - // Returned only in getChat. + // HasVisibleHistory is True, if new chat members will have access to old messages; + // available only to chat administrators. Returned only in getChat. // // optional HasVisibleHistory bool `json:"has_visible_history,omitempty"` @@ -449,23 +450,13 @@ func (c Chat) ChatConfig() ChatConfig { return ChatConfig{ChatID: c.ID} } -// This object describes a message that can be inaccessible to the bot. -// It can be one of -// -// Message -// InaccessibleMessage -type MaybeInaccessibleMessage struct { - Message - InaccessibleMessage -} - // InaccessibleMessage describes a message that was deleted or is otherwise inaccessible to the bot. type InaccessibleMessage struct { // Chat the message belonged to Chat Chat `json:"chat"` - // Unique message identifier inside the chat + // MessageID is unique message identifier inside the chat MessageID int `json:"message_id"` - // Always 0. The field can be used to differentiate regular and inaccessible messages. + // Date is always 0. The field can be used to differentiate regular and inaccessible messages. Date int `json:"date"` } @@ -492,8 +483,8 @@ type Message struct { // Date of the message was sent in Unix time Date int `json:"date"` // Chat is the conversation the message belongs to - Chat *Chat `json:"chat"` - // Information about the original message for forwarded messages + Chat Chat `json:"chat"` + // ForwardOrigin is information about the original message for forwarded messages // // optional ForwardOrigin *MessageOrigin `json:"forward_origin,omitempty"` @@ -764,19 +755,19 @@ type Message struct { // // optional GeneralForumTopicUnhidden *GeneralForumTopicUnhidden `json:"general_forum_topic_unhidden,omitempty"` - // Service message: a scheduled giveaway was created + // GiveawayCreated is as service message: a scheduled giveaway was created // // optional GiveawayCreated *GiveawayCreated `json:"giveaway_created,omitempty"` - // The message is a scheduled giveaway message + // Giveaway is a scheduled giveaway message // // optional Giveaway *Giveaway `json:"giveaway,omitempty"` - // A giveaway with public winners was completed + // GiveawayWinners is a giveaway with public winners was completed // // optional GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` - // Service message: a giveaway without public winners was completed + // GiveawayCompleted is a service message: a giveaway without public winners was completed // // optional GiveawayCompleted *GiveawayCompleted `json:"giveaway_completed,omitempty"` @@ -2205,6 +2196,21 @@ type CallbackQuery struct { GameShortName string `json:"game_short_name,omitempty"` } +// IsInaccessibleMessage method that shows whether message is inaccessible +func (c CallbackQuery) IsInaccessibleMessage() bool { + return c.Message != nil && c.Message.Date == 0 +} + +func (c CallbackQuery) GetInaccessibleMessage() InaccessibleMessage { + if c.Message == nil { + return InaccessibleMessage{} + } + return InaccessibleMessage{ + Chat: c.Message.Chat, + MessageID: c.Message.MessageID, + } +} + // ForceReply when receiving a message with this object, Telegram clients will // display a reply interface to the user (act as if the user has selected the // bot's message and tapped 'Reply'). This can be extremely useful if you want From a687eafa688398901a2328c55a597438d84d175d Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 7 Jan 2024 09:37:27 +0200 Subject: [PATCH 24/70] Add helper methods --- helper_methods.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/helper_methods.go b/helper_methods.go index de2dd8ae..99079f7a 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -855,6 +855,49 @@ func NewChatDescription(chatID int64, description string) SetChatDescriptionConf } } +func NewPinChatMessage(chatID int64, messageID int, disableNotification bool) PinChatMessageConfig { + return PinChatMessageConfig{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + DisableNotification: disableNotification, + } +} + +func NewUnpinChatMessage(chatID int64, messageID int) UnpinChatMessageConfig { + return UnpinChatMessageConfig{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + } +} + +func NewGetChatMember(chatID, userID int64) GetChatMemberConfig { + return GetChatMemberConfig{ + ChatConfigWithUser: ChatConfigWithUser{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + UserID: userID, + }, + } +} + +func NewChatMember(chatID, userID int64) ChatMemberConfig { + return ChatMemberConfig{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + UserID: userID, + } +} + // NewChatPhoto allows you to update the photo for a chat. func NewChatPhoto(chatID int64, photo RequestFileData) SetChatPhotoConfig { return SetChatPhotoConfig{ From 63e5c59035bfde1a7babea214eceb0e2e60e816f Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Tue, 9 Jan 2024 01:09:38 +0200 Subject: [PATCH 25/70] Fix UserIsBot and UserIsPremium fields in KeyboardButtonRequestUsers struct --- types.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types.go b/types.go index 2c4d8567..d3e88ee2 100644 --- a/types.go +++ b/types.go @@ -1958,13 +1958,13 @@ type KeyboardButtonRequestUsers struct { // If not specified, no additional restrictions are applied. // // optional - UserIsBot bool `json:"user_is_bot,omitempty"` + UserIsBot *bool `json:"user_is_bot,omitempty"` // UserIsPremium pass True to request a premium user, // pass False to request a non-premium user. // If not specified, no additional restrictions are applied. // // optional - UserIsPremium bool `json:"user_is_premium,omitempty"` + UserIsPremium *bool `json:"user_is_premium,omitempty"` // MaxQuantity is the maximum number of users to be selected. // 1-10. Defaults to 1 // From 5198d8b69e2b5eddd09e44f320be9f05ce544ebd Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Mon, 15 Jan 2024 11:29:03 +0100 Subject: [PATCH 26/70] Update README.md --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b18d15dd..9d57085b 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,12 @@ -# Golang bindings for the Telegram Bot API +> # Usage +> If you want to use this fork in the project that imports the original repo, the easiest way is to: +> - `git submodule add git@github.com:OvyFlash/telegram-bot-api.git telegram-bot-api` +> - `go mod edit --replace github.com/go-telegram-bot-api/telegram-bot-api/v5=./telegram-bot-api/` +> - `go mod tidy` +> And you're ready to go. +> Notice, that there have been several breaking changes since the telegram bot API v5 was released, so you might need to update your application. +# Golang bindings for the Telegram Bot API [![Go Reference](https://pkg.go.dev/badge/github.com/go-telegram-bot-api/telegram-bot-api/v5.svg)](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) [![Test](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml) From 9fd1f7e399b98750ec9d7174dd78d01203a32714 Mon Sep 17 00:00:00 2001 From: Etherdrake <67021215+Etherdrake@users.noreply.github.com> Date: Wed, 14 Feb 2024 12:35:58 -0500 Subject: [PATCH 27/70] Added NewDeleteMessages method to batch DeleteMessage requests within the same chat, create object and call bot.Request(object) --- helper_methods.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/helper_methods.go b/helper_methods.go index 99079f7a..93901d97 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -40,6 +40,19 @@ func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig { } } +// NewDeleteMessages creates a request to delete multiple messages. The messages have to be +// in the same chat. Provide the message ids as an array of integers +func NewDeleteMessages(chatID int64, messageIDs []int) DeleteMessagesConfig { + return DeleteMessagesConfig{ + BaseChatMessages: BaseChatMessages{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageIDs: messageIDs, + }, + } +} + // NewMessageToChannel creates a new Message that is sent to a channel // by username. // From 3beddeb22ff60cfbace496981642d4b926df41c2 Mon Sep 17 00:00:00 2001 From: Kurd <7689609+Alexkurd@users.noreply.github.com> Date: Sun, 18 Feb 2024 18:28:49 +0300 Subject: [PATCH 28/70] Fix Chat permissions mapping --- types.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/types.go b/types.go index d3e88ee2..44cd681c 100644 --- a/types.go +++ b/types.go @@ -2431,32 +2431,32 @@ type ChatMember struct { // True, if the user is allowed to send audios // // optional - CanSendAudios bool + CanSendAudios bool `json:"can_send_audios,omitempty"` // CanSendDocuments restricted only. // True, if the user is allowed to send documents // // optional - CanSendDocuments bool + CanSendDocuments bool `json:"can_send_documents,omitempty"` // CanSendPhotos is restricted only. // True, if the user is allowed to send photos // // optional - CanSendPhotos bool + CanSendPhotos bool `json:"can_send_photos,omitempty"` // CanSendVideos restricted only. // True, if the user is allowed to send videos // // optional - CanSendVideos bool + CanSendVideos bool `json:"can_send_videos,omitempty"` // CanSendVideoNotes restricted only. // True, if the user is allowed to send video notes // // optional - CanSendVideoNotes bool + CanSendVideoNotes bool `json:"can_send_video_notes,omitempty"` // CanSendVoiceNotes restricted only. // True, if the user is allowed to send voice notes // // optional - CanSendVoiceNotes bool + CanSendVoiceNotes bool `json:"can_send_voice_notes,omitempty"` // CanSendPolls restricted only. // True, if the user is allowed to send polls // @@ -2563,27 +2563,27 @@ type ChatPermissions struct { // CanSendAudios is true, if the user is allowed to send audios // // optional - CanSendAudios bool + CanSendAudios bool `json:"can_send_audios,omitempty"` // CanSendDocuments is true, if the user is allowed to send documents // // optional - CanSendDocuments bool + CanSendDocuments bool `json:"can_send_documents,omitempty"` // CanSendPhotos is true, if the user is allowed to send photos // // optional - CanSendPhotos bool + CanSendPhotos bool `json:"can_send_photos,omitempty"` // CanSendVideos is true, if the user is allowed to send videos // // optional - CanSendVideos bool + CanSendVideos bool `json:"can_send_videos,omitempty"` // CanSendVideoNotes is true, if the user is allowed to send video notes // // optional - CanSendVideoNotes bool + CanSendVideoNotes bool `json:"can_send_video_notes,omitempty"` // CanSendVoiceNotes is true, if the user is allowed to send voice notes // // optional - CanSendVoiceNotes bool + CanSendVoiceNotes bool `json:"can_send_voice_notes,omitempty"` // CanSendPolls is true, if the user is allowed to send polls, implies // can_send_messages // From a7a786d5aa211cb9758eb1dcf8b9b832d6dec896 Mon Sep 17 00:00:00 2001 From: dmekhov Date: Sun, 3 Mar 2024 18:27:18 +0300 Subject: [PATCH 29/70] fix ReplyToMessageID assignment in readme for compatibility with 7.0 api --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d57085b..d61b42c9 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ func main() { log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyToMessageID = update.Message.MessageID + msg.ReplyParameters.MessageID = update.Message.MessageID bot.Send(msg) } From 1e94209b0bafcfe776749da10c1a1907e25dac94 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Tue, 5 Mar 2024 20:02:42 +0200 Subject: [PATCH 30/70] Add optional Chat field in MessageOrigin struct to support MessageOrigin type channel --- types.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/types.go b/types.go index d3e88ee2..162be754 100644 --- a/types.go +++ b/types.go @@ -1157,10 +1157,12 @@ type MessageOrigin struct { // SenderUserName "hidden_user" only. // Name of the user that sent the message originally SenderUserName string `json:"sender_user_name,omitempty"` - // SenderChat "chat" and "channel". - // For "chat": Chat that sent the message originally - // For "channel": Channel chat to which the message was originally sent + // SenderChat "chat" only. + // Chat that sent the message originally SenderChat *Chat `json:"sender_chat,omitempty"` + // Chat "channel" only. + // Channel chat to which the message was originally sent + Chat *Chat `json:"chat,omitempty"` // AuthorSignature "chat" and "channel". // For "chat": For messages originally sent by an anonymous chat administrator, // original message author signature. From eced2e4efa397f26d23d2512bc3c063279bbd03a Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 10 Mar 2024 17:05:21 +0200 Subject: [PATCH 31/70] Fix API 7.0 update implementation. Add the fields chat_boost and removed_chat_boost to the type Update --- types.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types.go b/types.go index 1f069de8..d0909362 100644 --- a/types.go +++ b/types.go @@ -122,6 +122,14 @@ type Update struct { // // optional ChatJoinRequest *ChatJoinRequest `json:"chat_join_request,omitempty"` + // ChatBoostUpdated represents a boost added to a chat or changed. + // + // optional + ChatBoost *ChatBoostUpdated `json:"chat_boost,omitempty"` + // ChatBoostRemoved represents a boost removed from a chat. + // + // optional + ChatBoostRemoved *ChatBoostRemoved `json:"removed_chat_boost,omitempty"` } // SentFrom returns the user who sent an update. Can be nil, if Telegram did not provide information From 5f429897bc5140bbad019c6832f3205fd0dd955b Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Fri, 15 Mar 2024 21:28:47 +0100 Subject: [PATCH 32/70] Add missing `getCustomEmojiStickers` method from API v6.2 --- bot.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/bot.go b/bot.go index 39037b8d..7a282fc6 100644 --- a/bot.go +++ b/bot.go @@ -640,7 +640,20 @@ func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) return StickerSet{}, err } - var stickers StickerSet + var stickerSet StickerSet + err = json.Unmarshal(resp.Result, &stickerSet) + + return stickerSet, err +} + +// GetCustomEmojiStickers returns a slice of Sticker objects. +func (bot *BotAPI) GetCustomEmojiStickers(config GetCustomEmojiStickersConfig) ([]Sticker, error) { + resp, err := bot.Request(config) + if err != nil { + return []Sticker{}, err + } + + var stickers []Sticker err = json.Unmarshal(resp.Result, &stickers) return stickers, err From 2ff78b9568f0461c53b3897c7d553e89104a2c6a Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sat, 27 Apr 2024 15:16:43 +0300 Subject: [PATCH 33/70] BOT API 7.1 implementation --- types.go | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/types.go b/types.go index d0909362..2da8b9c2 100644 --- a/types.go +++ b/types.go @@ -384,6 +384,12 @@ type Chat struct { // // optional SlowModeDelay int `json:"slow_mode_delay,omitempty"` + // UnrestrictBoostCount is for supergroups, the minimum number of boosts that + // a non-administrator user needs to add in order to + // ignore slow mode and chat permissions. Returned only in getChat. + // + // optional + UnrestrictBoostCount int `json:"unrestrict_boost_count,omitempty"` // MessageAutoDeleteTime is the time after which all messages sent to the // chat will be automatically deleted; in seconds. Returned only in getChat. // @@ -420,6 +426,12 @@ type Chat struct { // // optional CanSetStickerSet bool `json:"can_set_sticker_set,omitempty"` + // CustomEmojiStickerSetName is 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. Returned only in getChat. + // + // optional + CustomEmojiStickerSetName string `json:"custom_emoji_sticker_set_name,omitempty"` // LinkedChatID is a unique identifier for the linked chat, i.e. the // discussion group identifier for a channel and vice versa; for supergroups // and channel chats. @@ -488,6 +500,11 @@ type Message struct { // // optional SenderChat *Chat `json:"sender_chat,omitempty"` + // SenderBoostCount is the number of boosts added by the user, + // if the sender of the message boosted the chat + // + // optional + SenderBoostCount int `json:"sender_boost_count,omitempty"` // Date of the message was sent in Unix time Date int `json:"date"` // Chat is the conversation the message belongs to @@ -520,6 +537,10 @@ type Message struct { // // optional Quote *TextQuote `json:"text_quote,omitempty"` + // ReplyToStory for replies to a story, the original story + // + // ReplyToStory + ReplyToStory *Story `json:"reply_to_story"` // ViaBot through which the message was sent; // // optional @@ -739,6 +760,10 @@ type Message struct { // // optional ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered,omitempty"` + // BoostAdded is a service message: user boosted the chat + // + // optional + BoostAdded *ChatBoostAdded `json:"boost_added,omitempty"` // ForumTopicCreated is a service message: forum topic created // // optional @@ -1318,7 +1343,12 @@ type Document struct { } // Story represents a message about a forwarded story in the chat. -type Story struct{} +type Story struct { + // Chat that posted the story + Chat Chat `json:"chat"` + // ID is an unique identifier for the story in the chat + ID int `json:"id"` +} // Video represents a video file. type Video struct { @@ -1579,6 +1609,12 @@ type MessageAutoDeleteTimerChanged struct { MessageAutoDeleteTime int `json:"message_auto_delete_time"` } +// ChatBoostAdded represents a service message about a user boosting a chat. +type ChatBoostAdded struct { + // BoostCount is a number of boosts added by the user + BoostCount int `json:"boost_count"` +} + // ForumTopicCreated represents a service message about a new forum topic // created in the chat. type ForumTopicCreated struct { From 6a83e6e519065dec0648c6a6e32d964afd71abec Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Thu, 2 May 2024 22:49:19 +0300 Subject: [PATCH 34/70] BOT API 7.2 implementation --- configs.go | 68 ++++++++++++- helper_methods.go | 7 ++ helper_structs.go | 6 ++ types.go | 236 ++++++++++++++++++++++++++++++++++++++++++++-- types_test.go | 2 + 5 files changed, 309 insertions(+), 10 deletions(-) diff --git a/configs.go b/configs.go index 268c9372..030d3c6f 100644 --- a/configs.go +++ b/configs.go @@ -60,6 +60,19 @@ const ( // UpdateTypeEditedChannelPost is new version of a channel post that is known to the bot and was edited UpdateTypeEditedChannelPost = "edited_channel_post" + // UpdateTypeBusinessConnection is the bot was connected to or disconnected from a business account, + // or a user edited an existing connection with the bot + UpdateTypeBusinessConnection = "business_connection" + + // UpdateTypeBusinessMessage is a new non-service message from a connected business account + UpdateTypeBusinessMessage = "business_message" + + // UpdateTypeEditedBusinessMessage is a new version of a message from a connected business account + UpdateTypeEditedBusinessMessage = "edited_business_message" + + // UpdateTypeDeletedBusinessMessages are the messages were deleted from a connected business account + UpdateTypeDeletedBusinessMessages = "deleted_business_messages" + // UpdateTypeMessageReactionis is a reaction to a message was changed by a user UpdateTypeMessageReaction = "message_reaction" @@ -2216,7 +2229,6 @@ type NewStickerSetConfig struct { Name string Title string Stickers []InputSticker - StickerFormat string StickerType string NeedsRepainting bool //optional; 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 } @@ -2231,7 +2243,6 @@ func (config NewStickerSetConfig) params() (Params, error) { params.AddNonZero64("user_id", config.UserID) params["name"] = config.Name params["title"] = config.Title - params["sticker_format"] = config.StickerFormat params.AddBool("needs_repainting", config.NeedsRepainting) params.AddNonEmpty("sticker_type", string(config.StickerType)) @@ -2363,6 +2374,33 @@ func (config DeleteStickerConfig) params() (Params, error) { return params, nil } +// ReplaceStickerInSetConfig allows you 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. +type ReplaceStickerInSetConfig struct { + UserID int64 + Name string + OldSticker string + Sticker InputSticker +} + +func (config ReplaceStickerInSetConfig) method() string { + return "replaceStickerInSet" +} + +func (config ReplaceStickerInSetConfig) params() (Params, error) { + params := make(Params) + + params.AddNonZero64("user_id", config.UserID) + params["name"] = config.Name + params["old_sticker"] = config.OldSticker + + err := params.AddInterface("sticker", config.Sticker) + + return params, err +} + // SetStickerEmojiListConfig allows you 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 type SetStickerEmojiListConfig struct { Sticker string @@ -2425,6 +2463,7 @@ type SetStickerSetThumbConfig struct { Name string UserID int64 Thumb RequestFileData + Format string } func (config SetStickerSetThumbConfig) method() string { @@ -2435,6 +2474,8 @@ func (config SetStickerSetThumbConfig) params() (Params, error) { params := make(Params) params["name"] = config.Name + params["format"] = config.Format + params.AddNonZero64("user_id", config.UserID) return params, nil @@ -2739,6 +2780,29 @@ func (config GetUserChatBoostsConfig) params() (Params, error) { return params, err } +type ( + GetBusinessConnectionConfig struct { + BusinessConnectionID BusinessConnectionID + } + BusinessConnectionID string +) + +func (GetBusinessConnectionConfig) method() string { + return "getBusinessConnection" +} + +func (config GetBusinessConnectionConfig) params() (Params, error) { + return config.BusinessConnectionID.params() +} + +func (config BusinessConnectionID) params() (Params, error) { + params := make(Params) + + params["business_connection_id"] = string(config) + + return params, nil +} + // GetMyCommandsConfig gets a list of the currently registered commands. type GetMyCommandsConfig struct { Scope *BotCommandScope diff --git a/helper_methods.go b/helper_methods.go index 93901d97..db786449 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -1075,6 +1075,13 @@ func NewSetMyName(languageCode, name string) SetMyNameConfig { } } +// NewGetBusinessConnection gets business connection request struct +func NewGetBusinessConnection(id string) GetBusinessConnectionConfig { + return GetBusinessConnectionConfig{ + BusinessConnectionID: BusinessConnectionID(id), + } +} + // NewGetMyCommandsWithScope allows you to set the registered commands for a // given scope. func NewGetMyCommandsWithScope(scope BotCommandScope) GetMyCommandsConfig { diff --git a/helper_structs.go b/helper_structs.go index 008fc474..921099e1 100644 --- a/helper_structs.go +++ b/helper_structs.go @@ -19,6 +19,7 @@ func (base ChatConfig) paramsWithKey(key string) (Params, error) { // BaseChat is base type for all chat config types. type BaseChat struct { ChatConfig + BusinessConnectionID BusinessConnectionID MessageThreadID int ProtectContent bool ReplyMarkup interface{} @@ -31,6 +32,11 @@ func (chat *BaseChat) params() (Params, error) { if err != nil { return params, err } + p1, err := chat.BusinessConnectionID.params() + if err != nil { + return params, err + } + params.Merge(p1) params.AddNonZero("message_thread_id", chat.MessageThreadID) params.AddBool("disable_notification", chat.DisableNotification) diff --git a/types.go b/types.go index 2da8b9c2..51aa3336 100644 --- a/types.go +++ b/types.go @@ -61,6 +61,26 @@ type Update struct { // // optional EditedChannelPost *Message `json:"edited_channel_post,omitempty"` + // BusinessConnection the bot was connected to or disconnected from a + // business account, or a user edited an existing connection with the bot + // + // optional + BusinessConnection *BusinessConnection `json:"business_connection,omitempty"` + // BusinessMessage is a new non-service message from a + // connected business account + // + // optional + BusinessMessage *Message `json:"business_message,omitempty"` + // EditedBusinessMessage is a new version of a message from a + // connected business account + // + // optional + EditedBusinessMessage *Message `json:"edited_business_message,omitempty"` + // DeletedBusinessMessages are the messages were deleted from a + // connected business account + // + // optional + DeletedBusinessMessages *BusinessMessagesDeleted `json:"deleted_business_messages,omitempty"` // MessageReaction is a reaction to a message was changed by a user. // // optional @@ -237,6 +257,12 @@ type User struct { // // optional SupportsInlineQueries bool `json:"supports_inline_queries,omitempty"` + // CanConnectToBusiness is true, if the bot can be connected to a + // Telegram Business account to receive its messages. + // Returned only in getMe. + // + // optional + CanConnectToBusiness bool `json:"can_connect_to_business,omitempty"` } // String displays a simple text version of a user. @@ -292,6 +318,31 @@ type Chat struct { // // optional ActiveUsernames []string `json:"active_usernames,omitempty"` + // Birthdate for private chats, the date of birth of the user. + // Returned only in getChat. + // + // optional + Birthdate *Birthdate `json:"birthdate,omitempty"` + // BusinessIntro is for private chats with business accounts, the intro of the business. + // Returned only in getChat. + // + // optional + BusinessIntro *BusinessIntro `json:"business_intro,omitempty"` + // BusinessLocation is for private chats with business accounts, the location + // of the business. Returned only in getChat. + // + // optional + BusinessLocation *BusinessLocation `json:"business_location,omitempty"` + // BusinessOpeningHours is for private chats with business accounts, + // the opening hours of the business. Returned only in getChat. + // + // optional + BusinessOpeningHours *BusinessOpeningHours `json:"business_opening_hours,omitempty"` + // PersonalChat is for private chats, the personal channel of the user. + // Returned only in getChat. + // + // optional + PersonalChat *Chat `json:"personal_chat,omitempty"` // AvailableReactions is a list of available reactions allowed in the chat. // If omitted, then all emoji reactions are allowed. Returned only in getChat. // @@ -426,8 +477,8 @@ type Chat struct { // // optional CanSetStickerSet bool `json:"can_set_sticker_set,omitempty"` - // CustomEmojiStickerSetName is for supergroups, the name of the group's - // custom emoji sticker set. Custom emoji from this set can be used by all + // CustomEmojiStickerSetName is 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. Returned only in getChat. // // optional @@ -505,8 +556,21 @@ type Message struct { // // optional SenderBoostCount int `json:"sender_boost_count,omitempty"` + // SenderBusinessBot is 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. + // + // optional + SenderBusinessBot *User `json:"sender_business_bot,omitempty"` // Date of the message was sent in Unix time Date int `json:"date"` + // BusinessConnectionID is an 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. + // + // optional + BusinessConnectionID string `json:"business_connection_id,omitempty"` // Chat is the conversation the message belongs to Chat Chat `json:"chat"` // ForwardOrigin is information about the original message for forwarded messages @@ -553,6 +617,11 @@ type Message struct { // // optional HasProtectedContent bool `json:"has_protected_content,omitempty"` + // IsFromOffline is 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 + // + // optional + IsFromOffline bool `json:"is_from_offline,omitempty"` // MediaGroupID is the unique identifier of a media message group this message belongs to; // // optional @@ -1663,13 +1732,37 @@ type GeneralForumTopicHidden struct { type GeneralForumTopicUnhidden struct { } +// SharedUser contains information about a user that was +// shared with the bot using a KeyboardButtonRequestUsers button. +type SharedUser struct { + // UserID is the identifier of the shared user. + UserID int64 `json:"user_id"` + // FirstName of the user, if the name was requested by the bot. + // + // optional + FirstName *string `json:"first_name,omitempty"` + // LastName of the user, if the name was requested by the bot. + // + // optional + LastName *string `json:"last_name,omitempty"` + // Username of the user, if the username was requested by the bot. + // + // optional + UserName *string `json:"username,omitempty"` + // Photo is array of available sizes of the chat photo, + // if the photo was requested by the bot + // + // optional + Photo []PhotoSize `json:"photo,omitempty"` +} + // UsersShared object contains information about the user whose identifier // was shared with the bot using a KeyboardButtonRequestUser button. type UsersShared struct { // RequestID is an indentifier of the request. RequestID int `json:"request_id"` - // UserIDs are identifiers of the shared user. - UserIDs []int64 `json:"user_ids"` + // Users shared with the bot. + Users []SharedUser `json:"users"` } // ChatShared contains information about the chat whose identifier @@ -1679,6 +1772,20 @@ type ChatShared struct { RequestID int `json:"request_id"` // ChatID is an identifier of the shared chat. ChatID int64 `json:"chat_id"` + // Title of the chat, if the title was requested by the bot. + // + // optional + Title *string `json:"title,omitempty"` + // UserName of the chat, if the username was requested by + // the bot and available. + // + // optional + UserName *string `json:"username,omitempty"` + // Photo is array of available sizes of the chat photo, + // if the photo was requested by the bot + // + // optional + Photo []PhotoSize `json:"photo,omitempty"` } // WriteAccessAllowed represents a service message about a user allowing a bot @@ -2016,6 +2123,18 @@ type KeyboardButtonRequestUsers struct { // // optional MaxQuantity int `json:"max_quantity,omitempty"` + // RequestName pass True to request the users' first and last names + // + // optional + RequestName bool `json:"request_name,omitempty"` + // RequestUsername pass True to request the users' usernames + // + // optional + RequestUsername bool `json:"request_username,omitempty"` + // RequestPhoto pass True to request the users' photos + // + // optional + RequestPhoto bool `json:"request_photo,omitempty"` } // KeyboardButtonRequestChat defines the criteria used to request @@ -2062,6 +2181,18 @@ type KeyboardButtonRequestChat struct { // // optional BotIsMember bool `json:"bot_is_member,omitempty"` + // RequestTitle pass True to request the chat's title + // + // optional + RequestTitle bool `json:"request_title,omitempty"` + // RequestUsername pass True to request the chat's username + // + // optional + RequestUsername bool `json:"request_username,omitempty"` + // RequestPhoto pass True to request the chat's photo + // + // optional + RequestPhoto bool `json:"request_photo,omitempty"` } // KeyboardButtonPollType represents type of poll, which is allowed to @@ -2688,6 +2819,64 @@ func (c *ChatPermissions) CanSendMediaMessages() bool { c.CanSendVideoNotes && c.CanSendVoiceNotes } +// Birthdate represents a user's birthdate +type Birthdate struct { + // Day of the user's birth; 1-31 + Day int `json:"day"` + // Month of the user's birth; 1-12 + Month int `json:"month"` + // Year of the user's birth + // + // optional + Year *int `json:"year,omitempty"` +} + +// BusinessIntro represents a basic information about your business +type BusinessIntro struct { + // Title text of the business intro + // + // optional + Title *string `json:"title,omitempty"` + // Message text of the business intro + // + // optional + Message *string `json:"message,omitempty"` + // Sticker of the business intro + // + // optional + Sticker *Sticker `json:"sticker,omitempty"` +} + +// BusinessLocation represents a business geodata +type BusinessLocation struct { + // Address of the business + Address string `json:"address"` + // Location of the business + // + // optional + Location *Location `json:"location,omitempty"` +} + +// BusinessOpeningHoursInterval represents a business working interval +type BusinessOpeningHoursInterval struct { + // OpeningMinute is 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 int `json:"opening_minute"` + // ClosingMinute is 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 int `json:"closing_minute"` +} + +// BusinessOpeningHours represents a set of business working intervals +type BusinessOpeningHours struct { + // TimeZoneName is the unique name of the time zone + // for which the opening hours are defined + TimeZoneName string `json:"time_zone_name"` + // OpeningHours is the list of time intervals describing + // business opening hours + OpeningHours []BusinessOpeningHoursInterval `json:"opening_hours"` +} + // ChatLocation represents a location to which a chat is connected. type ChatLocation struct { // Location is the location to which the supergroup is connected. Can't be a @@ -2904,6 +3093,38 @@ type UserChatBoosts struct { Boosts []ChatBoost `json:"boosts"` } +// BusinessConnection describes the connection of the bot with a business account. +type BusinessConnection struct { + // ID is an unique identifier of the business connection + ID string `json:"id"` + // User is a business account user that created the business connection + User User `json:"user"` + // UserChatID identifier of a private chat with the user who + // created the business connection. + UserChatID int64 `json:"user_chat_id"` + // Date the connection was established in Unix time + Date int64 `json:"date"` + // CanReply is True, if the bot can act on behalf of the + // business account in chats that were active in the last 24 hours + CanReply bool `json:"can_reply"` + // IsEnabled is True, if the connection is active + IsEnabled bool `json:"is_enabled"` +} + +// BusinessMessagesDeleted is received when messages are deleted +// from a connected business account. +type BusinessMessagesDeleted struct { + // BusinessConnectionID is an unique identifier + // of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Chat is the 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"` + // MessageIDs is a JSON-serialized list of identifiers of deleted messages + // in the chat of the business account + MessageIDs []int `json:"message_ids"` +} + // ResponseParameters are various errors that can be returned in APIResponse. type ResponseParameters struct { // The group has been migrated to a supergroup with the specified identifier. @@ -3139,10 +3360,6 @@ type StickerSet struct { Title string `json:"title"` // StickerType of stickers in the set, currently one of “regular”, “mask”, “custom_emoji” StickerType string `json:"sticker_type"` - // IsAnimated true, if the sticker set contains animated stickers - IsAnimated bool `json:"is_animated"` - // IsVideo true, if the sticker set contains video stickers - IsVideo bool `json:"is_video"` // ContainsMasks true, if the sticker set contains masks // // deprecated. Use sticker_type instead @@ -3190,6 +3407,9 @@ type MaskPosition struct { 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, upload a new one using multipart/form-data, or pass “attach://” to upload a new one using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. Sticker RequestFile `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"` // Position where the mask should be placed on faces. For “mask” stickers only. diff --git a/types_test.go b/types_test.go index 4fd9e440..ac1f3bc5 100644 --- a/types_test.go +++ b/types_test.go @@ -308,6 +308,7 @@ var ( _ Chattable = FileConfig{} _ Chattable = ForwardConfig{} _ Chattable = GameConfig{} + _ Chattable = GetBusinessConnectionConfig{} _ Chattable = GetChatMemberConfig{} _ Chattable = GetChatMenuButtonConfig{} _ Chattable = GetGameHighScoresConfig{} @@ -324,6 +325,7 @@ var ( _ Chattable = PinChatMessageConfig{} _ Chattable = PreCheckoutConfig{} _ Chattable = PromoteChatMemberConfig{} + _ Chattable = ReplaceStickerInSetConfig{} _ Chattable = RestrictChatMemberConfig{} _ Chattable = RevokeChatInviteLinkConfig{} _ Chattable = SendPollConfig{} From 1ad852c7652bb1c0226da1214678f9dc70dcf3d5 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Tue, 7 May 2024 17:32:47 +0300 Subject: [PATCH 35/70] Bot API 7.3 implementation --- bot.go | 6 +-- bot_test.go | 2 +- configs.go | 10 ++++- helper_methods.go | 9 +++- types.go | 111 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 132 insertions(+), 6 deletions(-) diff --git a/bot.go b/bot.go index 7a282fc6..1a16c273 100644 --- a/bot.go +++ b/bot.go @@ -553,13 +553,13 @@ func WriteToHTTPResponse(w http.ResponseWriter, c Chattable) error { } // GetChat gets information about a chat. -func (bot *BotAPI) GetChat(config ChatInfoConfig) (Chat, error) { +func (bot *BotAPI) GetChat(config ChatInfoConfig) (ChatFullInfo, error) { resp, err := bot.Request(config) if err != nil { - return Chat{}, err + return ChatFullInfo{}, err } - var chat Chat + var chat ChatFullInfo err = json.Unmarshal(resp.Result, &chat) return chat, err diff --git a/bot_test.go b/bot_test.go index 40633d62..d61a73b5 100644 --- a/bot_test.go +++ b/bot_test.go @@ -933,7 +933,7 @@ func TestUnpinAllChatMessages(t *testing.T) { func TestPolls(t *testing.T) { bot, _ := getBot(t) - poll := NewPoll(SupergroupChatID, "Are polls working?", "Yes", "No") + poll := NewPoll(SupergroupChatID, "Are polls working?", NewPollOption("Yes"), NewPollOption("No")) msg, err := bot.Send(poll) if err != nil { diff --git a/configs.go b/configs.go index 030d3c6f..b11a5841 100644 --- a/configs.go +++ b/configs.go @@ -829,6 +829,7 @@ type EditMessageLiveLocationConfig struct { BaseEdit Latitude float64 // required Longitude float64 // required + LivePeriod int //optional HorizontalAccuracy float64 // optional Heading int // optional ProximityAlertRadius int // optional @@ -841,6 +842,7 @@ func (config EditMessageLiveLocationConfig) params() (Params, error) { params.AddNonZeroFloat("longitude", config.Longitude) params.AddNonZeroFloat("horizontal_accuracy", config.HorizontalAccuracy) params.AddNonZero("heading", config.Heading) + params.AddNonZero("live_period", config.LivePeriod) params.AddNonZero("proximity_alert_radius", config.ProximityAlertRadius) return params, err @@ -924,7 +926,9 @@ func (config ContactConfig) method() string { type SendPollConfig struct { BaseChat Question string - Options []string + QuestionParseMode string // optional + QuestionEntities []MessageEntity // optional + Options []InputPollOption IsAnonymous bool Type string AllowsMultipleAnswers bool @@ -944,6 +948,10 @@ func (config SendPollConfig) params() (Params, error) { } params["question"] = config.Question + params.AddNonEmpty("question_parse_mode", config.QuestionParseMode) + if err = params.AddInterface("question_entities", config.QuestionEntities); err != nil { + return params, err + } if err = params.AddInterface("options", config.Options); err != nil { return params, err } diff --git a/helper_methods.go b/helper_methods.go index db786449..747d4a04 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -933,7 +933,7 @@ func NewDeleteChatPhoto(chatID int64) DeleteChatPhotoConfig { } // NewPoll allows you to create a new poll. -func NewPoll(chatID int64, question string, options ...string) SendPollConfig { +func NewPoll(chatID int64, question string, options ...InputPollOption) SendPollConfig { return SendPollConfig{ BaseChat: BaseChat{ ChatConfig: ChatConfig{ChatID: chatID}, @@ -944,6 +944,13 @@ func NewPoll(chatID int64, question string, options ...string) SendPollConfig { } } +// NewPollOption allows you to create poll option +func NewPollOption(text string) InputPollOption { + return InputPollOption{ + Text: text, + } +} + // NewStopPoll allows you to stop a poll. func NewStopPoll(chatID int64, messageID int) StopPollConfig { return StopPollConfig{ diff --git a/types.go b/types.go index 51aa3336..ec75ffe8 100644 --- a/types.go +++ b/types.go @@ -311,6 +311,11 @@ type Chat struct { // // optional IsForum bool `json:"is_forum,omitempty"` +} + +// ChatFullInfo contains full information about a chat. +type ChatFullInfo struct { + Chat // Photo is a chat photo Photo *ChatPhoto `json:"photo"` // If non-empty, the list of all active chat usernames; @@ -355,6 +360,8 @@ type Chat struct { // // optional AccentColorID int `json:"accent_color_id,omitempty"` + // The maximum number of reactions that can be set on a message in the chat + MaxReactionCount int `json:"max_reaction_count"` // BackgroundCustomEmojiID is a custom emoji identifier of emoji chosen by // the chat for the reply header and link preview background. // Returned only in getChat. @@ -833,6 +840,10 @@ type Message struct { // // optional BoostAdded *ChatBoostAdded `json:"boost_added,omitempty"` + // Service message: chat background set + // + // optional + ChatBackgroundSet *ChatBackground `json:"chat_background_set,omitempty"` // ForumTopicCreated is a service message: forum topic created // // optional @@ -1528,10 +1539,31 @@ type Dice struct { type PollOption struct { // Text is the option text, 1-100 characters Text string `json:"text"` + // Special entities that appear in the option text. + // Currently, only custom emoji entities are allowed in poll option texts + // + // optional + TextEntities []MessageEntity `json:"text_entities"` // VoterCount is the number of users that voted for this option VoterCount int `json:"voter_count"` } +// InputPollOption contains information about one answer option in a poll to send. +type InputPollOption struct { + // Option text, 1-100 characters + Text string `json:"text"` + // Mode for parsing entities in the text. See formatting options for more details. + // Currently, only custom emoji entities are allowed + // + // optional + TextParseMode string `json:"text_parse_mode"` + // A JSON-serialized list of special entities that appear in the poll option text. + // It can be specified instead of text_parse_mode + // + // optional + TextEntities []MessageEntity `json:"text_entities"` +} + // PollAnswer represents an answer of a user in a non-anonymous poll. type PollAnswer struct { // PollID is the unique poll identifier @@ -1557,6 +1589,11 @@ type Poll struct { ID string `json:"id"` // Question is the poll question, 1-255 characters Question string `json:"question"` + // Special entities that appear in the question. + // Currently, only custom emoji entities are allowed in poll questions + // + // optional + QuestionEntities []MessageEntity `json:"question_entities"` // Options is the list of poll options Options []PollOption `json:"options"` // TotalVoterCount is the total numbers of users who voted in the poll @@ -1610,6 +1647,7 @@ type Location struct { HorizontalAccuracy float64 `json:"horizontal_accuracy,omitempty"` // LivePeriod is time relative to the message sending date, during which the // location can be updated, in seconds. For active live locations only. + // Use 0x7FFFFFFF (2147483647 - max positive Int) to edit indefinitely // // optional LivePeriod int `json:"live_period,omitempty"` @@ -1684,6 +1722,73 @@ type ChatBoostAdded struct { BoostCount int `json:"boost_count"` } +// BackgroundFill describes the way a background is filled based on the selected colors. +// Currently, it can be one of: +// - BackgroundFillSolid +// - BackgroundFillGradient +// - BackgroundFillFreeformGradient +type BackgroundFill struct { + // Type of the background fill, can be: + // - solid + // - gradient + // - freeform_gradient + Type string `json:"type"` + // The color of the background fill in the RGB24 format + Color int `json:"color"` + // Top color of the gradient in the RGB24 format + TopColor int `json:"top_color"` + // Bottom color of the gradient in the RGB24 format + BottomColor int `json:"bottom_color"` + // Clockwise rotation angle of the background fill in degrees; 0-359 + RotationAngle int `json:"rotation_angle"` + // A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format + Colors []int `json:"colors"` +} + +// BackgroundType describes the type of a background. Currently, it can be one of: +// - BackgroundTypeFill +// - BackgroundTypeWallpaper +// - BackgroundTypePattern +// - BackgroundTypeChatTheme +type BackgroundType struct { + // Type of the background. + // Currently, it can be one of: + // - fill + // - wallpaper + // - pattern + // - chat_theme + Type string `json:"type"` + // The background fill or fill that is combined with the pattern + Fill BackgroundFill `json:"fill"` + // Dimming of the background in dark themes, as a percentage; 0-100 + DarkThemeDimming int `json:"dark_theme_dimming"` + // Document with the wallpaper / pattern + Document Document `json:"document"` + // True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12 + // + // optional + IsBlurred bool `json:"is_blurred"` + // True, if the background moves slightly when the device is tilted + // + // optional + IsMoving bool `json:"is_moving"` + // Intensity of the pattern when it is shown above the filled background; 0-100 + Intensity int `json:"intensity"` + // 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 + // + // optional + IsInverted bool `json:"is_inverted"` + // Name of the chat theme, which is usually an emoji + ThemeName string `json:"theme_name"` +} + +// ChatBackground represents a chat background. +type ChatBackground struct { + // Type of the background + Type BackgroundType `json:"type"` +} + // ForumTopicCreated represents a service message about a new forum topic // created in the chat. type ForumTopicCreated struct { @@ -2702,6 +2807,12 @@ type ChatMemberUpdated struct { // // optional InviteLink *ChatInviteLink `json:"invite_link,omitempty"` + // ViaJoinRequest is true, if the user joined the chat + // after sending a direct join request + // and being approved by an administrator + // + // optional + ViaJoinRequest bool `json:"via_join_request,omitempty"` // ViaChatFolderInviteLink is True, if the user joined the chat // via a chat folder invite link // From 3dfc49d5c1144743b3911cc8ff22b49f114aca8e Mon Sep 17 00:00:00 2001 From: stdkhai Date: Fri, 10 May 2024 17:19:52 +0300 Subject: [PATCH 36/70] add missed omitempty tag & update comments --- types.go | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/types.go b/types.go index ec75ffe8..0828a0bc 100644 --- a/types.go +++ b/types.go @@ -1543,7 +1543,7 @@ type PollOption struct { // Currently, only custom emoji entities are allowed in poll option texts // // optional - TextEntities []MessageEntity `json:"text_entities"` + TextEntities []MessageEntity `json:"text_entities,omitempty"` // VoterCount is the number of users that voted for this option VoterCount int `json:"voter_count"` } @@ -1556,12 +1556,12 @@ type InputPollOption struct { // Currently, only custom emoji entities are allowed // // optional - TextParseMode string `json:"text_parse_mode"` + TextParseMode string `json:"text_parse_mode,omitempty"` // A JSON-serialized list of special entities that appear in the poll option text. // It can be specified instead of text_parse_mode // // optional - TextEntities []MessageEntity `json:"text_entities"` + TextEntities []MessageEntity `json:"text_entities,omitempty"` } // PollAnswer represents an answer of a user in a non-anonymous poll. @@ -1593,7 +1593,7 @@ type Poll struct { // Currently, only custom emoji entities are allowed in poll questions // // optional - QuestionEntities []MessageEntity `json:"question_entities"` + QuestionEntities []MessageEntity `json:"question_entities,omitempty"` // Options is the list of poll options Options []PollOption `json:"options"` // TotalVoterCount is the total numbers of users who voted in the poll @@ -1733,14 +1733,19 @@ type BackgroundFill struct { // - gradient // - freeform_gradient Type string `json:"type"` + // BackgroundFillSolid only. // The color of the background fill in the RGB24 format Color int `json:"color"` + // BackgroundFillGradient only. // Top color of the gradient in the RGB24 format TopColor int `json:"top_color"` + // BackgroundFillGradient only. // Bottom color of the gradient in the RGB24 format BottomColor int `json:"bottom_color"` + // BackgroundFillGradient only. // Clockwise rotation angle of the background fill in degrees; 0-359 RotationAngle int `json:"rotation_angle"` + // BackgroundFillFreeformGradient only. // A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format Colors []int `json:"colors"` } @@ -1758,27 +1763,35 @@ type BackgroundType struct { // - pattern // - chat_theme Type string `json:"type"` + // BackgroundTypeFill and BackgroundTypePattern only. // The background fill or fill that is combined with the pattern Fill BackgroundFill `json:"fill"` + // BackgroundTypeFill and BackgroundTypeWallpaper only. // Dimming of the background in dark themes, as a percentage; 0-100 DarkThemeDimming int `json:"dark_theme_dimming"` + // BackgroundTypeWallpaper and BackgroundTypePattern only. // Document with the wallpaper / pattern Document Document `json:"document"` + // BackgroundTypeWallpaper only. // True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12 // // optional - IsBlurred bool `json:"is_blurred"` + IsBlurred bool `json:"is_blurred,omitempty"` + // BackgroundTypeWallpaper and BackgroundTypePattern only. // True, if the background moves slightly when the device is tilted // // optional - IsMoving bool `json:"is_moving"` + IsMoving bool `json:"is_moving,omitempty"` + // BackgroundTypePattern only. // Intensity of the pattern when it is shown above the filled background; 0-100 Intensity int `json:"intensity"` + // BackgroundTypePattern only. // 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 // // optional - IsInverted bool `json:"is_inverted"` + IsInverted bool `json:"is_inverted,omitempty"` + // BackgroundTypeChatTheme only. // Name of the chat theme, which is usually an emoji ThemeName string `json:"theme_name"` } From d0fa8e929e4d1416b1db97b1d0c004816ca4e5df Mon Sep 17 00:00:00 2001 From: bobra Date: Wed, 15 May 2024 02:57:25 +0200 Subject: [PATCH 37/70] Fix missing ParseMode in InlineQueryResultVideo ParseMode for this type actually exists, but was missed in the original repo. https://core.telegram.org/bots/api#inlinequeryresultvideo --- types.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/types.go b/types.go index 0828a0bc..4aa4b810 100644 --- a/types.go +++ b/types.go @@ -4406,9 +4406,15 @@ type InlineQueryResultVideo struct { // // optional Caption string `json:"caption,omitempty"` - // Width video width + // ParseMode mode for parsing entities in the video caption. + // See formatting options for more details + // (https://core.telegram.org/bots/api#formatting-options). // // optional + ParseMode string `json:"parse_mode,omitempty"` + // Width video width + // + // optional Width int `json:"video_width,omitempty"` // Height video height // @@ -4448,7 +4454,7 @@ type InlineQueryResultVoice struct { // // optional Caption string `json:"caption,omitempty"` - // ParseMode mode for parsing entities in the video caption. + // ParseMode mode for parsing entities in the voice caption. // See formatting options for more details // (https://core.telegram.org/bots/api#formatting-options). // From bece330506ef0674ff37c1bc068794f18c1b4bd9 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Fri, 31 May 2024 19:21:42 +0300 Subject: [PATCH 38/70] Bot API 7.4 implementation --- configs.go | 80 ++++++++++++++++++++++++++++++++--------------- helper_structs.go | 12 ++++--- types.go | 65 ++++++++++++++++++++++++++++++++++---- types_test.go | 1 + 4 files changed, 122 insertions(+), 36 deletions(-) diff --git a/configs.go b/configs.go index b11a5841..dfb607f7 100644 --- a/configs.go +++ b/configs.go @@ -379,11 +379,12 @@ func (config ForwardMessagesConfig) method() string { // CopyMessageConfig contains information about a copyMessage request. type CopyMessageConfig struct { BaseChat - FromChat ChatConfig - MessageID int - Caption string - ParseMode string - CaptionEntities []MessageEntity + FromChat ChatConfig + MessageID int + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config CopyMessageConfig) params() (Params, error) { @@ -400,6 +401,7 @@ func (config CopyMessageConfig) params() (Params, error) { params.AddNonZero("message_id", config.MessageID) params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) return params, err @@ -442,10 +444,11 @@ func (config CopyMessagesConfig) method() string { type PhotoConfig struct { BaseFile BaseSpoiler - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity + Thumb RequestFileData + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config PhotoConfig) params() (Params, error) { @@ -456,6 +459,7 @@ func (config PhotoConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) if err != nil { return params, err @@ -609,12 +613,13 @@ func (config StickerConfig) files() []RequestFile { type VideoConfig struct { BaseFile BaseSpoiler - Thumb RequestFileData - Duration int - Caption string - ParseMode string - CaptionEntities []MessageEntity - SupportsStreaming bool + Thumb RequestFileData + Duration int + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool + SupportsStreaming bool } func (config VideoConfig) params() (Params, error) { @@ -627,6 +632,7 @@ func (config VideoConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("supports_streaming", config.SupportsStreaming) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) if err != nil { return params, err @@ -665,11 +671,12 @@ func (config VideoConfig) files() []RequestFile { type AnimationConfig struct { BaseFile BaseSpoiler - Duration int - Thumb RequestFileData - Caption string - ParseMode string - CaptionEntities []MessageEntity + Duration int + Thumb RequestFileData + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config AnimationConfig) params() (Params, error) { @@ -681,6 +688,7 @@ func (config AnimationConfig) params() (Params, error) { params.AddNonZero("duration", config.Duration) params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) if err != nil { return params, err @@ -1109,9 +1117,10 @@ func (config EditMessageTextConfig) method() string { // EditMessageCaptionConfig allows you to modify the caption of a message. type EditMessageCaptionConfig struct { BaseEdit - Caption string - ParseMode string - CaptionEntities []MessageEntity + Caption string + ParseMode string + CaptionEntities []MessageEntity + ShowCaptionAboveMedia bool } func (config EditMessageCaptionConfig) params() (Params, error) { @@ -1122,6 +1131,7 @@ func (config EditMessageCaptionConfig) params() (Params, error) { params["caption"] = config.Caption params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) err = params.AddInterface("caption_entities", config.CaptionEntities) return params, err @@ -1894,12 +1904,12 @@ func (config InvoiceConfig) params() (Params, error) { params["title"] = config.Title params["description"] = config.Description params["payload"] = config.Payload - params["provider_token"] = config.ProviderToken params["currency"] = config.Currency if err = params.AddInterface("prices", config.Prices); err != nil { return params, err } + params.AddNonEmpty("provider_token", config.ProviderToken) params.AddNonZero("max_tip_amount", config.MaxTipAmount) err = params.AddInterface("suggested_tip_amounts", config.SuggestedTipAmounts) params.AddNonEmpty("start_parameter", config.StartParameter) @@ -1953,12 +1963,12 @@ func (config InvoiceLinkConfig) params() (Params, error) { params["title"] = config.Title params["description"] = config.Description params["payload"] = config.Payload - params["provider_token"] = config.ProviderToken params["currency"] = config.Currency if err := params.AddInterface("prices", config.Prices); err != nil { return params, err } + params.AddNonEmpty("provider_token", config.ProviderToken) params.AddNonZero("max_tip_amount", config.MaxTipAmount) err := params.AddInterface("suggested_tip_amounts", config.SuggestedTipAmounts) params.AddNonEmpty("provider_data", config.ProviderData) @@ -2025,6 +2035,26 @@ func (config PreCheckoutConfig) params() (Params, error) { return params, nil } +// RefundStarPaymentConfig refunds a successful payment in Telegram Stars. +// Returns True on success. +type RefundStarPaymentConfig struct { + UserID int64 //required + TelegramPaymentChargeID string //required +} + +func (config RefundStarPaymentConfig) method() string { + return "refundStarPayment" +} + +func (config RefundStarPaymentConfig) params() (Params, error) { + params := make(Params) + + params["telegram_payment_charge_id"] = config.TelegramPaymentChargeID + params.AddNonZero64("user_id", config.UserID) + + return params, nil +} + // DeleteMessageConfig contains information of a message in a chat to delete. type DeleteMessageConfig struct { BaseChatMessage diff --git a/helper_structs.go b/helper_structs.go index 921099e1..52d56b25 100644 --- a/helper_structs.go +++ b/helper_structs.go @@ -20,11 +20,12 @@ func (base ChatConfig) paramsWithKey(key string) (Params, error) { type BaseChat struct { ChatConfig BusinessConnectionID BusinessConnectionID - MessageThreadID int - ProtectContent bool - ReplyMarkup interface{} - DisableNotification bool - ReplyParameters ReplyParameters + MessageThreadID int + ProtectContent bool + ReplyMarkup interface{} + DisableNotification bool + MessageEffectID string // for private chats only + ReplyParameters ReplyParameters } func (chat *BaseChat) params() (Params, error) { @@ -41,6 +42,7 @@ func (chat *BaseChat) params() (Params, error) { params.AddNonZero("message_thread_id", chat.MessageThreadID) params.AddBool("disable_notification", chat.DisableNotification) params.AddBool("protect_content", chat.ProtectContent) + params.AddNonEmpty("message_effect_id", chat.MessageEffectID) err = params.AddInterface("reply_markup", chat.ReplyMarkup) if err != nil { diff --git a/types.go b/types.go index 4aa4b810..16728d44 100644 --- a/types.go +++ b/types.go @@ -651,6 +651,10 @@ type Message struct { // // Optional LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // EffectID is the unique identifier of the message effect added to the message + // + // optional + EffectID string `json:"effect_id,omitempty"` // Animation message is an animation, information about the animation. // For backward compatibility, when this field is set, the document field will also be set; // @@ -701,6 +705,10 @@ type Message struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // ShowCaptionAboveMedia is True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // HasSpoiler True, if the message media is covered by a spoiler animation // // optional @@ -1003,6 +1011,7 @@ type MessageEntity struct { // “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), @@ -2415,6 +2424,7 @@ type InlineKeyboardButton struct { // optional CallbackGame *CallbackGame `json:"callback_game,omitempty"` // Pay 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. // @@ -3289,6 +3299,10 @@ type BaseInputMedia struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // HasSpoiler pass True, if the photo needs to be covered with a spoiler animation // // optional @@ -3778,6 +3792,10 @@ type InlineQueryResultCachedGIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message. // // optional @@ -3817,6 +3835,10 @@ type InlineQueryResultCachedMPEG4GIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message. // // optional @@ -3858,6 +3880,10 @@ type InlineQueryResultCachedPhoto struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message. // // optional @@ -3917,6 +3943,10 @@ type InlineQueryResultCachedVideo struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message // // optional @@ -4159,6 +4189,10 @@ type InlineQueryResultGIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message // // optional @@ -4267,6 +4301,10 @@ type InlineQueryResultMPEG4GIF struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ReplyMarkup inline keyboard attached to the message // // optional @@ -4327,6 +4365,10 @@ type InlineQueryResultPhoto struct { // // optional CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // InputMessageContent content of the message to be sent instead of the photo. // // optional @@ -4406,6 +4448,15 @@ type InlineQueryResultVideo struct { // // optional Caption string `json:"caption,omitempty"` + // CaptionEntities is a list of special entities that appear in the caption, + // which can be specified instead of parse_mode + // + // optional + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + // + // optional + ShowCaptionAboveMedia bool `json:"show_caption_above_media,omitempty"` // ParseMode mode for parsing entities in the video caption. // See formatting options for more details // (https://core.telegram.org/bots/api#formatting-options). @@ -4414,7 +4465,7 @@ type InlineQueryResultVideo struct { ParseMode string `json:"parse_mode,omitempty"` // Width video width // - // optional + // optional Width int `json:"video_width,omitempty"` // Height video height // @@ -4617,9 +4668,11 @@ type InputInvoiceMessageContent struct { // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to // the user, use for your internal processes. Payload string `json:"payload"` - // Payment provider token, obtained via Botfather + // Payment provider token, obtained via Botfather. Pass an empty string for payments in Telegram Stars. + // + // optional ProviderToken string `json:"provider_token"` - // Three-letter ISO 4217 currency code + // Three-letter ISO 4217 currency code. 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.) @@ -4711,7 +4764,7 @@ type Invoice struct { Description string `json:"description"` // StartParameter unique bot deep-linking parameter that can be used to generate this invoice StartParameter string `json:"start_parameter"` - // Currency three-letter ISO 4217 currency code + // Currency three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars // (see https://core.telegram.org/bots/payments#supported-currencies) Currency string `json:"currency"` // TotalAmount total price in the smallest units of the currency (integer, not float/double). @@ -4771,7 +4824,7 @@ type ShippingOption struct { // SuccessfulPayment contains basic information about a successful payment. type SuccessfulPayment struct { - // Currency three-letter ISO 4217 currency code + // Currency three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars // (see https://core.telegram.org/bots/payments#supported-currencies) Currency string `json:"currency"` // TotalAmount total price in the smallest units of the currency (integer, not float/double). @@ -4815,7 +4868,7 @@ type PreCheckoutQuery struct { ID string `json:"id"` // From user who sent the query From *User `json:"from"` - // Currency three-letter ISO 4217 currency code + // Currency three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars // // (see https://core.telegram.org/bots/payments#supported-currencies) Currency string `json:"currency"` // TotalAmount total price in the smallest units of the currency (integer, not float/double). diff --git a/types_test.go b/types_test.go index ac1f3bc5..c4cd3fe2 100644 --- a/types_test.go +++ b/types_test.go @@ -375,6 +375,7 @@ var ( _ Chattable = SetMyShortDescriptionConfig{} _ Chattable = GetMyNameConfig{} _ Chattable = SetMyNameConfig{} + _ Chattable = RefundStarPaymentConfig{} ) // Ensure all Fileable types are correct. From 1deaa64606373cd1f36dfc4248ed5b70e90923f3 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Sun, 23 Jun 2024 13:07:40 +0300 Subject: [PATCH 39/70] Bot API 7.5 implementation --- configs.go | 21 ++++++++++++++ helper_structs.go | 6 ++-- types.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 98 insertions(+), 3 deletions(-) diff --git a/configs.go b/configs.go index dfb607f7..734566fa 100644 --- a/configs.go +++ b/configs.go @@ -2035,6 +2035,27 @@ func (config PreCheckoutConfig) params() (Params, error) { return params, nil } +// Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object. +type GetStarTransactionsConfig struct { + // Number of transactions to skip in the response + Offset int64 + // The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100. + Limit int64 +} + +func (config GetStarTransactionsConfig) method() string { + return "getStarTransactions" +} + +func (config GetStarTransactionsConfig) params() (Params, error) { + params := make(Params) + + params.AddNonZero64("offset", config.Offset) + params.AddNonZero64("limit", config.Limit) + + return params, nil +} + // RefundStarPaymentConfig refunds a successful payment in Telegram Stars. // Returns True on success. type RefundStarPaymentConfig struct { diff --git a/helper_structs.go b/helper_structs.go index 52d56b25..47f62a6c 100644 --- a/helper_structs.go +++ b/helper_structs.go @@ -65,8 +65,9 @@ func (file BaseFile) params() (Params, error) { // BaseEdit is base type of all chat edits. type BaseEdit struct { BaseChatMessage - InlineMessageID string - ReplyMarkup *InlineKeyboardMarkup + InlineMessageID string + ReplyMarkup *InlineKeyboardMarkup + BusinessConnectionID string } func (edit BaseEdit) params() (Params, error) { @@ -83,6 +84,7 @@ func (edit BaseEdit) params() (Params, error) { } err := params.AddInterface("reply_markup", edit.ReplyMarkup) + params.AddNonEmpty("business_connection_id", edit.BusinessConnectionID) return params, err } diff --git a/types.go b/types.go index 16728d44..512fb956 100644 --- a/types.go +++ b/types.go @@ -2374,6 +2374,8 @@ type InlineKeyboardButton struct { // Text label text on the button Text string `json:"text"` // URL HTTP or tg:// url to be opened when button is pressed. + // Links tg://user?id= can be used to mention a user by their identifier without using a username, + // if this is allowed by their privacy settings. // // optional URL *string `json:"url,omitempty"` @@ -2389,6 +2391,7 @@ type InlineKeyboardButton struct { // WebApp is the 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 Telegram Business account. // // optional WebApp *WebAppInfo `json:"web_app,omitempty"` @@ -2401,6 +2404,7 @@ type InlineKeyboardButton struct { // Especially useful when combined with switch_pm… actions – in this case // the user will be automatically returned to the chat they switched from, // skipping the chat selection screen. + // Not supported for messages sent on behalf of a Telegram Business account. // // optional SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` @@ -2410,12 +2414,14 @@ type InlineKeyboardButton struct { // // 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 for messages sent on behalf of a Telegram Business account. // // optional SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` //SwitchInlineQueryChosenChat 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 + //username and the specified inline query in the input field. + // Not supported for messages sent on behalf of a Telegram Business account. // //optional SwitchInlineQueryChosenChat *SwitchInlineQueryChosenChat `json:"switch_inline_query_chosen_chat,omitempty"` @@ -4889,3 +4895,69 @@ type PreCheckoutQuery struct { // optional OrderInfo *OrderInfo `json:"order_info,omitempty"` } + +// RevenueWithdrawalState describes the state of a revenue withdrawal operation. +// Currently, it can be one of +// - RevenueWithdrawalStatePending +// - RevenueWithdrawalStateSucceeded +// - RevenueWithdrawalStateFailed +type RevenueWithdrawalState struct { + // Type of the state. Must be one of: + // - pending + // - succeeded + // - failed + Type string `json:"type"` + // Date the withdrawal was completed in Unix time. Represents only in “succeeded” state + Date int64 `json:"date,omitempty"` + // An HTTPS URL that can be used to see transaction details. + // Represents only in “succeeded” state + URL string `json:"url,omitempty"` +} + +// TransactionPartner describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of +// - TransactionPartnerFragment +// - TransactionPartnerUser +// - TransactionPartnerOther +type TransactionPartner struct { + //Type of the transaction partner. Must be one of: + // - fragment + // - user + // - other + Type string `json:"type"` + // State of the transaction if the transaction is outgoing. + // Represent only in "fragment" state + // + // optional + WithdrawalState *RevenueWithdrawalState `json:"withdrawal_state,omitempty"` + // Information about the user. + // Represent only in "user" state + User *User `json:"user,omitempty"` +} + +// StarTransaction describes a Telegram Star transaction. +type StarTransaction struct { + // Unique identifier of the transaction. + // Coincides with the identifer of the original transaction for refund transactions. + // Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users. + ID string `json:"id"` + // Number of Telegram Stars transferred by the transaction + Amount int64 `json:"amount"` + // Date the transaction was created in Unix time + Date int64 `json:"date"` + // Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). + // Only for incoming transactions + // + // optional + Source *TransactionPartner `json:"source,omitempty"` + // Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). + // Only for outgoing transactions + // + // optional + Reciever *TransactionPartner `json:"reciever,omitempty"` +} + +// StarTransactions contains a list of Telegram Star transactions. +type StarTransactions struct { + // The list of transactions + Transactions []StarTransaction `json:"transactions"` +} From 6bd5d1256a8aea56428054bb7f298b7369a2bbc3 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Sun, 23 Jun 2024 13:10:34 +0300 Subject: [PATCH 40/70] add TransactionPartner to chattable --- types_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/types_test.go b/types_test.go index c4cd3fe2..ebe0407b 100644 --- a/types_test.go +++ b/types_test.go @@ -376,6 +376,7 @@ var ( _ Chattable = GetMyNameConfig{} _ Chattable = SetMyNameConfig{} _ Chattable = RefundStarPaymentConfig{} + _ Chattable = GetStarTransactionsConfig{} ) // Ensure all Fileable types are correct. From a8238b8afdf33cb2cf76730e43cbd5c57d82a299 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Tue, 2 Jul 2024 11:47:58 +0300 Subject: [PATCH 41/70] Bot API 7.6 implementation --- configs.go | 54 +++++++++++++++++++++++++ types.go | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++ types_test.go | 2 + 3 files changed, 162 insertions(+) diff --git a/configs.go b/configs.go index 734566fa..bcba50b5 100644 --- a/configs.go +++ b/configs.go @@ -377,6 +377,7 @@ func (config ForwardMessagesConfig) method() string { } // CopyMessageConfig contains information about a copyMessage request. +// Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. type CopyMessageConfig struct { BaseChat FromChat ChatConfig @@ -412,6 +413,7 @@ func (config CopyMessageConfig) method() string { } // CopyMessagesConfig contains information about a copyMessages request. +// Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. type CopyMessagesConfig struct { BaseChat FromChat ChatConfig @@ -760,6 +762,58 @@ func (config VideoNoteConfig) files() []RequestFile { return files } +// Use this method to send paid media to channel chats. On success, the sent Message is returned. +type PaidMediaConfig struct { + BaseChat + StarCount int64 + Media []InputPaidMedia + Caption string // optional + ParseMode string // optional + CaptionEntities []MessageEntity // optional + ShowCaptionAboveMedia bool // optional +} + +func (config PaidMediaConfig) params() (Params, error) { + params, err := config.BaseChat.params() + if err != nil { + return params, err + } + + params.AddNonZero64("star_count", config.StarCount) + params.AddNonEmpty("caption", config.Caption) + params.AddNonEmpty("parse_mode", config.ParseMode) + params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) + + err = params.AddInterface("media", config.Media) + if err != nil { + return params, err + } + err = params.AddInterface("caption_entities", config.CaptionEntities) + return params, err +} + +func (config PaidMediaConfig) files() []RequestFile { + files := []RequestFile{} + for i, v := range config.Media { + files = append(files, RequestFile{ + Name: fmt.Sprintf("%s-%d", v.Type, i), + Data: v.Media, + }) + if v.Thumb != nil { + files = append(files, RequestFile{ + Name: fmt.Sprintf("thumbnail-%d", i), + Data: v.Thumb, + }) + } + } + + return files +} + +func (config PaidMediaConfig) method() string { + return "sendPaidMedia" +} + // VoiceConfig contains information about a SendVoice request. type VoiceConfig struct { BaseFile diff --git a/types.go b/types.go index 512fb956..47fbb348 100644 --- a/types.go +++ b/types.go @@ -436,6 +436,11 @@ type ChatFullInfo struct { // // optional Permissions *ChatPermissions `json:"permissions,omitempty"` + // True, if paid media messages can be sent or forwarded to the channel chat. + // The field is available only for channel chats. + // + // optional + CanSendPaidMedia bool `json:"can_send_paid_media,omitempty"` // SlowModeDelay is for supergroups, the minimum allowed delay between // consecutive messages sent by each unprivileged user. Returned only in // getChat. @@ -673,6 +678,10 @@ type Message struct { // // optional Document *Document `json:"document,omitempty"` + // Message contains paid media; information about the paid media + // + // optional + PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"` // Photo message is a photo, available sizes of the photo; // // optional @@ -1153,6 +1162,10 @@ type ExternalReplyInfo struct { // // optional Document *Document `json:"document,omitempty"` + // Message contains paid media; information about the paid media + // + // optional + PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"` // Photo message is a photo, available sizes of the photo; // // optional @@ -1514,6 +1527,47 @@ type Voice struct { FileSize int64 `json:"file_size,omitempty"` } +// PaidMediaInfo describes the paid media added to a message. +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"` +} + +// This object describes paid media. Currently, it can be one of +// - PaidMediaPreview +// - PaidMediaPhoto +// - PaidMediaVideo +type PaidMedia struct { + // Type of the paid media, should be one of: + // - "photo" + // - "video" + // - "preview" + Type string `json:"type"` + // PaidMediaPreview only. + // Media width as defined by the sender. + // + // optional + Width int64 `json:"width,omitempty"` + // PaidMediaPreview only. + // Media height as defined by the sender + // + // optional + Height int64 `json:"height,omitempty"` + // PaidMediaPreview only. + // Duration of the media in seconds as defined by the sender + // + // optional + Duration int64 `json:"duration,omitempty"` + // PaidMediaPhoto only. + // The photo + Photo *[]PhotoSize `json:"photo,omitempty"` + // PaidMediaVideo only. + // The video + Video *Video `json:"video,omitempty"` +} + // Contact represents a phone contact. // // Note that LastName and UserID may be empty. @@ -3153,6 +3207,9 @@ type MenuButton struct { Text string `json:"text,omitempty"` // WebApp is the description of the Web App that will be launched when the // user presses the button for the `web_app` type. + // + // 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,omitempty"` } @@ -3414,6 +3471,48 @@ type InputMediaDocument struct { DisableContentTypeDetection bool `json:"disable_content_type_detection,omitempty"` } +// This object describes the paid media to be sent. Currently, it can be one of: +// - InputPaidMediaPhoto +// - InputPaidMediaVideo +type InputPaidMedia struct { + // Type of the media, must be one of: + // - "photo" + // - "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://” to upload a new one using multipart/form-data under name. + // More information on https://core.telegram.org/bots/api#sending-files + Media RequestFileData `json:"media"` + // InputPaidMediaVideo only. + // 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://” if the thumbnail was uploaded using multipart/form-data under . + // + // optional + Thumb RequestFileData `json:"thumbnail"` + // InputPaidMediaVideo only. + // Video width + // + // optional + Width int64 `json:"width,omitempty"` + // InputPaidMediaVideo only. + // Video height + // + // optional + Height int64 `json:"height,omitempty"` + // InputPaidMediaVideo only. + // Video duration in seconds + // + // optional + Duration int64 `json:"duration,omitempty"` + // InputPaidMediaVideo only. + // Pass True if the uploaded video is suitable for streaming + SupportsStreaming bool `json:"supports_streaming,omitempty"` +} + // Constant values for sticker types const ( StickerTypeRegular = "regular" @@ -4918,11 +5017,13 @@ type RevenueWithdrawalState struct { // - TransactionPartnerFragment // - TransactionPartnerUser // - TransactionPartnerOther +// - TransactionPartnerTelegramAds type TransactionPartner struct { //Type of the transaction partner. Must be one of: // - fragment // - user // - other + // - telegram_ads Type string `json:"type"` // State of the transaction if the transaction is outgoing. // Represent only in "fragment" state @@ -4932,6 +5033,11 @@ type TransactionPartner struct { // Information about the user. // Represent only in "user" state User *User `json:"user,omitempty"` + // TransactionPartnerUser only. + // Bot-specified invoice payload + // + // optional + InvoicePayload string `json:"invoice_payload,omitempty"` } // StarTransaction describes a Telegram Star transaction. diff --git a/types_test.go b/types_test.go index ebe0407b..9571e412 100644 --- a/types_test.go +++ b/types_test.go @@ -377,6 +377,7 @@ var ( _ Chattable = SetMyNameConfig{} _ Chattable = RefundStarPaymentConfig{} _ Chattable = GetStarTransactionsConfig{} + _ Chattable = PaidMediaConfig{} ) // Ensure all Fileable types are correct. @@ -398,6 +399,7 @@ var ( _ Fileable = (*MediaGroupConfig)(nil) _ Fileable = (*WebhookConfig)(nil) _ Fileable = (*SetStickerSetThumbConfig)(nil) + _ Fileable = (*PaidMediaConfig)(nil) ) // Ensure all RequestFileData types are correct. From 8d9704f6dbff1e03c479a64aa06c7653df22d926 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 7 Jul 2024 00:59:14 +0300 Subject: [PATCH 42/70] Remove redundant pointer for PhotoSize slice in PaidMedia structure --- types.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types.go b/types.go index 47fbb348..f6243ade 100644 --- a/types.go +++ b/types.go @@ -1562,7 +1562,7 @@ type PaidMedia struct { Duration int64 `json:"duration,omitempty"` // PaidMediaPhoto only. // The photo - Photo *[]PhotoSize `json:"photo,omitempty"` + Photo []PhotoSize `json:"photo,omitempty"` // PaidMediaVideo only. // The video Video *Video `json:"video,omitempty"` From 2126343ee23526983a34b4593716918ba7bacf4b Mon Sep 17 00:00:00 2001 From: stdkhai Date: Mon, 8 Jul 2024 13:04:50 +0300 Subject: [PATCH 43/70] BotAPI 7.7 implementation --- types.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/types.go b/types.go index f6243ade..cd16cefd 100644 --- a/types.go +++ b/types.go @@ -826,6 +826,10 @@ type Message struct { // // optional SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"` + // Message is a service message about a refunded payment, information about the payment + // + // optional + RefundedPayment *RefundedPayment `json:"refunded_payment,omitempty"` // UsersShared is a service message: the users were shared with the bot // // optional @@ -4955,6 +4959,27 @@ type SuccessfulPayment struct { ProviderPaymentChargeID string `json:"provider_payment_charge_id"` } +// RefundPayment contains basic information about a refunded payment. +type RefundedPayment struct { + // Three-letter ISO 4217 currency code (https://core.telegram.org/bots/payments#supported-currencies), + // 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 https://core.telegram.org/bots/payments/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"` + // Provider payment identifier + // + // optional + ProviderPaymentChargeID string `json:"provider_payment_charge_id,omitempty"` +} + // ShippingQuery contains information about an incoming shipping query. type ShippingQuery struct { // ID unique query identifier From ac7ff118744f5fef3f3bff4764db1fbf223bb4d7 Mon Sep 17 00:00:00 2001 From: Marco Andronaco Date: Sun, 21 Jul 2024 17:04:25 +0200 Subject: [PATCH 44/70] add required "SuggestedTipAmounts" field in NewInvoice --- helper_methods.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/helper_methods.go b/helper_methods.go index 747d4a04..9dc229c5 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -834,18 +834,20 @@ func NewCallbackWithAlert(id, text string) CallbackConfig { } // NewInvoice creates a new Invoice request to the user. -func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices []LabeledPrice) InvoiceConfig { +func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices []LabeledPrice, suggestedTipAmounts []int) InvoiceConfig { return InvoiceConfig{ BaseChat: BaseChat{ ChatConfig: ChatConfig{ChatID: chatID}, }, - Title: title, - Description: description, - Payload: payload, - ProviderToken: providerToken, - StartParameter: startParameter, - Currency: currency, - Prices: prices} + Title: title, + Description: description, + Payload: payload, + ProviderToken: providerToken, + StartParameter: startParameter, + Currency: currency, + Prices: prices, + SuggestedTipAmounts: suggestedTipAmounts, + } } // NewChatTitle allows you to update the title of a chat. From 819ceaf793b123f21d7310964c3525660f21f225 Mon Sep 17 00:00:00 2001 From: stdkhai Date: Fri, 9 Aug 2024 13:46:20 +0300 Subject: [PATCH 45/70] BotAPI 7.8 implementation --- helper_structs.go | 6 ++++-- types.go | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/helper_structs.go b/helper_structs.go index 47f62a6c..3c7796eb 100644 --- a/helper_structs.go +++ b/helper_structs.go @@ -107,7 +107,8 @@ func (spoiler BaseSpoiler) params() (Params, error) { // BaseChatMessage is a base type for all messages in chats. type BaseChatMessage struct { ChatConfig - MessageID int + MessageID int + BusinessConnectionID BusinessConnectionID } func (base BaseChatMessage) params() (Params, error) { @@ -116,8 +117,9 @@ func (base BaseChatMessage) params() (Params, error) { return params, err } params.AddNonZero("message_id", base.MessageID) + err = params.AddInterface("business_connection_id", base.BusinessConnectionID) - return params, nil + return params, err } // BaseChatMessages is a base type for all messages in chats. diff --git a/types.go b/types.go index cd16cefd..15a46736 100644 --- a/types.go +++ b/types.go @@ -263,6 +263,10 @@ type User struct { // // optional CanConnectToBusiness bool `json:"can_connect_to_business,omitempty"` + // True, if the bot has a main Web App. Returned only in getMe. + // + // optional + HasMainWebApp bool `json:"has_main_web_app,omitempty"` } // String displays a simple text version of a user. From 540e6677ca820110738c5d162151adf3ffd287ab Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Fri, 9 Aug 2024 17:13:41 +0300 Subject: [PATCH 46/70] Move preparing of 'business_connection_id' field to BaseChatMessage struct --- helper_structs.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/helper_structs.go b/helper_structs.go index 3c7796eb..10ddc847 100644 --- a/helper_structs.go +++ b/helper_structs.go @@ -67,7 +67,6 @@ type BaseEdit struct { BaseChatMessage InlineMessageID string ReplyMarkup *InlineKeyboardMarkup - BusinessConnectionID string } func (edit BaseEdit) params() (Params, error) { @@ -84,7 +83,6 @@ func (edit BaseEdit) params() (Params, error) { } err := params.AddInterface("reply_markup", edit.ReplyMarkup) - params.AddNonEmpty("business_connection_id", edit.BusinessConnectionID) return params, err } @@ -116,8 +114,12 @@ func (base BaseChatMessage) params() (Params, error) { if err != nil { return params, err } + p1, err := base.BusinessConnectionID.params() + if err != nil { + return params, err + } + params.Merge(p1) params.AddNonZero("message_id", base.MessageID) - err = params.AddInterface("business_connection_id", base.BusinessConnectionID) return params, err } From 11b1a666629f22c85a2e99330efbc06a319711db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Pazos?= Date: Mon, 19 Aug 2024 23:08:19 -0300 Subject: [PATCH 47/70] feat: some support for context propagation --- bot.go | 69 ++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 53 insertions(+), 16 deletions(-) diff --git a/bot.go b/bot.go index 1a16c273..fc42d56b 100644 --- a/bot.go +++ b/bot.go @@ -3,6 +3,7 @@ package tgbotapi import ( + "context" "encoding/json" "errors" "fmt" @@ -11,6 +12,7 @@ import ( "net/http" "net/url" "strings" + "sync" "time" ) @@ -25,11 +27,13 @@ type BotAPI struct { Debug bool `json:"debug"` Buffer int `json:"buffer"` - Self User `json:"-"` - Client HTTPClient `json:"-"` - shutdownChannel chan interface{} + Self User `json:"-"` + Client HTTPClient `json:"-"` apiEndpoint string + + stoppers []context.CancelFunc + mu sync.RWMutex } // NewBotAPI creates a new BotAPI instance. @@ -53,10 +57,9 @@ func NewBotAPIWithAPIEndpoint(token, apiEndpoint string) (*BotAPI, error) { // It requires a token, provided by @BotFather on Telegram and API endpoint. func NewBotAPIWithClient(token, apiEndpoint string, client HTTPClient) (*BotAPI, error) { bot := &BotAPI{ - Token: token, - Client: client, - Buffer: 100, - shutdownChannel: make(chan interface{}), + Token: token, + Client: client, + Buffer: 100, apiEndpoint: apiEndpoint, } @@ -92,6 +95,10 @@ func buildParams(in Params) url.Values { // MakeRequest makes a request to a specific endpoint with our token. func (bot *BotAPI) MakeRequest(endpoint string, params Params) (*APIResponse, error) { + return bot.MakeRequestWithContext(context.Background(), endpoint, params) +} + +func (bot *BotAPI) MakeRequestWithContext(ctx context.Context, endpoint string, params Params) (*APIResponse, error) { if bot.Debug { log.Printf("Endpoint: %s, params: %v\n", endpoint, params) } @@ -100,7 +107,7 @@ func (bot *BotAPI) MakeRequest(endpoint string, params Params) (*APIResponse, er values := buildParams(params) - req, err := http.NewRequest("POST", method, strings.NewReader(values.Encode())) + req, err := http.NewRequestWithContext(ctx, "POST", method, strings.NewReader(values.Encode())) if err != nil { return &APIResponse{}, err } @@ -165,6 +172,10 @@ func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) // UploadFiles makes a request to the API with files. func (bot *BotAPI) UploadFiles(endpoint string, params Params, files []RequestFile) (*APIResponse, error) { + return bot.UploadFilesWithContext(context.Background(), endpoint, params, files) +} + +func (bot *BotAPI) UploadFilesWithContext(ctx context.Context, endpoint string, params Params, files []RequestFile) (*APIResponse, error) { r, w := io.Pipe() m := multipart.NewWriter(w) @@ -223,7 +234,7 @@ func (bot *BotAPI) UploadFiles(endpoint string, params Params, files []RequestFi method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint) - req, err := http.NewRequest("POST", method, r) + req, err := http.NewRequestWithContext(ctx, "POST", method, r) if err != nil { return nil, err } @@ -281,7 +292,11 @@ func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { // and so you may get this data from BotAPI.Self without the need for // another request. func (bot *BotAPI) GetMe() (User, error) { - resp, err := bot.MakeRequest("getMe", nil) + return bot.GetMeWithContext(context.Background()) +} + +func (bot *BotAPI) GetMeWithContext(ctx context.Context) (User, error) { + resp, err := bot.MakeRequestWithContext(ctx, "getMe", nil) if err != nil { return User{}, err } @@ -311,6 +326,10 @@ func hasFilesNeedingUpload(files []RequestFile) bool { // Request sends a Chattable to Telegram, and returns the APIResponse. func (bot *BotAPI) Request(c Chattable) (*APIResponse, error) { + return bot.RequestWithContext(context.Background(), c) +} + +func (bot *BotAPI) RequestWithContext(ctx context.Context, c Chattable) (*APIResponse, error) { params, err := c.params() if err != nil { return nil, err @@ -332,7 +351,7 @@ func (bot *BotAPI) Request(c Chattable) (*APIResponse, error) { } } - return bot.MakeRequest(c.method(), params) + return bot.MakeRequestWithContext(ctx, c.method(), params) } // Send will send a Chattable item to Telegram and provides the @@ -401,7 +420,11 @@ func (bot *BotAPI) GetFile(config FileConfig) (File, error) { // Set Timeout to a large number to reduce requests, so you can get updates // instantly instead of having to wait between requests. func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { - resp, err := bot.Request(config) + return bot.GetUpdatesWithContext(context.Background(), config) +} + +func (bot *BotAPI) GetUpdatesWithContext(ctx context.Context, config UpdateConfig) ([]Update, error) { + resp, err := bot.RequestWithContext(ctx, config) if err != nil { return []Update{}, err } @@ -415,7 +438,11 @@ func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { // GetWebhookInfo allows you to fetch information about a webhook and if // one currently is set, along with pending update count and error messages. func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { - resp, err := bot.MakeRequest("getWebhookInfo", nil) + return bot.GetWebhookInfoWithContext(context.Background()) +} + +func (bot *BotAPI) GetWebhookInfoWithContext(ctx context.Context) (WebhookInfo, error) { + resp, err := bot.MakeRequestWithContext(ctx, "getWebhookInfo", nil) if err != nil { return WebhookInfo{}, err } @@ -430,16 +457,21 @@ func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel { ch := make(chan Update, bot.Buffer) + ctx, cancel := context.WithCancel(context.Background()) + bot.mu.Lock() + bot.stoppers = append(bot.stoppers, cancel) + bot.mu.Unlock() + go func() { for { select { - case <-bot.shutdownChannel: + case <-ctx.Done(): close(ch) return default: } - updates, err := bot.GetUpdates(config) + updates, err := bot.GetUpdatesWithContext(ctx, config) if err != nil { log.Println(err) log.Println("Failed to get updates, retrying in 3 seconds...") @@ -462,10 +494,15 @@ func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel { // StopReceivingUpdates stops the go routine which receives updates func (bot *BotAPI) StopReceivingUpdates() { + bot.mu.Lock() + defer bot.mu.Unlock() + if bot.Debug { log.Println("Stopping the update receiver routine...") } - close(bot.shutdownChannel) + for _, stopper := range bot.stoppers { + stopper() + } } // ListenForWebhook registers a http handler for a webhook. From acd4170b3b199b49f0e75d69865f88bf31aa9220 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Pazos?= Date: Mon, 19 Aug 2024 23:32:16 -0300 Subject: [PATCH 48/70] Don't wait 3 seconds if the context was cancelled --- bot.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/bot.go b/bot.go index fc42d56b..b39f8ebc 100644 --- a/bot.go +++ b/bot.go @@ -473,10 +473,11 @@ func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel { updates, err := bot.GetUpdatesWithContext(ctx, config) if err != nil { - log.Println(err) - log.Println("Failed to get updates, retrying in 3 seconds...") - time.Sleep(time.Second * 3) - + if ctx.Err() == nil { + log.Println(err) + log.Println("Failed to get updates, retrying in 3 seconds...") + time.Sleep(time.Second * 3) + } continue } From f9ab9c0a4df305dcfc111e96a8b92c6fda442a39 Mon Sep 17 00:00:00 2001 From: Marco Andronaco Date: Wed, 18 Sep 2024 09:50:47 +0200 Subject: [PATCH 49/70] add NewSetMessageReaction --- helper_methods.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/helper_methods.go b/helper_methods.go index 9dc229c5..d9964998 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -988,6 +988,20 @@ func NewDiceWithEmoji(chatID int64, emoji string) DiceConfig { } } +// NewSetMessageReaction allows you to set a message's reactions. +func NewSetMessageReaction(chatID int64, messageID int, reaction []ReactionType, isBig bool) SetMessageReactionConfig { + return SetMessageReactionConfig{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + Reaction: reaction, + IsBig: isBig, + } +} + // NewBotCommandScopeDefault represents the default scope of bot commands. func NewBotCommandScopeDefault() BotCommandScope { return BotCommandScope{Type: "default"} From cefbcc69b78057de6fde895e5cd5c91722afecd9 Mon Sep 17 00:00:00 2001 From: Alex Geer Date: Thu, 19 Sep 2024 22:28:08 +0300 Subject: [PATCH 50/70] Added the ability to call the createInvoiceLink() method to generate a link to invoice for the telegram mini app. createInvoiceLink() Use this method to create a link for an invoice. Returns the created invoice link as String on success. --- bot.go | 17 +++++++++++++++++ helper_methods.go | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/bot.go b/bot.go index b39f8ebc..25e5328d 100644 --- a/bot.go +++ b/bot.go @@ -671,6 +671,23 @@ func (bot *BotAPI) GetInviteLink(config ChatInviteLinkConfig) (string, error) { return inviteLink, err } +// CreateInvoiceLink Use this method to create a link for an invoice. Returns the created invoice link as +// String on success. +func (bot *BotAPI) CreateInvoiceLink(config InvoiceLinkConfig) (inviteLink string, err error) { + var resp *APIResponse + + if resp, err = bot.Request(config); err != nil { + return + } + if !resp.Ok { + err = fmt.Errorf("returns error code: %d", resp.ErrorCode) + return + } + err = json.Unmarshal(resp.Result, &inviteLink) + + return +} + // GetStickerSet returns a StickerSet. func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) { resp, err := bot.Request(config) diff --git a/helper_methods.go b/helper_methods.go index 9dc229c5..9155eba3 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -834,7 +834,23 @@ func NewCallbackWithAlert(id, text string) CallbackConfig { } // NewInvoice creates a new Invoice request to the user. -func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices []LabeledPrice, suggestedTipAmounts []int) InvoiceConfig { +func NewInvoice( + chatID int64, + title string, + description string, + payload string, + providerToken string, + startParameter string, + currency string, + prices []LabeledPrice, + suggestedTipAmounts []int, +) InvoiceConfig { + var maxTipAmount, n int + for n = range suggestedTipAmounts { + if maxTipAmount < suggestedTipAmounts[n] { + maxTipAmount = suggestedTipAmounts[n] + } + } return InvoiceConfig{ BaseChat: BaseChat{ ChatConfig: ChatConfig{ChatID: chatID}, @@ -847,6 +863,21 @@ func NewInvoice(chatID int64, title, description, payload, providerToken, startP Currency: currency, Prices: prices, SuggestedTipAmounts: suggestedTipAmounts, + MaxTipAmount: maxTipAmount, + } +} + +// NewInvoiceLink creates a new createInvoiceLink request. +func NewInvoiceLink(ico InvoiceConfig) InvoiceLinkConfig { + return InvoiceLinkConfig{ + Title: ico.Title, + Description: ico.Description, + Payload: ico.Payload, + ProviderToken: ico.ProviderToken, + Currency: ico.Currency, + Prices: ico.Prices, + SuggestedTipAmounts: ico.SuggestedTipAmounts, + MaxTipAmount: ico.MaxTipAmount, } } From 807a7e7522e9c4bffbab0096ccfb89f3743bab7f Mon Sep 17 00:00:00 2001 From: Stanislav Lukyanov Date: Tue, 1 Oct 2024 21:59:44 +0200 Subject: [PATCH 51/70] add extra edit message media types --- helper_methods.go | 48 +++++++++++++++++++++++++++++ helpers_test.go | 78 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/helper_methods.go b/helper_methods.go index 643701c7..c7150faa 100644 --- a/helper_methods.go +++ b/helper_methods.go @@ -227,6 +227,14 @@ func NewMediaGroup(chatID int64, files []interface{}) MediaGroupConfig { } } +// NewBaseInputMedia creates a new BaseInputMedia. +func NewBaseInputMedia(mediaType string, media RequestFileData) BaseInputMedia { + return BaseInputMedia{ + Type: mediaType, + Media: media, + } +} + // NewInputMediaPhoto creates a new InputMediaPhoto. func NewInputMediaPhoto(media RequestFileData) InputMediaPhoto { return InputMediaPhoto{ @@ -607,6 +615,46 @@ func NewInlineQueryResultVenue(id, title, address string, latitude, longitude fl } } +// NewEditMessageMedia allows you to edit the media content of a message. +func NewEditMessageMedia(chatID int64, messageID int, inputMedia interface{}) EditMessageMediaConfig { + return EditMessageMediaConfig{ + BaseEdit: BaseEdit{ + BaseChatMessage: BaseChatMessage{ + ChatConfig: ChatConfig{ + ChatID: chatID, + }, + MessageID: messageID, + }, + }, + Media: inputMedia, + } +} + +// NewEditMessagePhoto allows you to edit the photo content of a message. +func NewEditMessagePhoto(chatID int64, messageID int, inputPhoto InputMediaPhoto) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputPhoto) +} + +// NewEditMessageVideo allows you to edit the video content of a message. +func NewEditMessageVideo(chatID int64, messageID int, inputVideo InputMediaVideo) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputVideo) +} + +// NewEditMessageAnimation allows you to edit the animation content of a message. +func NewEditMessageAnimation(chatID int64, messageID int, inputAnimation InputMediaAnimation) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputAnimation) +} + +// NewEditMessageAudio allows you to edit the audio content of a message. +func NewEditMessageAudio(chatID int64, messageID int, inputAudio InputMediaAudio) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputAudio) +} + +// NewEditMessageDocument allows you to edit the document content of a message. +func NewEditMessageDocument(chatID int64, messageID int, inputDocument InputMediaDocument) EditMessageMediaConfig { + return NewEditMessageMedia(chatID, messageID, inputDocument) +} + // NewEditMessageText allows you to edit the text of a message. func NewEditMessageText(chatID int64, messageID int, text string) EditMessageTextConfig { return EditMessageTextConfig{ diff --git a/helpers_test.go b/helpers_test.go index fe8098e0..92de20bb 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -197,6 +197,84 @@ func TestNewInlineKeyboardButtonSwitchInlineQueryChoosenChat(t *testing.T) { } } +func TestNewEditMessageMedia(t *testing.T) { + baseInputMedia := NewBaseInputMedia("photo", FileID("test")) + edit := NewEditMessageMedia(ChatID, ReplyToMessageID, baseInputMedia) + + if edit.Media == nil || + edit.Media.(BaseInputMedia).Type != "photo" || + edit.Media.(BaseInputMedia).Media != baseInputMedia.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessagePhoto(t *testing.T) { + inputMediaPhoto := NewInputMediaPhoto(FilePath("tests/image.jpg")) + edit := NewEditMessagePhoto(ChatID, ReplyToMessageID, inputMediaPhoto) + + if edit.Media == nil || + edit.Media.(InputMediaPhoto).Type != "photo" || + edit.Media.(InputMediaPhoto).Media != inputMediaPhoto.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageVideo(t *testing.T) { + inputMediaVideo := NewInputMediaVideo(FilePath("tests/video.mp4")) + edit := NewEditMessageVideo(ChatID, ReplyToMessageID, inputMediaVideo) + + if edit.Media == nil || + edit.Media.(InputMediaVideo).Type != "video" || + edit.Media.(InputMediaVideo).Media != inputMediaVideo.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageAnimation(t *testing.T) { + inputMediaAnimation := NewInputMediaAnimation(FileID("test")) + edit := NewEditMessageAnimation(ChatID, ReplyToMessageID, inputMediaAnimation) + + if edit.Media == nil || + edit.Media.(InputMediaAnimation).Type != "animation" || + edit.Media.(InputMediaAnimation).Media != inputMediaAnimation.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageAudio(t *testing.T) { + inputMediaAudio := NewInputMediaAudio(FileID("test")) + edit := NewEditMessageAudio(ChatID, ReplyToMessageID, inputMediaAudio) + + if edit.Media == nil || + edit.Media.(InputMediaAudio).Type != "audio" || + edit.Media.(InputMediaAudio).Media != inputMediaAudio.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + +func TestNewEditMessageDocument(t *testing.T) { + inputMediaDocument := NewInputMediaDocument(FileID("test")) + edit := NewEditMessageDocument(ChatID, ReplyToMessageID, inputMediaDocument) + + if edit.Media == nil || + edit.Media.(InputMediaDocument).Type != "document" || + edit.Media.(InputMediaDocument).Media != inputMediaDocument.Media || + edit.BaseEdit.ChatID != ChatID || + edit.BaseEdit.MessageID != ReplyToMessageID { + t.Fail() + } +} + func TestNewEditMessageText(t *testing.T) { edit := NewEditMessageText(ChatID, ReplyToMessageID, "new text") From d2dc7791d0407508e7515d720f7c0fe32f28e05f Mon Sep 17 00:00:00 2001 From: Stanislav Lukyanov Date: Tue, 8 Oct 2024 22:11:06 +0200 Subject: [PATCH 52/70] update edit media tests --- helpers_test.go | 66 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/helpers_test.go b/helpers_test.go index 92de20bb..ffe3805f 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -201,9 +201,14 @@ func TestNewEditMessageMedia(t *testing.T) { baseInputMedia := NewBaseInputMedia("photo", FileID("test")) edit := NewEditMessageMedia(ChatID, ReplyToMessageID, baseInputMedia) - if edit.Media == nil || - edit.Media.(BaseInputMedia).Type != "photo" || - edit.Media.(BaseInputMedia).Media != baseInputMedia.Media || + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(BaseInputMedia); !ok || + media.Type != "photo" || + media.Media != baseInputMedia.Media || edit.BaseEdit.ChatID != ChatID || edit.BaseEdit.MessageID != ReplyToMessageID { t.Fail() @@ -214,9 +219,14 @@ func TestNewEditMessagePhoto(t *testing.T) { inputMediaPhoto := NewInputMediaPhoto(FilePath("tests/image.jpg")) edit := NewEditMessagePhoto(ChatID, ReplyToMessageID, inputMediaPhoto) - if edit.Media == nil || - edit.Media.(InputMediaPhoto).Type != "photo" || - edit.Media.(InputMediaPhoto).Media != inputMediaPhoto.Media || + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaPhoto); !ok || + media.Type != "photo" || + media.Media != inputMediaPhoto.Media || edit.BaseEdit.ChatID != ChatID || edit.BaseEdit.MessageID != ReplyToMessageID { t.Fail() @@ -227,9 +237,14 @@ func TestNewEditMessageVideo(t *testing.T) { inputMediaVideo := NewInputMediaVideo(FilePath("tests/video.mp4")) edit := NewEditMessageVideo(ChatID, ReplyToMessageID, inputMediaVideo) - if edit.Media == nil || - edit.Media.(InputMediaVideo).Type != "video" || - edit.Media.(InputMediaVideo).Media != inputMediaVideo.Media || + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaVideo); !ok || + media.Type != "video" || + media.Media != inputMediaVideo.Media || edit.BaseEdit.ChatID != ChatID || edit.BaseEdit.MessageID != ReplyToMessageID { t.Fail() @@ -240,9 +255,14 @@ func TestNewEditMessageAnimation(t *testing.T) { inputMediaAnimation := NewInputMediaAnimation(FileID("test")) edit := NewEditMessageAnimation(ChatID, ReplyToMessageID, inputMediaAnimation) - if edit.Media == nil || - edit.Media.(InputMediaAnimation).Type != "animation" || - edit.Media.(InputMediaAnimation).Media != inputMediaAnimation.Media || + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaAnimation); !ok || + media.Type != "animation" || + media.Media != inputMediaAnimation.Media || edit.BaseEdit.ChatID != ChatID || edit.BaseEdit.MessageID != ReplyToMessageID { t.Fail() @@ -253,9 +273,14 @@ func TestNewEditMessageAudio(t *testing.T) { inputMediaAudio := NewInputMediaAudio(FileID("test")) edit := NewEditMessageAudio(ChatID, ReplyToMessageID, inputMediaAudio) - if edit.Media == nil || - edit.Media.(InputMediaAudio).Type != "audio" || - edit.Media.(InputMediaAudio).Media != inputMediaAudio.Media || + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaAudio); !ok || + media.Type != "audio" || + media.Media != inputMediaAudio.Media || edit.BaseEdit.ChatID != ChatID || edit.BaseEdit.MessageID != ReplyToMessageID { t.Fail() @@ -266,9 +291,14 @@ func TestNewEditMessageDocument(t *testing.T) { inputMediaDocument := NewInputMediaDocument(FileID("test")) edit := NewEditMessageDocument(ChatID, ReplyToMessageID, inputMediaDocument) - if edit.Media == nil || - edit.Media.(InputMediaDocument).Type != "document" || - edit.Media.(InputMediaDocument).Media != inputMediaDocument.Media || + if edit.Media == nil { + t.Fail() + return + } + + if media, ok := edit.Media.(InputMediaDocument); !ok || + media.Type != "document" || + media.Media != inputMediaDocument.Media || edit.BaseEdit.ChatID != ChatID || edit.BaseEdit.MessageID != ReplyToMessageID { t.Fail() From 333ea1ea843fb153a13f324af84fc5cdee5a6130 Mon Sep 17 00:00:00 2001 From: OrIX219 Date: Fri, 11 Oct 2024 16:31:23 +0300 Subject: [PATCH 53/70] add caption_entities to DocumentConfig params --- configs.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/configs.go b/configs.go index bcba50b5..41c30ceb 100644 --- a/configs.go +++ b/configs.go @@ -560,6 +560,10 @@ func (config DocumentConfig) params() (Params, error) { params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("disable_content_type_detection", config.DisableContentTypeDetection) + err = params.AddInterface("caption_entities", config.CaptionEntities) + if err != nil { + return params, err + } return params, err } From 560d0008d1c35167fbd201c36468eaeb7d7212d9 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 13 Oct 2024 13:00:56 +0300 Subject: [PATCH 54/70] BotAPI 7.9 implementation --- configs.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ types.go | 37 ++++++++++++++++++++++++++++++----- types_test.go | 2 ++ 3 files changed, 88 insertions(+), 5 deletions(-) diff --git a/configs.go b/configs.go index 41c30ceb..8ce14438 100644 --- a/configs.go +++ b/configs.go @@ -1823,6 +1823,60 @@ func (config EditChatInviteLinkConfig) params() (Params, error) { return params, nil } +// CreateChatSubscriptionLinkConfig creates 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. +type CreateChatSubscriptionLinkConfig struct { + ChatConfig + Name string + SubscriptionPeriod int + SubscriptionPrice int +} + +func (CreateChatSubscriptionLinkConfig) method() string { + return "createChatSubscriptionInviteLink" +} + +func (config CreateChatSubscriptionLinkConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params.AddNonEmpty("name", config.Name) + params.AddNonZero("subscription_period", config.SubscriptionPeriod) + params.AddNonZero("subscription_price", config.SubscriptionPrice) + + return params, nil +} + +// EditChatSubscriptionLinkConfig edits 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. +type EditChatSubscriptionLinkConfig struct { + ChatConfig + InviteLink string + Name string +} + +func (EditChatSubscriptionLinkConfig) method() string { + return "editChatSubscriptionInviteLink" +} + +func (config EditChatSubscriptionLinkConfig) params() (Params, error) { + params, err := config.ChatConfig.params() + if err != nil { + return params, err + } + + params["invite_link"] = config.InviteLink + params.AddNonEmpty("name", config.Name) + + return params, nil +} + // RevokeChatInviteLinkConfig allows you 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 diff --git a/types.go b/types.go index 15a46736..d8a570cd 100644 --- a/types.go +++ b/types.go @@ -2662,6 +2662,17 @@ type ChatInviteLink struct { // // optional PendingJoinRequestCount int `json:"pending_join_request_count,omitempty"` + // SubscriptionPeriod is the number of seconds the subscription + // will be active for before the next payment + // + // optional + SubscriptionPeriod int `json:"subscription_period,omitempty"` + // SubscriptionPrice is 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 + // + // optional + SubscriptionPrice int `json:"subscription_price,omitempty"` } type ChatAdministratorRights struct { @@ -2704,10 +2715,14 @@ type ChatMember struct { // // optional IsAnonymous bool `json:"is_anonymous,omitempty"` - // UntilDate restricted and kicked only. + // UntilDate for restricted and kicked. // Date when restrictions will be lifted for this user; // unix time. // + // Until date for member. + // Date when the user's subscription will expire; + // Unix time + // // optional UntilDate int64 `json:"until_date,omitempty"` // CanBeEdited administrators only. @@ -3092,11 +3107,13 @@ type ChatLocation struct { const ( ReactionTypeEmoji = "emoji" ReactionTypeCustomEmoji = "custom_emoji" + ReactionTypePaid = "paid" ) -// ReactionType describes the type of a reaction. Currently, it can be one of: "emoji", "custom_emoji" +// ReactionType describes the type of a reaction. +// Currently, it can be one of: "emoji", "custom_emoji", "paid" type ReactionType struct { - // Type of the reaction. Can be "emoji", "custom_emoji" + // Type of the reaction. Can be "emoji", "custom_emoji", "paid" Type string `json:"type"` // Emoji type "emoji" only. Is a reaction emoji. Emoji string `json:"emoji"` @@ -3112,6 +3129,10 @@ func (r ReactionType) IsCustomEmoji() bool { return r.Type == ReactionTypeCustomEmoji } +func (r ReactionType) IsPaid() bool { + return r.Type == ReactionTypePaid +} + // ReactionCount represents a reaction added to a message along with the number of times it was added. type ReactionCount struct { // Type of the reaction @@ -5043,10 +5064,10 @@ type RevenueWithdrawalState struct { } // TransactionPartner describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of -// - TransactionPartnerFragment // - TransactionPartnerUser -// - TransactionPartnerOther +// - TransactionPartnerFragment // - TransactionPartnerTelegramAds +// - TransactionPartnerOther type TransactionPartner struct { //Type of the transaction partner. Must be one of: // - fragment @@ -5067,6 +5088,12 @@ type TransactionPartner struct { // // optional InvoicePayload string `json:"invoice_payload,omitempty"` + // PaidMedia is the nformation about the paid media + // bought by the user + // Represent only in "user" state + // + // optional + PaidMedia []PaidMedia `json:"paid_media,omitempty"` } // StarTransaction describes a Telegram Star transaction. diff --git a/types_test.go b/types_test.go index 9571e412..f209f76b 100644 --- a/types_test.go +++ b/types_test.go @@ -293,6 +293,7 @@ var ( _ Chattable = ContactConfig{} _ Chattable = CopyMessageConfig{} _ Chattable = CreateChatInviteLinkConfig{} + _ Chattable = CreateChatSubscriptionLinkConfig{} _ Chattable = DeleteChatPhotoConfig{} _ Chattable = DeleteChatStickerSetConfig{} _ Chattable = DeleteMessageConfig{} @@ -300,6 +301,7 @@ var ( _ Chattable = DeleteWebhookConfig{} _ Chattable = DocumentConfig{} _ Chattable = EditChatInviteLinkConfig{} + _ Chattable = EditChatSubscriptionLinkConfig{} _ Chattable = EditMessageCaptionConfig{} _ Chattable = EditMessageLiveLocationConfig{} _ Chattable = EditMessageMediaConfig{} From 7af9c3299704998fcb3d4f1b4e343909a636596b Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 13 Oct 2024 13:06:35 +0300 Subject: [PATCH 55/70] Add error returning from DocumentConfig.BaseFile.params() method --- configs.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/configs.go b/configs.go index 8ce14438..616e3123 100644 --- a/configs.go +++ b/configs.go @@ -556,7 +556,10 @@ type DocumentConfig struct { func (config DocumentConfig) params() (Params, error) { params, err := config.BaseFile.params() - + if err != nil { + return params, err + } + params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("disable_content_type_detection", config.DisableContentTypeDetection) From 5fd45917caa165a25bb1e65114f9da4c493eaee2 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Sun, 13 Oct 2024 13:25:59 +0300 Subject: [PATCH 56/70] BotAPI 7.10 implementation --- configs.go | 8 +++++++- types.go | 46 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/configs.go b/configs.go index 616e3123..b47a1edd 100644 --- a/configs.go +++ b/configs.go @@ -96,6 +96,10 @@ const ( // UpdateTypePreCheckoutQuery is new incoming pre-checkout query. Contains full information about checkout UpdateTypePreCheckoutQuery = "pre_checkout_query" + // UpdateTypePurchasedPaidMedia is a user purchased paid media with a non-empty payload + // sent by the bot in a non-channel chat + UpdateTypePurchasedPaidMedia = "purchased_paid_media" + // UpdateTypePoll is new poll state. Bots receive only updates about stopped polls and polls // which are sent by the bot UpdateTypePoll = "poll" @@ -559,7 +563,7 @@ func (config DocumentConfig) params() (Params, error) { if err != nil { return params, err } - + params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("disable_content_type_detection", config.DisableContentTypeDetection) @@ -774,6 +778,7 @@ type PaidMediaConfig struct { BaseChat StarCount int64 Media []InputPaidMedia + Payload string // optional Caption string // optional ParseMode string // optional CaptionEntities []MessageEntity // optional @@ -787,6 +792,7 @@ func (config PaidMediaConfig) params() (Params, error) { } params.AddNonZero64("star_count", config.StarCount) + params.AddNonEmpty("payload", config.Payload) params.AddNonEmpty("caption", config.Caption) params.AddNonEmpty("parse_mode", config.ParseMode) params.AddBool("show_caption_above_media", config.ShowCaptionAboveMedia) diff --git a/types.go b/types.go index d8a570cd..8bf58005 100644 --- a/types.go +++ b/types.go @@ -114,6 +114,11 @@ type Update struct { // // optional PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query,omitempty"` + // PurchasedPaidMedia is user purchased paid media with a non-empty + // payload sent by the bot in a non-channel chat + // + // optional + PurchasedPaidMedia *PaidMediaPurchased `json:"purchased_paid_media,omitempty"` // Pool new poll state. Bots receive only updates about stopped polls and // polls, which are sent by the bot // @@ -2032,7 +2037,14 @@ type VideoChatParticipantsInvited struct { } // This object represents a service message about the creation of a scheduled giveaway. Currently holds no information. -type GiveawayCreated struct{} +type GiveawayCreated struct { + // PrizeStarCount is the number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` +} // Giveaway represents a message about a scheduled giveaway. type Giveaway struct { @@ -2063,6 +2075,12 @@ type Giveaway struct { // // optional CountryCodes []string `json:"country_codes,omitempty"` + // PrizeStarCount is the number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` // PremiumSubscriptionMonthCount the number of months the Telegram Premium // subscription won from the giveaway will be active for // @@ -2089,6 +2107,12 @@ type GiveawayWinners struct { // // optional AdditionalChatCount int `json:"additional_chat_count,omitempty"` + // PrizeStarCount is the number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` // PremiumSubscriptionMonthCount the number of months the Telegram Premium // subscription won from the giveaway will be active for // @@ -2125,6 +2149,11 @@ type GiveawayCompleted struct { // // optional GiveawayMessage *Message `json:"giveaway_message,omitempty"` + // IsStarGiveaway True, if the giveaway is a Telegram Star giveaway. + // Otherwise, currently, the giveaway is a Telegram Premium giveaway. + // + // optional + IsStarGiveaway bool `json:"is_star_giveaway,omitempty"` } // LinkPreviewOptions describes the options used for link preview generation. @@ -3261,6 +3290,13 @@ type ChatBoostSource struct { // Is an 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 int `json:"giveaway_message_id,omitempty"` + // PrizeStarCount "giveaway" only. + // The number of Telegram Stars to be split + // between giveaway winners; + // for Telegram Star giveaways only + // + // optional + PrizeStarCount int `json:"prize_star_count,omitempty"` // IsUnclaimed "giveaway" only. // True, if the giveaway was completed, but there was no user to win the prize // @@ -5045,6 +5081,14 @@ type PreCheckoutQuery struct { OrderInfo *OrderInfo `json:"order_info,omitempty"` } +// PaidMediaPurchased contains information about a paid media purchase. +type PaidMediaPurchased struct { + // From is the user who purchased the media + From User `json:"from"` + // PaidMediaPayload bot-specified paid media payload + PaidMediaPayload string `json:"paid_media_payload"` +} + // RevenueWithdrawalState describes the state of a revenue withdrawal operation. // Currently, it can be one of // - RevenueWithdrawalStatePending From 269bc52e5a134d8aec5a0e1058520e466c7d8708 Mon Sep 17 00:00:00 2001 From: Stanislav Lukyanov Date: Mon, 14 Oct 2024 22:40:34 +0200 Subject: [PATCH 57/70] add animation type for inputMediaFiles --- configs.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/configs.go b/configs.go index b47a1edd..632fd695 100644 --- a/configs.go +++ b/configs.go @@ -3265,6 +3265,14 @@ func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { } return m + case InputMediaAnimation: + if m.Media.NeedsUpload() { + m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) + } + + if m.Thumb != nil && m.Thumb.NeedsUpload() { + m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) + } case InputMediaDocument: if m.Media.NeedsUpload() { m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) @@ -3307,6 +3315,20 @@ func prepareInputMediaFile(inputMedia interface{}, idx int) []RequestFile { }) } + if m.Thumb != nil && m.Thumb.NeedsUpload() { + files = append(files, RequestFile{ + Name: fmt.Sprintf("file-%d", idx), + Data: m.Thumb, + }) + } + case InputMediaAnimation: + if m.Media.NeedsUpload() { + files = append(files, RequestFile{ + Name: fmt.Sprintf("file-%d", idx), + Data: m.Media, + }) + } + if m.Thumb != nil && m.Thumb.NeedsUpload() { files = append(files, RequestFile{ Name: fmt.Sprintf("file-%d", idx), From 129367a08a59bdba465fe3edd904561f1644f551 Mon Sep 17 00:00:00 2001 From: Eugene Date: Mon, 28 Oct 2024 11:11:39 -0500 Subject: [PATCH 58/70] update go.mod for v6, update go version update module path to match to original repo --- .github/workflows/test.yml | 8 ++++---- go.mod | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 48b2859b..407f7940 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,14 +12,14 @@ jobs: name: Test runs-on: ubuntu-latest steps: - - name: Set up Go 1.x - uses: actions/setup-go@v2 + - name: Set up Go 1.23 + uses: actions/setup-go@v5 with: - go-version: ^1.15 + go-version: "1.23" id: go - name: Check out code into the Go module directory - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Build run: go build -v . diff --git a/go.mod b/go.mod index 167e5e45..976952ee 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/go-telegram-bot-api/telegram-bot-api/v5 +module github.com/OvyFlash/telegram-bot-api/v6 -go 1.16 +go 1.23 From de5d7a3cb1c6f66719d81001abca13a00c5a4688 Mon Sep 17 00:00:00 2001 From: Umputun Date: Mon, 28 Oct 2024 11:20:08 -0500 Subject: [PATCH 59/70] update docs with refs to the new module --- README.md | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index d61b42c9..4fa7fc1b 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,8 @@ -> # Usage -> If you want to use this fork in the project that imports the original repo, the easiest way is to: -> - `git submodule add git@github.com:OvyFlash/telegram-bot-api.git telegram-bot-api` -> - `go mod edit --replace github.com/go-telegram-bot-api/telegram-bot-api/v5=./telegram-bot-api/` -> - `go mod tidy` -> And you're ready to go. -> Notice, that there have been several breaking changes since the telegram bot API v5 was released, so you might need to update your application. - # Golang bindings for the Telegram Bot API -[![Go Reference](https://pkg.go.dev/badge/github.com/go-telegram-bot-api/telegram-bot-api/v5.svg)](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) +[![Go Reference](https://pkg.go.dev/badge/github.com/OvyFlash/telegram-bot-api/v6.svg)](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api/v6) [![Test](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml) -All methods are fairly self-explanatory, and reading the [godoc](https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5) page should +All methods are fairly self-explanatory, and reading the [godoc](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api/v6) page should explain everything. If something isn't clear, open an issue or submit a pull request. @@ -27,7 +19,7 @@ you want to ask questions or discuss development. ## Example First, ensure the library is installed and up to date by running -`go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5`. +`go get -u github.com/OvyFlash/telegram-bot-api/v6`. This is a very simple bot that just displays any gotten updates, then replies it to that chat. @@ -38,7 +30,7 @@ package main import ( "log" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + tgbotapi "github.com/OvyFlash/telegram-bot-api/v6" ) func main() { @@ -79,7 +71,7 @@ import ( "log" "net/http" - "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/OvyFlash/telegram-bot-api/v6" ) func main() { From 1376e01c644aecfc4d1a12bc497d3d279abd4b02 Mon Sep 17 00:00:00 2001 From: OvyFlash Date: Wed, 30 Oct 2024 14:46:21 +0200 Subject: [PATCH 60/70] Add CODEOWNERS file --- CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 CODEOWNERS diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 00000000..eda9b16e --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +* @iamwavecut @zhuk-kk From e79bf7d0bdd69c2f039143263ba6e75ff9146081 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Wed, 30 Oct 2024 19:25:49 +0100 Subject: [PATCH 61/70] fix: typo --- types.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types.go b/types.go index 8bf58005..75d8fc42 100644 --- a/types.go +++ b/types.go @@ -2149,7 +2149,7 @@ type GiveawayCompleted struct { // // optional GiveawayMessage *Message `json:"giveaway_message,omitempty"` - // IsStarGiveaway True, if the giveaway is a Telegram Star giveaway. + // IsStarGiveaway True, if the giveaway is a Telegram Star giveaway. // Otherwise, currently, the giveaway is a Telegram Premium giveaway. // // optional @@ -3638,7 +3638,7 @@ type Sticker struct { // NeedsRepainting 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 // //optional - NeedsRepainting bool `json:"needs_reainting,omitempty"` + NeedsRepainting bool `json:"needs_repainting,omitempty"` // FileSize // // optional From 383e626943c0714b6b007193f169e845435e4de3 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:06:48 +0100 Subject: [PATCH 62/70] breaking: rename package while switching to tags --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 976952ee..ac59cc91 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/OvyFlash/telegram-bot-api/v6 +module github.com/OvyFlash/telegram-bot-api go 1.23 From 01dd2c622f66d2e9a6db7c57893ac4fc35824810 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:07:30 +0100 Subject: [PATCH 63/70] noop: create examples --- bot_test.go | 179 +---------------------------- examples/polling_echo.go | 73 ++++++++++++ examples/polling_inline_query.go | 43 +++++++ examples/webhook_custom_handler.go | 86 ++++++++++++++ examples/webhook_echo.go | 65 +++++++++++ 5 files changed, 268 insertions(+), 178 deletions(-) create mode 100644 examples/polling_echo.go create mode 100644 examples/polling_inline_query.go create mode 100644 examples/webhook_custom_handler.go create mode 100644 examples/webhook_echo.go diff --git a/bot_test.go b/bot_test.go index d61a73b5..0e98e38a 100644 --- a/bot_test.go +++ b/bot_test.go @@ -1,14 +1,12 @@ package tgbotapi import ( - "net/http" "os" "testing" "time" ) const ( - TestToken = "153667468:AAHlSHlMqSt1f_uFmVRJbm5gntu2HI4WW8I" ChatID = 76918703 Channel = "@tgbotapitest" SupergroupChatID = -1001120141283 @@ -35,7 +33,7 @@ func (t testLogger) Printf(format string, v ...interface{}) { } func getBot(t *testing.T) (*BotAPI, error) { - bot, err := NewBotAPI(TestToken) + bot, err := NewBotAPI(os.Getenv("TEST_TOKEN")) bot.Debug = true logger := testLogger{t} @@ -671,154 +669,6 @@ func TestSendWithMediaGroupAudio(t *testing.T) { } } -func ExampleNewBotAPI() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - // Optional: wait for updates and clear them if you don't want to handle - // a large backlog of old messages - time.Sleep(time.Millisecond * 500) - updates.Clear() - - for update := range updates { - if update.Message == nil { - continue - } - - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - - msg := NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyParameters.MessageID = update.Message.MessageID - - bot.Send(msg) - } -} - -func ExampleNewWebhook() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, FilePath("cert.pem")) - - if err != nil { - panic(err) - } - - _, err = bot.Request(wh) - - if err != nil { - panic(err) - } - - info, err := bot.GetWebhookInfo() - - if err != nil { - panic(err) - } - - if info.LastErrorDate != 0 { - log.Printf("failed to set webhook: %s", info.LastErrorMessage) - } - - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } -} - -func ExampleWebhookHandler() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, FilePath("cert.pem")) - - if err != nil { - panic(err) - } - - _, err = bot.Request(wh) - if err != nil { - panic(err) - } - info, err := bot.GetWebhookInfo() - if err != nil { - panic(err) - } - if info.LastErrorDate != 0 { - log.Printf("[Telegram callback failed]%s", info.LastErrorMessage) - } - - http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { - update, err := bot.HandleUpdate(r) - if err != nil { - log.Printf("%+v\n", err.Error()) - } else { - log.Printf("%+v\n", *update) - } - }) - - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) -} - -func ExampleInlineConfig() { - bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot - if err != nil { - panic(err) - } - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - for update := range updates { - if update.InlineQuery == nil { // if no inline query, ignore it - continue - } - - article := NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query) - article.Description = update.InlineQuery.Query - - inlineConf := InlineConfig{ - InlineQueryID: update.InlineQuery.ID, - IsPersonal: true, - CacheTime: 0, - Results: []interface{}{article}, - } - - if _, err := bot.Request(inlineConf); err != nil { - log.Println(err) - } - } -} - func TestDeleteMessage(t *testing.T) { bot, _ := getBot(t) @@ -1021,33 +871,6 @@ func TestCommands(t *testing.T) { } } -// TODO: figure out why test is failing -// -// func TestEditMessageMedia(t *testing.T) { -// bot, _ := getBot(t) - -// msg := NewPhoto(ChatID, "tests/image.jpg") -// msg.Caption = "Test" -// m, err := bot.Send(msg) - -// if err != nil { -// t.Error(err) -// } - -// edit := EditMessageMediaConfig{ -// BaseEdit: BaseEdit{ -// ChatID: ChatID, -// MessageID: m.MessageID, -// }, -// Media: NewInputMediaVideo(FilePath("tests/video.mp4")), -// } - -// _, err = bot.Request(edit) -// if err != nil { -// t.Error(err) -// } -// } - func TestPrepareInputMediaForParams(t *testing.T) { media := []interface{}{ NewInputMediaPhoto(FilePath("tests/image.jpg")), diff --git a/examples/polling_echo.go b/examples/polling_echo.go new file mode 100644 index 00000000..c9852e0c --- /dev/null +++ b/examples/polling_echo.go @@ -0,0 +1,73 @@ +package main + +import ( + "log" + "time" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { polling_echo() } + +func polling_echo() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + + // Empty list allows all updates excluding + // UpdateTypeChatMember, UpdateTypeMessageReaction and UpdateTypeMessageReactionCount + updateConfig.AllowedUpdates = []string{ + api.UpdateTypeMessage, + api.UpdateTypeEditedMessage, + api.UpdateTypeChannelPost, + api.UpdateTypeEditedChannelPost, + api.UpdateTypeBusinessConnection, + api.UpdateTypeBusinessMessage, + api.UpdateTypeEditedBusinessMessage, + api.UpdateTypeDeletedBusinessMessages, + api.UpdateTypeMessageReaction, + api.UpdateTypeMessageReactionCount, + api.UpdateTypeInlineQuery, + api.UpdateTypeChosenInlineResult, + api.UpdateTypeCallbackQuery, + api.UpdateTypeShippingQuery, + api.UpdateTypePreCheckoutQuery, + api.UpdateTypePurchasedPaidMedia, + api.UpdateTypePoll, + api.UpdateTypePollAnswer, + api.UpdateTypeMyChatMember, + api.UpdateTypeChatMember, + api.UpdateTypeChatJoinRequest, + api.UpdateTypeChatBoost, + api.UpdateTypeRemovedChatBoost, + } + + updatesChannel := bot.GetUpdatesChan(updateConfig) + + // Optional: wait for updates and clear them if you don't want to handle + // a large backlog of old messages + time.Sleep(time.Millisecond * 500) + updatesChannel.Clear() + + for update := range updatesChannel { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + } +} diff --git a/examples/polling_inline_query.go b/examples/polling_inline_query.go new file mode 100644 index 00000000..1591f3fe --- /dev/null +++ b/examples/polling_inline_query.go @@ -0,0 +1,43 @@ +package main + +import ( + "log" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { polling_inline_query() } + +func polling_inline_query() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") // create new bot + if err != nil { + panic(err) + } + + log.Printf("Authorized on account %s", bot.Self.UserName) + + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + + updatesChannel := bot.GetUpdatesChan(updateConfig) + + for update := range updatesChannel { + if update.InlineQuery == nil { // if no inline query, skip update + continue + } + + article := api.NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query) + article.Description = update.InlineQuery.Query + + inlineConfig := api.InlineConfig{ + InlineQueryID: update.InlineQuery.ID, + IsPersonal: true, + CacheTime: 0, + Results: []interface{}{article}, + } + + if _, err := bot.Request(inlineConfig); err != nil { + log.Println(err) + } + } +} diff --git a/examples/webhook_custom_handler.go b/examples/webhook_custom_handler.go new file mode 100644 index 00000000..cdf98230 --- /dev/null +++ b/examples/webhook_custom_handler.go @@ -0,0 +1,86 @@ +package main + +import ( + "log" + "net/http" + "sync" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { webhook_custom_handler() } + +func webhook_custom_handler() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + // Listen for updates from the webhook and handle them yourself + http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { + update, err := bot.HandleUpdate(r) + if err != nil { + log.Printf("%+v\n", err.Error()) + } else { + log.Printf("%+v\n", *update) + } + + if update.Message == nil { + return + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + }) + + waitGroup := sync.WaitGroup{} + + waitGroup.Add(1) + go func() { + defer waitGroup.Done() + if err := http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil); err != nil { + log.Printf("Error listening on TLS: %v", err) + } + }() + + // Set the webhook + webHook, err := api.NewWebhookWithCert("https://your-bot-host-url/"+bot.Token, api.FilePath("cert.pem")) + if err != nil { + panic(err) + } + if err != nil { + panic(err) + } + + apiResponse, err := bot.Request(webHook) + if err != nil { + panic(err) + } + + if apiResponse.Ok { + log.Printf("Webhook set successfully") + } else { + log.Printf("Failed to set webhook: %s", apiResponse.Description) + } + + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + + if info.LastErrorDate != 0 { + log.Printf("Failed to get webhook info: %s", info.LastErrorMessage) + } + + // Wait for the server to terminate + waitGroup.Wait() +} diff --git a/examples/webhook_echo.go b/examples/webhook_echo.go new file mode 100644 index 00000000..2be84bcc --- /dev/null +++ b/examples/webhook_echo.go @@ -0,0 +1,65 @@ +package main + +import ( + "log" + "net/http" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { webhook_echo() } + +func webhook_echo() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + // Listen for updates from the webhook + updates := bot.ListenForWebhook("/" + bot.Token) + go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) + + // Set the webhook + webHook, err := api.NewWebhookWithCert("https://your-bot-host-url/"+bot.Token, api.FilePath("cert.pem")) + if err != nil { + panic(err) + } + + apiResponse, err := bot.Request(webHook) + if err != nil { + panic(err) + } + + if apiResponse.Ok { + log.Printf("Webhook set successfully") + } else { + log.Printf("Failed to set webhook: %s", apiResponse.Description) + } + + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + + if info.LastErrorDate != 0 { + log.Printf("Failed to get webhook info: %s", info.LastErrorMessage) + } + + for update := range updates { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + } +} From 8afd2aca51ecfae7b30ae91ed9079fc089b6f5d8 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:43:40 +0100 Subject: [PATCH 64/70] Update README.md --- README.md | 180 +++++++++++++++++++++++++++--------------------------- 1 file changed, 89 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 4fa7fc1b..12bb2c16 100644 --- a/README.md +++ b/README.md @@ -1,120 +1,118 @@ -# Golang bindings for the Telegram Bot API -[![Go Reference](https://pkg.go.dev/badge/github.com/OvyFlash/telegram-bot-api/v6.svg)](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api/v6) -[![Test](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/go-telegram-bot-api/telegram-bot-api/actions/workflows/test.yml) +# Golang Bindings for the Telegram Bot API +[![Go Reference](https://pkg.go.dev/badge/github.com/OvyFlash/telegram-bot-api.svg)](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api) +[![Test](https://github.com/OvyFlash/telegram-bot-api/actions/workflows/test.yml/badge.svg)](https://github.com/OvyFlash/telegram-bot-api/actions/workflows/test.yml) -All methods are fairly self-explanatory, and reading the [godoc](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api/v6) page should -explain everything. If something isn't clear, open an issue or submit -a pull request. +# Headline -There are more tutorials and high-level information on the website, [go-telegram-bot-api.dev](https://go-telegram-bot-api.dev). +This is a maintained fork of go-telegram-bot-api that preserves the original design while staying current with the latest Telegram Bot API specifications. It continues the development of the original [github.com/go-telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api) package. -The scope of this project is just to provide a wrapper around the API -without any additional features. There are other projects for creating -something with plugins and command handlers without having to design -all that yourself. +## Features -Join [the development group](https://telegram.me/go_telegram_bot_api) if -you want to ask questions or discuss development. +- Complete coverage of the Telegram Bot API +- Simple and intuitive interface +- Minimal dependencies +- Production-ready and actively maintained +- Preserves original API structure for easy migration -## Example +## Installation -First, ensure the library is installed and up to date by running -`go get -u github.com/OvyFlash/telegram-bot-api/v6`. - -This is a very simple bot that just displays any gotten updates, -then replies it to that chat. - -```go -package main - -import ( - "log" - - tgbotapi "github.com/OvyFlash/telegram-bot-api/v6" -) - -func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := tgbotapi.NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - for update := range updates { - if update.Message != nil { // If we got a message - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) +Install the latest version: +```bash +go get -u github.com/OvyFlash/telegram-bot-api +``` - msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyParameters.MessageID = update.Message.MessageID +> ❗ Tag versioning is discouraged due to the unstable nature of the Telegram Bot API, and it might break at any time after the API changes. +>``` +>go get -u github.com/OvyFlash/telegram-bot-api/v7 +>``` - bot.Send(msg) - } - } -} -``` +## Quick Start -If you need to use webhooks (if you wish to run on Google App Engine), -you may use a slightly different method. +Here's a simple echo bot using polling: ```go package main import ( - "log" - "net/http" - - "github.com/OvyFlash/telegram-bot-api/v6" + "log" + "time" + api "github.com/OvyFlash/telegram-bot-api" ) func main() { - bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken") - if err != nil { - log.Fatal(err) - } + bot, err := api.NewBotAPI("BOT_TOKEN") + if err != nil { + panic(err) + } - bot.Debug = true + log.Printf("Authorized on account %s", bot.Self.UserName) - log.Printf("Authorized on account %s", bot.Self.UserName) + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + updatesChannel := bot.GetUpdatesChan(updateConfig) - wh, _ := tgbotapi.NewWebhookWithCert("https://www.example.com:8443/"+bot.Token, "cert.pem") + // Optional: Clear initial updates + time.Sleep(time.Millisecond * 500) + updatesChannel.Clear() - _, err = bot.Request(wh) - if err != nil { - log.Fatal(err) - } + for update := range updatesChannel { + if update.Message == nil { + continue + } - info, err := bot.GetWebhookInfo() - if err != nil { - log.Fatal(err) - } + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - if info.LastErrorDate != 0 { - log.Printf("Telegram callback failed: %s", info.LastErrorMessage) - } + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } + bot.Send(msg) + } } ``` -If you need, you may generate a self-signed certificate, as this requires -HTTPS / TLS. The above example tells Telegram that this is your -certificate and that it should be trusted, even though it is not -properly signed. +## Webhook Setup +For webhook implementation: +1. Check the [examples](./examples) folder for examples of webhook implementations +2. Use HTTPS (required by Telegram) + - Generate SSL certificate: + ```bash openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes - -Now that [Let's Encrypt](https://letsencrypt.org) is available, -you may wish to generate your free TLS certificate there. + ``` + - Bring your own SSL certificate. [Let's Encrypt](https://letsencrypt.org) is recommended for free TLS certificates in production. + +## Documentation + +- [GoDoc](https://pkg.go.dev/github.com/OvyFlash/telegram-bot-api) +- Check the [examples](./examples) directory for more use cases + + +## Contributing + +- Issues and feature requests are welcome +- Pull requests should maintain the existing design philosophy +- The focus is on providing a clean API wrapper without additional features + +## License + +>The [MIT License](./LICENSE.txt) +> +>Copyright (c) 2015 Syfaro +> +>Permission is hereby granted, free of charge, to any person obtaining a copy +>of this software and associated documentation files (the "Software"), to deal +>in the Software without restriction, including without limitation the rights +>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +>copies of the Software, and to permit persons to whom the Software is +>furnished to do so, subject to the following conditions: +> +>The above copyright notice and this permission notice shall be included in all +>copies or substantial portions of the Software. +> +>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +>SOFTWARE. From e6837402196a4ed59883a351cd2c15c1f997feec Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:53:08 +0100 Subject: [PATCH 65/70] Update go.mod --- go.mod | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/go.mod b/go.mod index ac59cc91..e74046ec 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,8 @@ module github.com/OvyFlash/telegram-bot-api +retract ( + v5.0.0 + v6.0.0 +) + go 1.23 From 8a154ea277de6610d69684d91c9b1fdae4a20f13 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:57:48 +0100 Subject: [PATCH 66/70] Update configs.go --- configs.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/configs.go b/configs.go index 632fd695..f3d5bf16 100644 --- a/configs.go +++ b/configs.go @@ -3273,6 +3273,8 @@ func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { if m.Thumb != nil && m.Thumb.NeedsUpload() { m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) } + + return case InputMediaDocument: if m.Media.NeedsUpload() { m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) From 020f85f2dadba00f186b4f28db8025e73cfc1d38 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 18:18:46 +0100 Subject: [PATCH 67/70] Update README.md --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 12bb2c16..69d8ea8a 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,9 @@ Install the latest version: go get -u github.com/OvyFlash/telegram-bot-api ``` + > ❗ Tag versioning is discouraged due to the unstable nature of the Telegram Bot API, and it might break at any time after the API changes. ->``` ->go get -u github.com/OvyFlash/telegram-bot-api/v7 ->``` +> ~~`go get -u github.com/OvyFlash/telegram-bot-api/v7`~~ ## Quick Start From 851f2334eccf954b806a3254405b4396090d7d45 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 20:11:46 +0100 Subject: [PATCH 68/70] fix: typo --- configs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs.go b/configs.go index f3d5bf16..2c9f219b 100644 --- a/configs.go +++ b/configs.go @@ -3274,7 +3274,7 @@ func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { m.Thumb = fileAttach(fmt.Sprintf("attach://file-%d-thumb", idx)) } - return + return m case InputMediaDocument: if m.Media.NeedsUpload() { m.Media = fileAttach(fmt.Sprintf("attach://file-%d", idx)) From 3f2ca0c14ada05fba840432533fc5af70e98b15a Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 19 Dec 2024 18:19:06 +0100 Subject: [PATCH 69/70] Update go.mod --- go.mod | 5 ----- 1 file changed, 5 deletions(-) diff --git a/go.mod b/go.mod index e74046ec..ac59cc91 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,3 @@ module github.com/OvyFlash/telegram-bot-api -retract ( - v5.0.0 - v6.0.0 -) - go 1.23 From 4350cc49dfca4a9ada737f8f02f59f597b23090f Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Tue, 25 Mar 2025 12:51:00 +0100 Subject: [PATCH 70/70] fix: unwraps `PaidMediaConfig` to allow paid media in MediaGroupConfig --- configs.go | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/configs.go b/configs.go index 2c9f219b..8fd3dc7e 100644 --- a/configs.go +++ b/configs.go @@ -597,7 +597,7 @@ func (config DocumentConfig) files() []RequestFile { // StickerConfig contains information about a SendSticker request. type StickerConfig struct { - //Emoji associated with the sticker; only for just uploaded stickers + // Emoji associated with the sticker; only for just uploaded stickers Emoji string BaseFile } @@ -904,7 +904,7 @@ type EditMessageLiveLocationConfig struct { BaseEdit Latitude float64 // required Longitude float64 // required - LivePeriod int //optional + LivePeriod int // optional HorizontalAccuracy float64 // optional Heading int // optional ProximityAlertRadius int // optional @@ -1406,7 +1406,7 @@ func (config DeleteWebhookConfig) params() (Params, error) { // InlineQueryResultsButton represents a button to be shown above inline query results. You must use exactly one of the optional fields. type InlineQueryResultsButton struct { - //Label text on the button + // Label 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 switch back to the inline mode using the method switchInlineQuery inside the Web App. // @@ -2056,12 +2056,12 @@ func (config InvoiceConfig) method() string { // InvoiceLinkConfig contains information for createInvoiceLink method type InvoiceLinkConfig struct { - Title string //Required - Description string //Required - Payload string //Required - ProviderToken string //Required - Currency string //Required - Prices []LabeledPrice //Required + Title string // Required + Description string // Required + Payload string // Required + ProviderToken string // Required + Currency string // Required + Prices []LabeledPrice // Required MaxTipAmount int SuggestedTipAmounts []int ProviderData string @@ -2180,8 +2180,8 @@ func (config GetStarTransactionsConfig) params() (Params, error) { // RefundStarPaymentConfig refunds a successful payment in Telegram Stars. // Returns True on success. type RefundStarPaymentConfig struct { - UserID int64 //required - TelegramPaymentChargeID string //required + UserID int64 // required + TelegramPaymentChargeID string // required } func (config RefundStarPaymentConfig) method() string { @@ -2410,7 +2410,7 @@ type NewStickerSetConfig struct { Title string Stickers []InputSticker StickerType string - NeedsRepainting bool //optional; 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 // optional; 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 } func (config NewStickerSetConfig) method() string { @@ -3099,7 +3099,7 @@ func (config GetMyDescriptionConfig) params() (Params, error) { type SetMyDescriptionConfig struct { // Pass an empty string to remove the dedicated description for the given language. Description string - //If empty, the description will be applied to all users for whose language there is no dedicated description. + // If empty, the description will be applied to all users for whose language there is no dedicated description. LanguageCode string } @@ -3301,6 +3301,11 @@ func prepareInputMediaParam(inputMedia interface{}, idx int) interface{} { func prepareInputMediaFile(inputMedia interface{}, idx int) []RequestFile { files := []RequestFile{} + // Unwrap the PaidMediaConfig to get the media + if paidMedia, ok := inputMedia.(PaidMediaConfig); ok { + inputMedia = paidMedia.Media + } + switch m := inputMedia.(type) { case InputMediaPhoto: if m.Media.NeedsUpload() {