diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dba267..2941785 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## 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. - `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. diff --git a/bot.go b/bot.go index 7ca6b0c..09afd91 100644 --- a/bot.go +++ b/bot.go @@ -36,12 +36,12 @@ type MatchFunc func(update *models.Update) bool type Bot struct { lastUpdateID int64 - // usernameMx guards username, the username from the last successful GetMe + // usernameMx guards usernames, an immutable snapshot from the last successful GetMe // call for the bot the token belongs to. SetToken holds it while changing the // token, so checking the bot ID and clearing the username happen together; // other code still reads the token without it. usernameMx sync.RWMutex - username string + usernames []string url string token string @@ -127,33 +127,34 @@ func (b *Bot) ID() int64 { } // SetToken sets the bot token. If the token belongs to a different bot, by its -// ID prefix, the username recorded by GetMe is cleared until GetMe succeeds -// again. A new token for the same bot, as after revoking the old one, keeps it. +// ID prefix, the usernames recorded by GetMe are cleared until GetMe succeeds +// again. A new token for the same bot, as after revoking the old one, keeps them. func (b *Bot) SetToken(token string) { b.usernameMx.Lock() defer b.usernameMx.Unlock() previousID := b.ID() b.token = token if b.ID() != previousID { - b.username = "" + b.usernames = nil } } -// setUsername records the username GetMe returned, unless the token now +// setUsernames records the usernames 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 id. -func (b *Bot) setUsername(id int64, username string) { +func (b *Bot) setUsernames(me *models.BotFullInfo) { b.usernameMx.Lock() defer b.usernameMx.Unlock() - if id == b.ID() { - b.username = username + if me.ID == b.ID() { + // GetMe returns me to the caller; don't share its mutable slice. + b.usernames = append([]string{me.Username}, me.ActiveUsernames...) } } -func (b *Bot) botUsername() string { +func (b *Bot) botUsernames() []string { b.usernameMx.RLock() defer b.usernameMx.RUnlock() - return b.username + return b.usernames } // Token returns the bot token diff --git a/bot_test.go b/bot_test.go index a8bbb97..98ec350 100644 --- a/bot_test.go +++ b/bot_test.go @@ -433,7 +433,10 @@ func addressedCommandUpdate(text string) *models.Update { func TestBot_ProcessUpdateMatchesCommandAddressedToBot(t *testing.T) { var handled []string - b, err := New("1:token", WithHTTPClient(time.Second, getMeClient(t, "my_bot")), WithNotAsyncHandlers(), + client := getUpdatesClientFunc(func(*http.Request) (*http.Response, error) { + return getUpdatesJSONResponse(`{"ok":true,"result":{"id":1,"username":"my_bot","active_usernames":["alias_bot"]}}`), nil + }) + b, err := New("1:token", WithSkipGetMe(), WithHTTPClient(time.Second, client), WithNotAsyncHandlers(), WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) { handled = append(handled, "default "+update.Message.Text) })) @@ -444,10 +447,18 @@ func TestBot_ProcessUpdateMatchesCommandAddressedToBot(t *testing.T) { handled = append(handled, "start "+update.Message.Text) }) + me, err := b.GetMe(context.Background()) + if err != nil { + t.Fatal(err) + } + me.ActiveUsernames[0] = "other_bot" // The caller must not change routing by mutating the result. b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@my_bot")) + b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@ALIAS_bot")) b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@other_bot")) + b.SetToken("2:new_bot") + b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@ALIAS_bot")) - want := []string{"start /start@my_bot", "default /start@other_bot"} + want := []string{"start /start@my_bot", "start /start@ALIAS_bot", "default /start@other_bot", "default /start@ALIAS_bot"} if !reflect.DeepEqual(handled, want) { t.Errorf("handled %q, want %q", handled, want) } @@ -459,11 +470,11 @@ func TestBot_SetTokenForgetsUsernameOfAnotherBot(t *testing.T) { t.Fatal(err) } b.SetToken("1:revoked-and-replaced") - if got := b.botUsername(); got != "my_bot" { + if got := b.botUsernames(); !reflect.DeepEqual(got, []string{"my_bot"}) { t.Errorf("username after a new token of the same bot = %q, want my_bot", got) } b.SetToken("2:token") - if got := b.botUsername(); got != "" { + if got := b.botUsernames(); len(got) != 0 { t.Errorf("username after switching to another bot = %q, want empty", got) } } @@ -483,7 +494,7 @@ func TestBot_GetMeIgnoresUsernameOfAnotherBot(t *testing.T) { if _, err := b.GetMe(context.Background()); err != nil { t.Fatal(err) } - if got := b.botUsername(); got != "" { + if got := b.botUsernames(); len(got) != 0 { t.Errorf("username = %q, want empty for a GetMe answered by another bot", got) } } @@ -503,7 +514,7 @@ func TestBot_GetMeFailureKeepsUsername(t *testing.T) { if _, err := b.GetMe(context.Background()); err == nil { t.Fatal("GetMe succeeded, want an error") } - if got := b.botUsername(); got != "my_bot" { + if got := b.botUsernames(); !reflect.DeepEqual(got, []string{"my_bot"}) { t.Errorf("username after a failed GetMe = %q, want my_bot", got) } } @@ -519,7 +530,7 @@ func TestBot_GetMeDecodeErrorRecordsNoUsername(t *testing.T) { if _, err := b.GetMe(context.Background()); err == nil { t.Fatal("GetMe succeeded, want a decode error") } - if got := b.botUsername(); got != "" { + if got := b.botUsernames(); len(got) != 0 { t.Errorf("username = %q, want empty after a failed GetMe", got) } } @@ -534,7 +545,7 @@ func TestBot_UsernameConcurrentAccess(t *testing.T) { go func() { defer wg.Done() for j := 0; j < 100; j++ { - b.setUsername(1, "my_bot") + b.setUsernames(&models.BotFullInfo{ID: 1, Username: "my_bot"}) } }() go func() { @@ -547,7 +558,7 @@ func TestBot_UsernameConcurrentAccess(t *testing.T) { go func() { defer wg.Done() for j := 0; j < 100; j++ { - if got := b.botUsername(); got != "" && got != "my_bot" { + if got := b.botUsernames(); len(got) != 0 && !reflect.DeepEqual(got, []string{"my_bot"}) { t.Errorf("username = %q", got) } } diff --git a/handlers.go b/handlers.go index 734a884..80aac47 100644 --- a/handlers.go +++ b/handlers.go @@ -30,7 +30,8 @@ const ( // MatchTypeCommand matches a bot command anywhere in a message text or // caption, so it works only with HandlerTypeMessageText and // HandlerTypePhotoCaption. Specify the command without the slash, such as - // "start". It also matches /start@bot_username once GetMe has succeeded. + // "start". After GetMe succeeds it also matches commands addressed to the + // bot's primary username or any of its active usernames. MatchTypeCommand // MatchTypeCommandStartOnly is like MatchTypeCommand, but the command must // be at the start of the text or caption. @@ -54,9 +55,8 @@ type handler struct { matchFunc MatchFunc // Custom function for function-based matching } -// match reports whether the handler accepts update. botUsername is the bot's -// username, or empty if unknown. -func (h handler) match(update *models.Update, botUsername string) bool { +// match reports whether the handler accepts update. +func (h handler) match(update *models.Update, usernames ...string) bool { if h.matchType == matchTypeFunc { return h.matchFunc(update) } @@ -74,9 +74,9 @@ func (h handler) match(update *models.Update, botUsername string) bool { case MatchTypeContains: return h.matchContains(data) case MatchTypeCommand: - return h.matchCommand(data, entities, botUsername) + return h.matchCommand(data, entities, usernames) case MatchTypeCommandStartOnly: - return h.matchCommandStartOnly(data, entities, botUsername) + return h.matchCommandStartOnly(data, entities, usernames) case matchTypeRegexp: return h.matchRegexp(data) default: @@ -178,11 +178,11 @@ func utf16Index(s string, n int) (int, bool) { return len(s), units == n } -func (h handler) matchCommand(data string, entities []models.MessageEntity, botUsername string) bool { +func (h handler) matchCommand(data string, entities []models.MessageEntity, usernames []string) bool { for _, e := range entities { if e.Type == models.MessageEntityTypeBotCommand { command, ok := extractCommand(data, e) - if ok && h.isCommand(command, botUsername) { + if ok && h.isCommand(command, usernames) { return true } } @@ -190,11 +190,11 @@ func (h handler) matchCommand(data string, entities []models.MessageEntity, botU return false } -func (h handler) matchCommandStartOnly(data string, entities []models.MessageEntity, botUsername string) bool { +func (h handler) matchCommandStartOnly(data string, entities []models.MessageEntity, usernames []string) bool { for _, e := range entities { if e.Type == models.MessageEntityTypeBotCommand && e.Offset == 0 { command, ok := extractCommand(data, e) - if ok && h.isCommand(command, botUsername) { + if ok && h.isCommand(command, usernames) { return true } } @@ -205,15 +205,20 @@ func (h handler) matchCommandStartOnly(data string, entities []models.MessageEnt // isCommand reports whether command, without its leading "/", is the handler's // command. In groups, clients address a command to a bot by appending its // username, as in /start@bot_username. Telegram usernames are case-insensitive. -func (h handler) isCommand(command, botUsername string) bool { +func (h handler) isCommand(command string, usernames []string) bool { if command == h.pattern { return true } - if h.pattern == "" || botUsername == "" { + name, target, addressed := strings.Cut(command, "@") + if !addressed || target == "" || h.pattern == "" || name != h.pattern { return false } - name, target, addressed := strings.Cut(command, "@") - return addressed && name == h.pattern && strings.EqualFold(target, botUsername) + for _, username := range usernames { + if strings.EqualFold(target, username) { + return true + } + } + return false } // RegisterHandlerMatchFunc registers f for updates accepted by matchFunc. diff --git a/handlers_test.go b/handlers_test.go index e90faf9..daf4290 100644 --- a/handlers_test.go +++ b/handlers_test.go @@ -1010,7 +1010,7 @@ func TestHandler_matchCommand(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := handler{pattern: tt.pattern} - result := h.matchCommand(tt.data, tt.entities, "") + result := h.matchCommand(tt.data, tt.entities, nil) if result != tt.wantMatch { t.Errorf("matchCommand() = %v, want %v", result, tt.wantMatch) } @@ -1077,7 +1077,7 @@ func TestHandler_matchCommandStartOnly(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := handler{pattern: tt.pattern} - result := h.matchCommandStartOnly(tt.data, tt.entities, "") + result := h.matchCommandStartOnly(tt.data, tt.entities, nil) if result != tt.wantMatch { t.Errorf("matchCommandStartOnly() = %v, want %v", result, tt.wantMatch) } diff --git a/methods.go b/methods.go index ce2c1c3..f573447 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 bot is the one the +// GetMe also records the bot's usernames 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.BotFullInfo, error) { result := &models.BotFullInfo{} err := b.rawRequest(ctx, "getMe", nil, result) if err == nil { - b.setUsername(result.ID, result.Username) + b.setUsernames(result) } return result, err } diff --git a/process_update.go b/process_update.go index d6c6396..869e0e4 100644 --- a/process_update.go +++ b/process_update.go @@ -37,9 +37,9 @@ func (b *Bot) findHandler(upd *models.Update) HandlerFunc { b.handlersMx.RLock() defer b.handlersMx.RUnlock() - username := b.botUsername() + usernames := b.botUsernames() for _, h := range b.handlers { - if h.match(upd, username) { + if h.match(upd, usernames...) { return h.handler } }