Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
83 changes: 83 additions & 0 deletions bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions docs/plans/2026-11-26-getme-legacy.md
Original file line number Diff line number Diff line change
@@ -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 ./...`.
22 changes: 22 additions & 0 deletions methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
12 changes: 12 additions & 0 deletions models/input_rich_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions models/rich_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package models

import (
"encoding/json"
"errors"
"reflect"
)

// RichBlockType https://core.telegram.org/bots/api#richblock
Expand Down Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions models/rich_block_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
19 changes: 19 additions & 0 deletions models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading