Skip to content
Closed
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
11 changes: 10 additions & 1 deletion bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type Bot struct {

url string
token string
username string
pollTimeout time.Duration
skipGetMe bool
webhookSecretToken string
Expand Down Expand Up @@ -92,10 +93,11 @@ func New(token string, options ...Option) (*Bot, error) {
defer cancel()

if !b.skipGetMe {
_, err := b.GetMe(ctx)
botInfo, err := b.GetMe(ctx)
if err != nil {
return nil, fmt.Errorf("error call getMe, %w", err)
}
b.username = botInfo.Username
}

return b, nil
Expand All @@ -121,6 +123,13 @@ func (b *Bot) Token() string {
return b.token
}

// Username returns the bot username without `@` prefix
//
// Return empty string if bot with the `bot.WithSkipGetMe()` option
func (b *Bot) Username() string {
return b.username
}

// StartWebhook starts the Bot with webhook mode
func (b *Bot) StartWebhook(ctx context.Context) {
wg := sync.WaitGroup{}
Expand Down
10 changes: 10 additions & 0 deletions bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,3 +396,13 @@ func TestBot_SetToken(t *testing.T) {
t.Errorf("SetToken() = %s, want %s", b.token, "123456:xxx")
}
}

func TestBot_Username(t *testing.T) {
b := &Bot{username: "example_bot"}

username := b.Username()

if username != "example_bot" {
t.Errorf("Username() = %s, want %s", username, "example_bot")
}
}
12 changes: 12 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const (
MatchTypeContains
MatchTypeCommand
MatchTypeCommandStartOnly
MatchTypeCommandStartMaybeWithBotUsernameSuffix // example `/command@example_bot`, can't match username suffix if bot with the `bot.WithSkipGetMe()` option

matchTypeRegexp
matchTypeFunc
Expand All @@ -36,6 +37,7 @@ type handler struct {
handler HandlerFunc

pattern string
username string
re *regexp.Regexp
matchFunc MatchFunc
}
Expand Down Expand Up @@ -100,6 +102,15 @@ func (h handler) match(update *models.Update) bool {
}
}
}
if h.matchType == MatchTypeCommandStartMaybeWithBotUsernameSuffix {
for _, e := range entities {
if e.Type == models.MessageEntityTypeBotCommand {
if e.Offset == 0 && (data[e.Offset+1:e.Offset+e.Length] == h.pattern || data[e.Offset+1:e.Offset+e.Length] == h.pattern+"@"+h.username) {
return true
}
}
}
}
if h.matchType == matchTypeRegexp {
return h.re.Match([]byte(data))
}
Expand Down Expand Up @@ -154,6 +165,7 @@ func (b *Bot) RegisterHandler(handlerType HandlerType, pattern string, matchType
handlerType: handlerType,
matchType: matchType,
pattern: pattern,
username: b.username,
handler: applyMiddlewares(f, m...),
}

Expand Down
Loading
Loading