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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", opts...)
- `WithDebugHandler(handler DebugHandler)` - add debug handler
- `WithHTTPClient(pollTimeout time.Duration, client HttpClient)` - set custom http client
- `WithServerURL(serverURL string)` - set server url
- `WithSkipGetMe()` - skip call GetMe on bot init
- `WithSkipGetMe()` - skip call GetMe on bot init. A command handler for a bare command such as `start` then matches `/start@bot_username` only after `GetMe` succeeds.
- `WithAllowedUpdates(params AllowedUpdates)` - set [allowed_updates](https://core.telegram.org/bots/api#getupdates) for getUpdates method
- `WithUpdatesChannelCap(cap int)` - set updates channel capacity, by default 1024
- `WithWebhookSecretToken(webhookSecretToken string)` - set X-Telegram-Bot-Api-Secret-Token header sent from telegram servers to confirm validity of update
Expand Down
34 changes: 33 additions & 1 deletion bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ type MatchFunc func(update *models.Update) bool
type Bot struct {
lastUpdateID int64

// usernameMx guards username, the username 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

url string
token string
pollTimeout time.Duration
Expand Down Expand Up @@ -117,9 +124,34 @@ func (b *Bot) ID() int64 {
return i
}

// SetToken sets the bot token
// 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.
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 = ""
}
}

// 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) {
b.usernameMx.Lock()
defer b.usernameMx.Unlock()
if me.ID == b.ID() {
b.username = me.Username
}
}

func (b *Bot) botUsername() string {
b.usernameMx.RLock()
defer b.usernameMx.RUnlock()
return b.username
}

// Token returns the bot token
Expand Down
143 changes: 143 additions & 0 deletions bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package bot
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -412,3 +414,144 @@ func TestBot_SetToken(t *testing.T) {
t.Errorf("SetToken() = %s, want %s", b.token, "123456:xxx")
}
}

func getMeClient(t *testing.T, username string) HttpClient {
return getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) {
if !strings.HasSuffix(req.URL.Path, "/getMe") {
t.Errorf("unexpected request %s", req.URL.Path)
}
return getUpdatesJSONResponse(`{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"bot","username":"` + username + `"}}`), nil
})
}

func addressedCommandUpdate(text string) *models.Update {
return &models.Update{Message: &models.Message{
Text: text,
Entities: []models.MessageEntity{{Type: models.MessageEntityTypeBotCommand, Offset: 0, Length: len(text)}},
}}
}

func TestBot_ProcessUpdateMatchesCommandAddressedToBot(t *testing.T) {
var handled []string
b, err := New("1:token", WithHTTPClient(time.Second, getMeClient(t, "my_bot")), WithNotAsyncHandlers(),
WithDefaultHandler(func(_ context.Context, _ *Bot, update *models.Update) {
handled = append(handled, "default "+update.Message.Text)
}))
if err != nil {
t.Fatal(err)
}
b.RegisterHandler(HandlerTypeMessageText, "start", MatchTypeCommandStartOnly, func(_ context.Context, _ *Bot, update *models.Update) {
handled = append(handled, "start "+update.Message.Text)
})

b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@my_bot"))
b.ProcessUpdate(context.Background(), addressedCommandUpdate("/start@other_bot"))

want := []string{"start /start@my_bot", "default /start@other_bot"}
if !reflect.DeepEqual(handled, want) {
t.Errorf("handled %q, want %q", handled, want)
}
}

func TestBot_SetTokenForgetsUsernameOfAnotherBot(t *testing.T) {
b, err := New("1:token", WithHTTPClient(time.Second, getMeClient(t, "my_bot")))
if err != nil {
t.Fatal(err)
}
b.SetToken("1:revoked-and-replaced")
if got := b.botUsername(); got != "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 != "" {
t.Errorf("username after switching to another bot = %q, want empty", got)
}
}

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
// before the reply arrives, so the reply describes another bot.
b, err := New("1:token", WithSkipGetMe(), WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) {
b.SetToken("1:token")
return getUpdatesJSONResponse(`{"ok":true,"result":{"id":2,"is_bot":true,"first_name":"bot","username":"other_bot"}}`), nil
})))
if err != nil {
t.Fatal(err)
}
b.SetToken("2:token")
if _, err := b.GetMe(context.Background()); err != nil {
t.Fatal(err)
}
if got := b.botUsername(); got != "" {
t.Errorf("username = %q, want empty for a GetMe answered by another bot", got)
}
}

