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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
2 changes: 1 addition & 1 deletion bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
4 changes: 4 additions & 0 deletions build_request_form.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 8 additions & 1 deletion build_request_form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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",
)
}

Expand All @@ -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,
Expand Down
6 changes: 5 additions & 1 deletion examples/inline_keyboard/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
}
Expand Down
15 changes: 10 additions & 5 deletions examples/inline_keyboard_multiselect/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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(),
})
}
Expand Down
30 changes: 23 additions & 7 deletions examples/middleware/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)
}
}

Expand Down
15 changes: 11 additions & 4 deletions methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions methods_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
64 changes: 63 additions & 1 deletion methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,20 @@ type httpClient struct {
reqFiles map[string]string // multipart file parts by name, with expected content
absent []string
present []string
emptyBody bool
t *testing.T
}

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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<b>&amp;</b> \"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)
}
})
}
5 changes: 5 additions & 0 deletions models/callback_query.go
Original file line number Diff line number Diff line change
@@ -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"`
Expand Down
3 changes: 3 additions & 0 deletions models/forum.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
6 changes: 3 additions & 3 deletions models/input_rich_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading