diff --git a/CHANGELOG.md b/CHANGELOG.md index 2941785..36eaf71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,10 +3,10 @@ ## Unreleased - Command handlers also recognize commands addressed to any active username returned by `GetMe`. -- 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. +- Breaking: `GetMe` now returns `*models.BotFullInfo` instead of `*models.User`. Call the deprecated `GetMeLegacy` if you still need `*models.User`. +- Breaking: Expandable block quotations now use `Blocks`. The deprecated `Text` field is not populated when decoding. Sending `Text` without any blocks returns `Text is deprecated; use Blocks`; when blocks are present, `Text` is ignored. Nested files inside `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. +- Bot settings now come from `BotFullInfo`. The nine previous bot setting fields on `User` are deprecated but still populated by `GetMeLegacy`. - 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. diff --git a/bot_test.go b/bot_test.go index 98ec350..0ad3e4d 100644 --- a/bot_test.go +++ b/bot_test.go @@ -479,6 +479,89 @@ func TestBot_SetTokenForgetsUsernameOfAnotherBot(t *testing.T) { } } +func TestBot_GetMeLegacy(t *testing.T) { + const wantJSON = `{"id":1,"is_bot":true,"first_name":"Bot","username":"my_bot"}` + calls := 0 + client := getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if req.URL.Path != "/bot1:token/getMe" { + t.Errorf("request path = %s, want /bot1:token/getMe", req.URL.Path) + } + return getUpdatesJSONResponse(`{"ok":true,"result":` + strings.TrimSuffix(wantJSON, "}") + `,"active_usernames":["alias_bot"]}}`), nil + }) + b, err := New("1:token", WithSkipGetMe(), WithHTTPClient(time.Second, client), WithNotAsyncHandlers()) + if err != nil { + t.Fatal(err) + } + handled := false + b.RegisterHandler(HandlerTypeMessageText, "start", MatchTypeCommand, func(context.Context, *Bot, *models.Update) { + handled = true + }) + + me, err := b.GetMeLegacy(context.Background()) + if err != nil { + t.Fatal(err) + } + got, err := json.Marshal(me) + if err != nil { + t.Fatal(err) + } + if string(got) != wantJSON { + t.Errorf("legacy user = %s, want %s", got, wantJSON) + } + if calls != 1 { + t.Errorf("getMe requests = %d, want 1", calls) + } + b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@Alias_Bot")) + if !handled { + t.Error("command was not routed to the handler using an active username") + } +} + +func TestBot_GetMeLegacyIndependentFlags(t *testing.T) { + for _, flag := range []string{ + "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_join_request_queries", "supports_guest_queries", + } { + t.Run(flag, func(t *testing.T) { + b := &Bot{client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { + return getUpdatesJSONResponse(`{"ok":true,"result":{"id":1,"is_bot":true,"` + flag + `":true}}`), nil + })} + user, err := b.GetMeLegacy(context.Background()) + if err != nil { + t.Fatal(err) + } + data, err := json.Marshal(user) + if err != nil { + t.Fatal(err) + } + var got map[string]json.RawMessage + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + delete(got, "id") + delete(got, "is_bot") + if len(got) != 1 || string(got[flag]) != "true" { + t.Errorf("legacy user = %s, want only %s among optional fields", data, flag) + } + }) + } +} + +func TestBot_GetMeLegacyPreservesError(t *testing.T) { + b := &Bot{client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { + return getUpdatesJSONResponse(`{"ok":false,"error_code":401,"description":"Unauthorized"}`), nil + })} + me, err := b.GetMeLegacy(context.Background()) + if !errors.Is(err, ErrorUnauthorized) { + t.Errorf("error = %v, want ErrorUnauthorized", err) + } + if me == nil || *me != (models.User{}) { + t.Errorf("legacy user on failure = %+v, want a zero user", me) + } +} + func TestBot_GetMeIgnoresUsernameOfAnotherBot(t *testing.T) { var b *Bot // GetMe is sent with bot 2's token, and the token is switched back to bot 1 diff --git a/docs/plans/2026-11-26-getme-legacy.md b/docs/plans/2026-11-26-getme-legacy.md new file mode 100644 index 0000000..fe6b79c --- /dev/null +++ b/docs/plans/2026-11-26-getme-legacy.md @@ -0,0 +1,24 @@ +# План: `GetMeLegacy` и миграция на `Blocks` + +`GetMe` остаётся основным методом и возвращает `*models.BotFullInfo`. +Номер версии пока не выбираем; тег и путь модуля не меняем. + +1. **Подготовить рабочее место.** Создать отдельный worktree + `.worktrees/getme-legacy` с веткой `feat/getme-legacy` от текущего HEAD + и сохранить этот план в `docs/plans/` до изменения кода. +2. **Добавить `GetMeLegacy`.** Метод возвращает `(*models.User, error)` и + помечен `Deprecated: Use GetMe.` Он вызывает `GetMe` один раз, сохраняя + обработку ошибок и обновление активных имён бота. Вернуть в `User` + девять прежних полей с исходными именами и JSON-тегами, включая + `SupportInlineQueries`; пометить их устаревшими и заполнять из `BotFullInfo`. +3. **Защитить отправку цитат.** Вернуть `Text RichText` в обе модели + раскрывающейся цитаты с пометкой `Deprecated: Use Blocks.` При чтении + библиотека не заполняет `Text`. При отправке, если `Text` отличается от + нулевого значения, а `Blocks` пуст, вернуть ошибку + `Text is deprecated; use Blocks` вместо молчаливой потери содержимого. + Если блоки есть, отправлять только `Blocks`, игнорируя `Text`. + Описать это в changelog. +4. **Проверить миграцию.** Проверить прежние значения полей `User`, один + запрос и маршрутизацию по алиасам. Для цитат подтвердить ошибку при + отправке только `Text`, приоритет `Blocks` при наличии обоих полей и + пустой `Text` при чтении. Запустить `go test -race ./...` и `go vet ./...`. diff --git a/methods.go b/methods.go index f573447..9fa0854 100644 --- a/methods.go +++ b/methods.go @@ -42,6 +42,28 @@ func (b *Bot) GetMe(ctx context.Context) (*models.BotFullInfo, error) { return result, err } +// GetMeLegacy returns the result of GetMe in the previous User format. +// +// Deprecated: Use GetMe. +func (b *Bot) GetMeLegacy(ctx context.Context) (*models.User, error) { + me, err := b.GetMe(ctx) + return &models.User{ + ID: me.ID, + IsBot: me.IsBot, + FirstName: me.FirstName, + Username: me.Username, + CanJoinGroups: me.CanJoinGroups, + CanReadAllGroupMessages: me.CanReadAllGroupMessages, + SupportInlineQueries: me.SupportsInlineQueries, + CanConnectToBusiness: me.CanConnectToBusiness, + HasTopicsEnabled: me.HasTopicsEnabled, + AllowsUsersToCreateTopics: me.AllowsUsersToCreateTopics, + CanManageBots: me.CanManageBots, + SupportsJoinRequestQueries: me.SupportsJoinRequestQueries, + SupportsGuestQueries: me.SupportsGuestQueries, + }, err +} + // Logout https://core.telegram.org/bots/api#logout func (b *Bot) Logout(ctx context.Context) (bool, error) { var result bool diff --git a/methods_test.go b/methods_test.go index 938a488..89f0aff 100644 --- a/methods_test.go +++ b/methods_test.go @@ -1527,6 +1527,25 @@ func TestBot_RichMessageMethods(t *testing.T) { assertTrue(t, resp) }) + t.Run("SendRichMessageRejectsLegacyExpandableQuoteText", func(t *testing.T) { + b := &Bot{client: getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { + t.Fatal("request made with legacy quotation text") + return nil, nil + })} + _, err := b.SendRichMessage(context.Background(), &SendRichMessageParams{ + ChatID: 123, + RichMessage: models.InputRichMessage{Blocks: []models.InputRichBlock{{ + Type: models.RichBlockTypeExpandableBlockQuotation, + InputRichBlockExpandableBlockQuotation: &models.InputRichBlockExpandableBlockQuotation{ + Text: models.RichText{PlainText: "legacy quotation"}, + }, + }}}, + }) + if err == nil || !strings.Contains(err.Error(), "Text is deprecated; use Blocks") { + t.Fatalf("got %v, want deprecated Text error", err) + } + }) + t.Run("SendRichMessageWithAttachment", func(t *testing.T) { c := &httpClient{ t: t, diff --git a/models/input_rich_block.go b/models/input_rich_block.go index cd5eb47..be04d9d 100644 --- a/models/input_rich_block.go +++ b/models/input_rich_block.go @@ -278,6 +278,18 @@ type InputRichBlockExpandableBlockQuotation struct { Type RichBlockType `json:"type"` // always "expandable_blockquote" Blocks []InputRichBlock `json:"blocks"` Credit *RichText `json:"credit,omitempty"` + + // Deprecated: Use Blocks. Text is not decoded or sent. + Text RichText `json:"-"` +} + +// MarshalJSON implements json.Marshaler. +func (q InputRichBlockExpandableBlockQuotation) MarshalJSON() ([]byte, error) { + if err := checkExpandableBlockQuotationText(q.Text, len(q.Blocks)); err != nil { + return nil, err + } + type wire InputRichBlockExpandableBlockQuotation + return json.Marshal(wire(q)) } // InputRichBlockPullQuotation https://core.telegram.org/bots/api#inputrichblockpullquotation diff --git a/models/rich_block.go b/models/rich_block.go index 32bf9b5..117a57f 100644 --- a/models/rich_block.go +++ b/models/rich_block.go @@ -2,6 +2,8 @@ package models import ( "encoding/json" + "errors" + "reflect" ) // RichBlockType https://core.telegram.org/bots/api#richblock @@ -277,6 +279,25 @@ type RichBlockExpandableBlockQuotation struct { Type RichBlockType `json:"type"` Blocks []RichBlock `json:"blocks"` Credit *RichText `json:"credit,omitempty"` + + // Deprecated: Use Blocks. Text is not decoded from JSON. + Text RichText `json:"-"` +} + +// MarshalJSON implements json.Marshaler. +func (q RichBlockExpandableBlockQuotation) MarshalJSON() ([]byte, error) { + if err := checkExpandableBlockQuotationText(q.Text, len(q.Blocks)); err != nil { + return nil, err + } + type wire RichBlockExpandableBlockQuotation + return json.Marshal(wire(q)) +} + +func checkExpandableBlockQuotationText(text RichText, blockCount int) error { + if blockCount == 0 && !reflect.ValueOf(text).IsZero() { + return errors.New("Text is deprecated; use Blocks") + } + return nil } // RichBlockPullQuotation https://core.telegram.org/bots/api#richblockpullquotation diff --git a/models/rich_block_test.go b/models/rich_block_test.go index d476c37..63946a6 100644 --- a/models/rich_block_test.go +++ b/models/rich_block_test.go @@ -2,10 +2,52 @@ package models import ( "encoding/json" + "reflect" "strings" "testing" ) +func TestExpandableBlockQuotationLegacyText(t *testing.T) { + const wire = `{"type":"expandable_blockquote","blocks":[{"type":"paragraph","text":"new"}]}` + const legacyWire = `{"type":"expandable_blockquote","blocks":[{"type":"paragraph","text":"new"}],"text":"old"}` + var received RichBlock + var input InputRichBlock + if err := json.Unmarshal([]byte(legacyWire), &received); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(legacyWire), &input); err != nil { + t.Fatal(err) + } + q := received.RichBlockExpandableBlockQuotation + iq := input.InputRichBlockExpandableBlockQuotation + if q == nil || iq == nil { + t.Fatal("expandable quotation not decoded") + } + if !reflect.ValueOf(q.Text).IsZero() || !reflect.ValueOf(iq.Text).IsZero() { + t.Fatal("deprecated Text was decoded") + } + // A nonzero array value also counts as legacy Text, even when empty. + q.Text = RichText{Array: []RichText{}} + iq.Text = RichText{PlainText: "old"} + for _, block := range []any{received, input} { + got, err := json.Marshal(block) + if err != nil { + t.Fatal(err) + } + if string(got) != wire { + t.Errorf("%T: got %s, want %s", block, got, wire) + } + } + + q.Blocks = nil + iq.Blocks = []InputRichBlock{} + for _, block := range []any{received, input} { + if _, err := json.Marshal(block); err == nil || !strings.Contains(err.Error(), "Text is deprecated; use Blocks") { + t.Errorf("%T: got %v, want deprecated Text error", block, err) + } + } +} + func richBlockRoundTrip(t *testing.T, src string) RichBlock { t.Helper() diff --git a/models/user.go b/models/user.go index af35c6f..929f62f 100644 --- a/models/user.go +++ b/models/user.go @@ -16,6 +16,25 @@ type User struct { LanguageCode string `json:"language_code,omitempty"` IsPremium bool `json:"is_premium,omitempty"` AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"` + + // Deprecated: Use BotFullInfo.CanJoinGroups. + CanJoinGroups bool `json:"can_join_groups,omitempty"` + // Deprecated: Use BotFullInfo.CanReadAllGroupMessages. + CanReadAllGroupMessages bool `json:"can_read_all_group_messages,omitempty"` + // Deprecated: Use BotFullInfo.SupportsInlineQueries. + SupportInlineQueries bool `json:"supports_inline_queries,omitempty"` + // Deprecated: Use BotFullInfo.CanConnectToBusiness. + CanConnectToBusiness bool `json:"can_connect_to_business,omitempty"` + // Deprecated: Use BotFullInfo.HasTopicsEnabled. + HasTopicsEnabled bool `json:"has_topics_enabled,omitempty"` + // Deprecated: Use BotFullInfo.AllowsUsersToCreateTopics. + AllowsUsersToCreateTopics bool `json:"allows_users_to_create_topics,omitempty"` + // Deprecated: Use BotFullInfo.CanManageBots. + CanManageBots bool `json:"can_manage_bots,omitempty"` + // Deprecated: Use BotFullInfo.SupportsJoinRequestQueries. + SupportsJoinRequestQueries bool `json:"supports_join_request_queries,omitempty"` + // Deprecated: Use BotFullInfo.SupportsGuestQueries. + SupportsGuestQueries bool `json:"supports_guest_queries,omitempty"` } // BotFullInfo https://core.telegram.org/bots/api#botfullinfo