func TestBot_GetMeFailureKeepsUsername(t *testing.T) {
fail := false
b, err := New("1:token", WithHTTPClient(time.Second, getUpdatesClientFunc(func(req *http.Request) (*http.Response, error) {
if fail {
return nil, errors.New("network down")
}
return getUpdatesJSONResponse(`{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"bot","username":"my_bot"}}`), nil
})))
if err != nil {
t.Fatal(err)
}
fail = true
if _, err := b.GetMe(context.Background()); err == nil {
t.Fatal("GetMe succeeded, want an error")
}
if got := b.botUsername(); got != "my_bot" {
t.Errorf("username after a failed GetMe = %q, want my_bot", got)
}
}

func TestBot_GetMeDecodeErrorRecordsNoUsername(t *testing.T) {
b, err := New("1:token", WithSkipGetMe(), WithHTTPClient(time.Second, getUpdatesClientFunc(func(*http.Request) (*http.Response, error) {
// The id and username decode even though is_bot fails.
return getUpdatesJSONResponse(`{"ok":true,"result":{"id":1,"username":"my_bot","is_bot":"yes"}}`), nil
})))
if err != nil {
t.Fatal(err)
}
if _, err := b.GetMe(context.Background()); err == nil {
t.Fatal("GetMe succeeded, want a decode error")
}
if got := b.botUsername(); got != "" {
t.Errorf("username = %q, want empty after a failed GetMe", got)
}
}

// Run with -race: the username is read while it is set and while the token
// changes.
func TestBot_UsernameConcurrentAccess(t *testing.T) {
b := &Bot{token: "1:token"}
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(3)
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
b.setUsername(&models.User{ID: 1, Username: "my_bot"})
}
}()
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
b.SetToken("2:token")
b.SetToken("1:token")
}
}()
go func() {
defer wg.Done()
for j := 0; j < 100; j++ {
if got := b.botUsername(); got != "" && got != "my_bot" {
t.Errorf("username = %q", got)
}
}
}()
}
wg.Wait()
}
30 changes: 23 additions & 7 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ type handler struct {
matchFunc MatchFunc
}

func (h handler) match(update *models.Update) bool {
// 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 {
if h.matchType == matchTypeFunc {
return h.matchFunc(update)
}
Expand All @@ -61,9 +63,9 @@ func (h handler) match(update *models.Update) bool {
case MatchTypeContains:
return h.matchContains(data)
case MatchTypeCommand:
return h.matchCommand(data, entities)
return h.matchCommand(data, entities, botUsername)
case MatchTypeCommandStartOnly:
return h.matchCommandStartOnly(data, entities)
return h.matchCommandStartOnly(data, entities, botUsername)
case matchTypeRegexp:
return h.matchRegexp(data)
default:
Expand Down Expand Up @@ -139,30 +141,44 @@ func extractCommand(data string, entity models.MessageEntity) (string, bool) {
return data[entity.Offset+1 : entity.Offset+entity.Length], true
}

func (h handler) matchCommand(data string, entities []models.MessageEntity) bool {
func (h handler) matchCommand(data string, entities []models.MessageEntity, botUsername string) bool {
for _, e := range entities {
if e.Type == models.MessageEntityTypeBotCommand {
command, ok := extractCommand(data, e)
if ok && command == h.pattern {
if ok && h.isCommand(command, botUsername) {
return true
}
}
}
return false
}

func (h handler) matchCommandStartOnly(data string, entities []models.MessageEntity) bool {
func (h handler) matchCommandStartOnly(data string, entities []models.MessageEntity, botUsername string) bool {
for _, e := range entities {
if e.Type == models.MessageEntityTypeBotCommand && e.Offset == 0 {
command, ok := extractCommand(data, e)
if ok && command == h.pattern {
if ok && h.isCommand(command, botUsername) {
return true
}
}
}
return false
}

// 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 {
if command == h.pattern {
return true
}
if h.pattern == "" || botUsername == "" {
return false
}
name, target, addressed := strings.Cut(command, "@")
return addressed && name == h.pattern && strings.EqualFold(target, botUsername)
}

func (b *Bot) RegisterHandlerMatchFunc(matchFunc MatchFunc, f HandlerFunc, m ...Middleware) string {
b.handlersMx.Lock()
defer b.handlersMx.Unlock()
Expand Down
Loading
Loading