diff --git a/CHANGELOG.md b/CHANGELOG.md index a336c2b1..7dba2676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## Unreleased + +- Breaking: `GetMe` now returns `*models.BotFullInfo` instead of `*models.User`. +- Breaking: `RichBlockExpandableBlockQuotation` and `InputRichBlockExpandableBlockQuotation` replace `Text` with `Blocks`. Nested files inside those blocks are uploaded. +- `BotFullInfo` adds `active_usernames`, `inline_query_placeholder`, `needs_inline_query_location`, and `has_topic_sidebar`. It also adds `has_main_web_app`, which `getMe` already returned and `User` did not declare. +- Fields that `getMe` used to return on `User` move to `BotFullInfo`: `can_join_groups`, `can_read_all_group_messages`, `supports_inline_queries`, `can_connect_to_business`, `has_topics_enabled`, `allows_users_to_create_topics`, `can_manage_bots`, `supports_guest_queries`, and `supports_join_request_queries`. `User` keeps the fields sent for ordinary users. +- Add `SetMySettings`. Omitted parameters stay unchanged: a nil bool or integer is not sent, `False()` and a zero feedback denominator are sent, and an empty placeholder string clears the inline placeholder. +- Callback queries from the bot's own messages can arrive with `inline_message_id` instead of `message` when `callback_query_mode` says so. `WriteAccessAllowed.Inviter` is the bot owner who invited the user into the private chat. + ## v1.30.0 (2026-11-19) - Preserve update delivery during shutdown (#317). Polling resumes at the first diff --git a/README.md b/README.md index c0e9f736..fd9f6ce7 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ > [Telegram Group](https://t.me/gotelegrambotui) -> Supports Bot API version: [10.4](https://core.telegram.org/bots/api#november-9-2026) from November 9, 2026 +> Supports Bot API version: [10.5](https://core.telegram.org/bots/api-changelog#november-22-2026) from November 22, 2026 It's a Go zero-dependencies telegram bot framework diff --git a/bot.go b/bot.go index 15087c12..0716333d 100644 --- a/bot.go +++ b/bot.go @@ -139,12 +139,12 @@ func (b *Bot) SetToken(token string) { // setUsername records the username GetMe returned, unless the token now // belongs to another bot, as when it was switched during the request. The -// token starts with the bot's ID, which GetMe returns as the user ID. -func (b *Bot) setUsername(me *models.User) { +// token starts with the bot's ID, which GetMe returns as id. +func (b *Bot) setUsername(id int64, username string) { b.usernameMx.Lock() defer b.usernameMx.Unlock() - if me.ID == b.ID() { - b.username = me.Username + if id == b.ID() { + b.username = username } } diff --git a/bot_test.go b/bot_test.go index 9eedb0ee..a8bbb979 100644 --- a/bot_test.go +++ b/bot_test.go @@ -534,7 +534,7 @@ func TestBot_UsernameConcurrentAccess(t *testing.T) { go func() { defer wg.Done() for j := 0; j < 100; j++ { - b.setUsername(&models.User{ID: 1, Username: "my_bot"}) + b.setUsername(1, "my_bot") } }() go func() { diff --git a/build_request_form.go b/build_request_form.go index c0712ff0..5357e0da 100644 --- a/build_request_form.go +++ b/build_request_form.go @@ -418,6 +418,10 @@ func addInputRichBlockAttachments(form *requestForm, block models.InputRichBlock if block.InputRichBlockBlockQuotation != nil { return addInputRichBlockSliceAttachments(form, block.InputRichBlockBlockQuotation.Blocks) } + case models.RichBlockTypeExpandableBlockQuotation: + if block.InputRichBlockExpandableBlockQuotation != nil { + return addInputRichBlockSliceAttachments(form, block.InputRichBlockExpandableBlockQuotation.Blocks) + } case models.RichBlockTypeCollage: if block.InputRichBlockCollage != nil { return addInputRichBlockSliceAttachments(form, block.InputRichBlockCollage.Blocks) diff --git a/build_request_form_test.go b/build_request_form_test.go index 8d229331..47c6e253 100644 --- a/build_request_form_test.go +++ b/build_request_form_test.go @@ -553,6 +553,12 @@ func Test_addInputRichBlockAttachments_containerBlocks(t *testing.T) { Blocks: []models.InputRichBlock{richDocumentBlock("quote.pdf")}, }, }, + { + Type: models.RichBlockTypeExpandableBlockQuotation, + InputRichBlockExpandableBlockQuotation: &models.InputRichBlockExpandableBlockQuotation{ + Blocks: []models.InputRichBlock{richDocumentBlock("expandable.pdf")}, + }, + }, { Type: models.RichBlockTypeCollage, InputRichBlockCollage: &models.InputRichBlockCollage{ @@ -587,7 +593,7 @@ func Test_addInputRichBlockAttachments_containerBlocks(t *testing.T) { assertEqualString(t, formFileNames(t, buf.String(), "XXX"), - "list.pdf,quote.pdf,collage.pdf,slideshow.pdf,details.pdf", + "list.pdf,quote.pdf,expandable.pdf,collage.pdf,slideshow.pdf,details.pdf", ) } @@ -603,6 +609,7 @@ func Test_addInputRichBlockAttachments_missingVariant(t *testing.T) { models.RichBlockTypeVoiceNote, models.RichBlockTypeList, models.RichBlockTypeBlockQuotation, + models.RichBlockTypeExpandableBlockQuotation, models.RichBlockTypeCollage, models.RichBlockTypeSlideshow, models.RichBlockTypeDetails, diff --git a/examples/inline_keyboard/main.go b/examples/inline_keyboard/main.go index fe95aee3..c2066ef0 100644 --- a/examples/inline_keyboard/main.go +++ b/examples/inline_keyboard/main.go @@ -39,8 +39,12 @@ func callbackHandler(ctx context.Context, b *bot.Bot, update *models.Update) { CallbackQueryID: update.CallbackQuery.ID, ShowAlert: false, }) + msg := update.CallbackQuery.Message.Message + if msg == nil { + return + } b.SendMessage(ctx, &bot.SendMessageParams{ - ChatID: update.CallbackQuery.Message.Message.Chat.ID, + ChatID: msg.Chat.ID, Text: "You selected the button: " + update.CallbackQuery.Data, }) } diff --git a/examples/inline_keyboard_multiselect/main.go b/examples/inline_keyboard_multiselect/main.go index 1573306f..5dd35e80 100644 --- a/examples/inline_keyboard_multiselect/main.go +++ b/examples/inline_keyboard_multiselect/main.go @@ -43,6 +43,11 @@ func callbackHandler(ctx context.Context, b *bot.Bot, update *models.Update) { ShowAlert: false, }) + msg := update.CallbackQuery.Message.Message + if msg == nil { + return + } + switch update.CallbackQuery.Data { case "btn_opt1": currentOptions[0] = !currentOptions[0] @@ -52,19 +57,19 @@ func callbackHandler(ctx context.Context, b *bot.Bot, update *models.Update) { currentOptions[2] = !currentOptions[2] case "btn_select": b.DeleteMessage(ctx, &bot.DeleteMessageParams{ - ChatID: update.CallbackQuery.Message.Message.Chat.ID, - MessageID: update.CallbackQuery.Message.Message.ID, + ChatID: msg.Chat.ID, + MessageID: msg.ID, }) b.SendMessage(ctx, &bot.SendMessageParams{ - ChatID: update.CallbackQuery.Message.Message.Chat.ID, + ChatID: msg.Chat.ID, Text: fmt.Sprintf("Selected options: %v", currentOptions), }) return } b.EditMessageReplyMarkup(ctx, &bot.EditMessageReplyMarkupParams{ - ChatID: update.CallbackQuery.Message.Message.Chat.ID, - MessageID: update.CallbackQuery.Message.Message.ID, + ChatID: msg.Chat.ID, + MessageID: msg.ID, ReplyMarkup: buildKeyboard(), }) } diff --git a/examples/middleware/main.go b/examples/middleware/main.go index 854197ac..0657b776 100644 --- a/examples/middleware/main.go +++ b/examples/middleware/main.go @@ -29,7 +29,7 @@ func main() { panic(err) } - b.RegisterHandler(bot.HandlerTypeCallbackQueryData, "", bot.MatchTypeExact, func(ctx context.Context, b *bot.Bot, update *models.Update) { + b.RegisterHandler(bot.HandlerTypeCallbackQueryData, "", bot.MatchTypePrefix, func(ctx context.Context, b *bot.Bot, update *models.Update) { log.Printf("callback query data: %s", update.CallbackQuery.Data) }, singleFlight) @@ -54,18 +54,34 @@ func showMessageWithUserName(next bot.HandlerFunc) bot.HandlerFunc { } } +type callbackFlightKey struct { + chatID int64 + messageID int +} + // singleFlight is a middleware that ensures that only one callback query is processed at a time. func singleFlight(next bot.HandlerFunc) bot.HandlerFunc { sf := sync.Map{} return func(ctx context.Context, b *bot.Bot, update *models.Update) { - if update.CallbackQuery != nil { - key := update.CallbackQuery.Message.Message.ID - if _, loaded := sf.LoadOrStore(key, struct{}{}); loaded { - return - } - defer sf.Delete(key) + if update.CallbackQuery == nil { + return + } + q := update.CallbackQuery + var key any + switch { + case q.InlineMessageID != "": + key = q.InlineMessageID + case q.Message.Message != nil: + key = callbackFlightKey{chatID: q.Message.Message.Chat.ID, messageID: q.Message.Message.ID} + default: next(ctx, b, update) + return } + if _, loaded := sf.LoadOrStore(key, struct{}{}); loaded { + return + } + defer sf.Delete(key) + next(ctx, b, update) } } diff --git a/methods.go b/methods.go index 6452b077..ce2c1c34 100644 --- a/methods.go +++ b/methods.go @@ -30,14 +30,14 @@ func (b *Bot) DeleteWebhook(ctx context.Context, params *DeleteWebhookParams) (b } // GetMe https://core.telegram.org/bots/api#getme -// GetMe also records the bot's username when the returned user is the bot the +// GetMe also records the bot's username when the returned bot is the one the // token belongs to, so a MatchTypeCommand or MatchTypeCommandStartOnly handler // for start also matches /start@bot_username. -func (b *Bot) GetMe(ctx context.Context) (*models.User, error) { - result := &models.User{} +func (b *Bot) GetMe(ctx context.Context) (*models.BotFullInfo, error) { + result := &models.BotFullInfo{} err := b.rawRequest(ctx, "getMe", nil, result) if err == nil { - b.setUsername(result) + b.setUsername(result.ID, result.Username) } return result, err } @@ -605,6 +605,13 @@ func (b *Bot) GetBusinessConnection(ctx context.Context, params *GetBusinessConn return result, err } +// SetMySettings https://core.telegram.org/bots/api#setmysettings +func (b *Bot) SetMySettings(ctx context.Context, params *SetMySettingsParams) (bool, error) { + var result bool + err := b.rawRequest(ctx, "setMySettings", params, &result) + return result, err +} + // SetMyCommands https://core.telegram.org/bots/api#setmycommands func (b *Bot) SetMyCommands(ctx context.Context, params *SetMyCommandsParams) (bool, error) { var result bool diff --git a/methods_params.go b/methods_params.go index 261b700b..ff018d72 100644 --- a/methods_params.go +++ b/methods_params.go @@ -799,6 +799,36 @@ type GetBusinessConnectionParams struct { BusinessConnectionID any `json:"business_connection_id"` } +// CallbackQueryMode is how the bot receives callback queries from buttons +// in messages it sent. +// https://core.telegram.org/bots/api#setmysettings +type CallbackQueryMode string + +const ( + CallbackQueryModeDefault CallbackQueryMode = "default" + CallbackQueryModeAuto CallbackQueryMode = "auto" + CallbackQueryModeInline CallbackQueryMode = "inline" +) + +// SetMySettingsParams https://core.telegram.org/bots/api#setmysettings +type SetMySettingsParams struct { + SupportsInlineQueries *bool `json:"supports_inline_queries,omitempty"` + InlineQueryPlaceholder *string `json:"inline_query_placeholder,omitempty"` + NeedsInlineQueryLocation *bool `json:"needs_inline_query_location,omitempty"` + InlineFeedbackShareDenominator *int `json:"inline_feedback_share_denominator,omitempty"` + CanJoinGroups *bool `json:"can_join_groups,omitempty"` + CanReadAllGroupMessages *bool `json:"can_read_all_group_messages,omitempty"` + CanConnectToBusiness *bool `json:"can_connect_to_business,omitempty"` + CanManageBots *bool `json:"can_manage_bots,omitempty"` + SupportsGuestQueries *bool `json:"supports_guest_queries,omitempty"` + SupportsJoinRequestQueries *bool `json:"supports_join_request_queries,omitempty"` + HasTopicsEnabled *bool `json:"has_topics_enabled,omitempty"` + AllowsUsersToCreateTopics *bool `json:"allows_users_to_create_topics,omitempty"` + HasTopicSidebar *bool `json:"has_topic_sidebar,omitempty"` + CanCommunicateWithBots *bool `json:"can_communicate_with_bots,omitempty"` + CallbackQueryMode CallbackQueryMode `json:"callback_query_mode,omitempty"` +} + type SetMyCommandsParams struct { Commands []models.BotCommand `json:"commands"` Scope models.BotCommandScope `json:"scope,omitempty"` diff --git a/methods_test.go b/methods_test.go index 9ffb1a76..938a4885 100644 --- a/methods_test.go +++ b/methods_test.go @@ -21,6 +21,7 @@ type httpClient struct { reqFiles map[string]string // multipart file parts by name, with expected content absent []string present []string + emptyBody bool t *testing.T } @@ -28,6 +29,12 @@ func (c *httpClient) Do(req *http.Request) (*http.Response, error) { if c.reqPath != "" && req.URL.Path != c.reqPath { return nil, fmt.Errorf("invalid request path %q, expect %q", req.URL.Path, c.reqPath) } + if c.emptyBody { + if req.ContentLength != 0 || req.Header.Get("Content-Type") != "" { + c.t.Errorf("expected empty body, content-type %q length %d", req.Header.Get("Content-Type"), req.ContentLength) + return nil, fmt.Errorf("expected empty body") + } + } if c.reqFields != nil { for k, v := range c.reqFields { if v != req.FormValue(k) { @@ -137,11 +144,14 @@ func TestBot_Methods(t *testing.T) { }) t.Run("GetMe", func(t *testing.T) { - c := &httpClient{t: t, resp: `{"username":"foo"}`} + c := &httpClient{t: t, resp: `{"id":1,"is_bot":true,"first_name":"Bot","username":"foo","supports_inline_queries":true,"has_topic_sidebar":true}`} b := &Bot{client: c} resp, err := b.GetMe(context.Background()) assertNoErr(t, err) assertEqualString(t, resp.Username, "foo") + if !resp.SupportsInlineQueries || !resp.HasTopicSidebar { + t.Fatalf("%+v", resp) + } }) t.Run("Logout", func(t *testing.T) { @@ -2079,3 +2089,55 @@ func TestAnswerInlineQuery_CacheTime(t *testing.T) { } }) } + +func TestBot_SetMySettings(t *testing.T) { + t.Run("empty", func(t *testing.T) { + c := &httpClient{t: t, resp: `true`, emptyBody: true} + b := &Bot{client: c} + resp, err := b.SetMySettings(context.Background(), &SetMySettingsParams{}) + assertNoErr(t, err) + assertTrue(t, resp) + }) + + t.Run("explicit values", func(t *testing.T) { + empty := "" + zero := 0 + c := &httpClient{t: t, resp: `true`, reqFields: map[string]string{ + "can_join_groups": "false", + "inline_query_placeholder": "", + "inline_feedback_share_denominator": "0", + "callback_query_mode": "inline", + }, present: []string{"inline_query_placeholder"}, absent: []string{ + "supports_inline_queries", + "has_topic_sidebar", + }} + b := &Bot{client: c} + resp, err := b.SetMySettings(context.Background(), &SetMySettingsParams{ + CanJoinGroups: False(), + InlineQueryPlaceholder: &empty, + InlineFeedbackShareDenominator: &zero, + CallbackQueryMode: CallbackQueryModeInline, + }) + assertNoErr(t, err) + assertTrue(t, resp) + }) + + t.Run("preserves placeholder characters", func(t *testing.T) { + placeholder := "{\"count\":1,\"path\":\"a\\\\b\"}\n& \"quoted\"" + buf := &bytes.Buffer{} + w := multipart.NewWriter(buf) + _, err := buildRequestForm(w, &SetMySettingsParams{ + InlineQueryPlaceholder: &placeholder, + }) + assertNoErr(t, err) + if err := w.Close(); err != nil { + t.Fatal(err) + } + form, err := multipart.NewReader(buf, w.Boundary()).ReadForm(1 << 20) + assertNoErr(t, err) + got, ok := form.Value["inline_query_placeholder"] + if !ok || len(got) != 1 || got[0] != placeholder { + t.Fatalf("placeholder: got %v, want %q", got, placeholder) + } + }) +} diff --git a/models/callback_query.go b/models/callback_query.go index 0a18ea50..7d1009b5 100644 --- a/models/callback_query.go +++ b/models/callback_query.go @@ -1,6 +1,11 @@ package models // CallbackQuery https://core.telegram.org/bots/api#callbackquery +// +// For a button on a message sent by the bot, Message is set unless +// callback_query_mode of setMySettings uses inline_message_id instead. +// InlineMessageID is set for a message sent via the bot in inline mode, +// and can also be set for the bot's own messages in that mode. type CallbackQuery struct { ID string `json:"id"` From User `json:"from,omitempty"` diff --git a/models/forum.go b/models/forum.go index 747cd493..ebb230fc 100644 --- a/models/forum.go +++ b/models/forum.go @@ -70,8 +70,11 @@ type ChatShared struct { } // WriteAccessAllowed https://core.telegram.org/bots/api#writeaccessallowed +// +// Inviter is the owner of the bot when that owner invited the user to the private chat. type WriteAccessAllowed struct { FromRequest bool `json:"from_request,omitempty"` WebAppName string `json:"web_app_name,omitempty"` FromAttachmentMenu bool `json:"from_attachment_menu,omitempty"` + Inviter *User `json:"inviter,omitempty"` } diff --git a/models/input_rich_block.go b/models/input_rich_block.go index 8c9b15f6..cd5eb475 100644 --- a/models/input_rich_block.go +++ b/models/input_rich_block.go @@ -275,9 +275,9 @@ type InputRichBlockBlockQuotation struct { // InputRichBlockExpandableBlockQuotation https://core.telegram.org/bots/api#inputrichblockexpandableblockquotation type InputRichBlockExpandableBlockQuotation struct { - Type RichBlockType `json:"type"` // always "expandable_blockquote" - Text RichText `json:"text"` - Credit *RichText `json:"credit,omitempty"` + Type RichBlockType `json:"type"` // always "expandable_blockquote" + Blocks []InputRichBlock `json:"blocks"` + Credit *RichText `json:"credit,omitempty"` } // InputRichBlockPullQuotation https://core.telegram.org/bots/api#inputrichblockpullquotation diff --git a/models/input_rich_block_test.go b/models/input_rich_block_test.go index c5b9da93..00bca285 100644 --- a/models/input_rich_block_test.go +++ b/models/input_rich_block_test.go @@ -20,7 +20,7 @@ func TestInputRichBlock_Marshal(t *testing.T) { {"divider", InputRichBlock{Type: RichBlockTypeDivider, InputRichBlockDivider: &InputRichBlockDivider{}}, "divider"}, {"math", InputRichBlock{Type: RichBlockTypeMathematicalExpression, InputRichBlockMathematicalExpression: &InputRichBlockMathematicalExpression{Expression: "x^2"}}, "mathematical_expression"}, {"thinking", InputRichBlock{Type: RichBlockTypeThinking, InputRichBlockThinking: &InputRichBlockThinking{Text: RichText{PlainText: "reasoning"}}}, "thinking"}, - {"expandable_blockquote", InputRichBlock{Type: RichBlockTypeExpandableBlockQuotation, InputRichBlockExpandableBlockQuotation: &InputRichBlockExpandableBlockQuotation{Text: RichText{PlainText: "q"}}}, "expandable_blockquote"}, + {"expandable_blockquote", InputRichBlock{Type: RichBlockTypeExpandableBlockQuotation, InputRichBlockExpandableBlockQuotation: &InputRichBlockExpandableBlockQuotation{Blocks: []InputRichBlock{{Type: RichBlockTypeParagraph, InputRichBlockParagraph: &InputRichBlockParagraph{Text: RichText{PlainText: "q"}}}}}}, "expandable_blockquote"}, {"buttons", InputRichBlock{Type: RichBlockTypeButtons, InputRichBlockButtons: &InputRichBlockButtons{Buttons: []RichMessageButton{{Text: RichText{PlainText: "Go"}, CallbackData: "go"}}, Align: "right"}}, "buttons"}, {"document", InputRichBlock{Type: RichBlockTypeDocument, InputRichBlockDocument: &InputRichBlockDocument{Document: InputMediaDocument{Media: "d"}}}, "document"}, } diff --git a/models/rich_block.go b/models/rich_block.go index 0b1fa66a..32bf9b5e 100644 --- a/models/rich_block.go +++ b/models/rich_block.go @@ -275,7 +275,7 @@ type RichBlockBlockQuotation struct { // RichBlockExpandableBlockQuotation https://core.telegram.org/bots/api#richblockexpandableblockquotation type RichBlockExpandableBlockQuotation struct { Type RichBlockType `json:"type"` - Text RichText `json:"text"` + Blocks []RichBlock `json:"blocks"` Credit *RichText `json:"credit,omitempty"` } diff --git a/models/rich_block_test.go b/models/rich_block_test.go index c38b51cc..d476c37c 100644 --- a/models/rich_block_test.go +++ b/models/rich_block_test.go @@ -110,12 +110,16 @@ func TestRichBlock_MarshalDoesNotMutate(t *testing.T) { } func TestRichBlock_ExpandableBlockQuotation(t *testing.T) { - rb := richBlockRoundTrip(t, `{"type":"expandable_blockquote","text":"quoted","credit":"author"}`) + rb := richBlockRoundTrip(t, `{"type":"expandable_blockquote","blocks":[{"type":"paragraph","text":"quoted"}],"credit":"author"}`) if rb.Type != RichBlockTypeExpandableBlockQuotation { t.Fatalf("wrong type %q", rb.Type) } - if rb.RichBlockExpandableBlockQuotation == nil || rb.RichBlockExpandableBlockQuotation.Text.PlainText != "quoted" { - t.Fatal("expandable blockquote text not decoded") + q := rb.RichBlockExpandableBlockQuotation + if q == nil || len(q.Blocks) != 1 || q.Blocks[0].RichBlockParagraph == nil || q.Blocks[0].RichBlockParagraph.Text.PlainText != "quoted" { + t.Fatal("expandable blockquote blocks not decoded") + } + if q.Credit == nil || q.Credit.PlainText != "author" { + t.Fatal("expandable blockquote credit not decoded") } } diff --git a/models/user.go b/models/user.go index f5f5836b..af35c6ff 100644 --- a/models/user.go +++ b/models/user.go @@ -8,23 +8,36 @@ type UserProfilePhotos struct { // User https://core.telegram.org/bots/api#user type User struct { - ID int64 `json:"id"` - IsBot bool `json:"is_bot"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Username string `json:"username,omitempty"` - LanguageCode string `json:"language_code,omitempty"` - IsPremium bool `json:"is_premium,omitempty"` - AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"` - CanJoinGroups bool `json:"can_join_groups,omitempty"` - CanReadAllGroupMessages bool `json:"can_read_all_group_messages,omitempty"` - SupportInlineQueries bool `json:"supports_inline_queries,omitempty"` - CanConnectToBusiness bool `json:"can_connect_to_business,omitempty"` - HasTopicsEnabled bool `json:"has_topics_enabled,omitempty"` - AllowsUsersToCreateTopics bool `json:"allows_users_to_create_topics,omitempty"` - CanManageBots bool `json:"can_manage_bots,omitempty"` - SupportsJoinRequestQueries bool `json:"supports_join_request_queries,omitempty"` - SupportsGuestQueries bool `json:"supports_guest_queries,omitempty"` + ID int64 `json:"id"` + IsBot bool `json:"is_bot"` + FirstName string `json:"first_name,omitempty"` + LastName string `json:"last_name,omitempty"` + Username string `json:"username,omitempty"` + LanguageCode string `json:"language_code,omitempty"` + IsPremium bool `json:"is_premium,omitempty"` + AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"` +} + +// BotFullInfo https://core.telegram.org/bots/api#botfullinfo +type BotFullInfo struct { + ID int64 `json:"id"` + IsBot bool `json:"is_bot"` + FirstName string `json:"first_name"` + Username string `json:"username,omitempty"` + ActiveUsernames []string `json:"active_usernames,omitempty"` + CanJoinGroups bool `json:"can_join_groups"` + CanReadAllGroupMessages bool `json:"can_read_all_group_messages"` + SupportsGuestQueries bool `json:"supports_guest_queries"` + SupportsInlineQueries bool `json:"supports_inline_queries"` + InlineQueryPlaceholder string `json:"inline_query_placeholder,omitempty"` + NeedsInlineQueryLocation bool `json:"needs_inline_query_location"` + CanConnectToBusiness bool `json:"can_connect_to_business"` + HasMainWebApp bool `json:"has_main_web_app"` + HasTopicsEnabled bool `json:"has_topics_enabled"` + AllowsUsersToCreateTopics bool `json:"allows_users_to_create_topics"` + HasTopicSidebar bool `json:"has_topic_sidebar"` + CanManageBots bool `json:"can_manage_bots"` + SupportsJoinRequestQueries bool `json:"supports_join_request_queries"` } // UserProfileAudios https://core.telegram.org/bots/api#userprofileaudios diff --git a/models/user_test.go b/models/user_test.go index 256c2ef1..9917d2fd 100644 --- a/models/user_test.go +++ b/models/user_test.go @@ -2,11 +2,56 @@ package models import ( "encoding/json" + "strings" "testing" ) -// TestUser_SupportsJoinRequestQueries verifies supports_join_request_queries decodes when present and stays false when absent. -func TestUser_SupportsJoinRequestQueries(t *testing.T) { +func TestBotFullInfo(t *testing.T) { + const src = `{"id":42,"is_bot":true,"first_name":"Bot","username":"foo","active_usernames":["foo","foo_bot"],"supports_inline_queries":true,"inline_query_placeholder":"search","needs_inline_query_location":true,"has_main_web_app":true,"has_topic_sidebar":true,"supports_join_request_queries":true}` + + var info BotFullInfo + if err := json.Unmarshal([]byte(src), &info); err != nil { + t.Fatal(err) + } + if info.ID != 42 || !info.IsBot || info.FirstName != "Bot" || info.Username != "foo" { + t.Fatalf("%+v", info) + } + if len(info.ActiveUsernames) != 2 || info.ActiveUsernames[0] != "foo" || info.ActiveUsernames[1] != "foo_bot" { + t.Fatalf("usernames %+v", info.ActiveUsernames) + } + if !info.SupportsInlineQueries || info.InlineQueryPlaceholder != "search" || !info.HasTopicSidebar { + t.Fatalf("%+v", info) + } + if !info.NeedsInlineQueryLocation || !info.HasMainWebApp || !info.SupportsJoinRequestQueries { + t.Fatalf("%+v", info) + } + + var user User + if err := json.Unmarshal([]byte(src), &user); err != nil { + t.Fatal(err) + } + if user.ID != 42 || user.FirstName != "Bot" || user.Username != "foo" || !user.IsBot { + t.Fatalf("%+v", user) + } +} + +func TestBotFullInfo_MarshalRequiredFalse(t *testing.T) { + out, err := json.Marshal(BotFullInfo{ID: 1, IsBot: true, FirstName: "Bot"}) + if err != nil { + t.Fatal(err) + } + got := string(out) + if !strings.Contains(got, `"can_join_groups":false`) { + t.Fatalf("required false dropped: %s", got) + } + for _, optional := range []string{`"username"`, `"active_usernames"`, `"inline_query_placeholder"`} { + if strings.Contains(got, optional) { + t.Fatalf("optional %s present in %s", optional, got) + } + } +} + +func TestBotFullInfo_SupportsJoinRequestQueries(t *testing.T) { tests := []struct { name string src string @@ -25,19 +70,18 @@ func TestUser_SupportsJoinRequestQueries(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var u User - if err := json.Unmarshal([]byte(tt.src), &u); err != nil { + var info BotFullInfo + if err := json.Unmarshal([]byte(tt.src), &info); err != nil { t.Fatalf("unmarshal: %v", err) } - if u.SupportsJoinRequestQueries != tt.want { - t.Fatalf("supports_join_request_queries = %v, want %v", u.SupportsJoinRequestQueries, tt.want) + if info.SupportsJoinRequestQueries != tt.want { + t.Fatalf("supports_join_request_queries = %v, want %v", info.SupportsJoinRequestQueries, tt.want) } }) } } -// TestUser_SupportInlineQueries verifies supports_inline_queries decodes when present and stays false when absent. -func TestUser_SupportInlineQueries(t *testing.T) { +func TestBotFullInfo_SupportsInlineQueries(t *testing.T) { tests := []struct { name string src string @@ -56,12 +100,12 @@ func TestUser_SupportInlineQueries(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var u User - if err := json.Unmarshal([]byte(tt.src), &u); err != nil { + var info BotFullInfo + if err := json.Unmarshal([]byte(tt.src), &info); err != nil { t.Fatalf("unmarshal: %v", err) } - if u.SupportInlineQueries != tt.want { - t.Fatalf("supports_inline_queries = %v, want %v", u.SupportInlineQueries, tt.want) + if info.SupportsInlineQueries != tt.want { + t.Fatalf("supports_inline_queries = %v, want %v", info.SupportsInlineQueries, tt.want) } }) }