Skip to content

Commit

Permalink
Added not predicate & fixed command regexp
Browse files Browse the repository at this point in the history
  • Loading branch information
mymmrac committed Dec 27, 2021
1 parent 060b6d3 commit 9cc96a9
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
21 changes: 20 additions & 1 deletion internal/test/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var (
userUsername = tu.Username("@mymmrac")
)

const testCase = 16
const testCase = 17

func main() {
testToken := os.Getenv("TOKEN")
Expand Down Expand Up @@ -336,6 +336,25 @@ func main() {
return update.Message != nil && count > 1
})

bh.Start()
case 17:
updates, _ := bot.GetUpdatesViaLongPulling(nil)
defer bot.StopLongPulling()

bh := th.NewBotHandler(bot, updates)
defer bh.Stop()

bh.Handle(func(bot *telego.Bot, update telego.Update) {
msg := update.Message
matches := th.CommandRegexp.FindStringSubmatch(msg.Text)
_, _ = bot.SendMessage(tu.Message(tu.ID(msg.Chat.ID), fmt.Sprintf("%#v", matches)))
}, th.HasCommand())

bh.Handle(func(bot *telego.Bot, update telego.Update) {
msg := update.Message
_, _ = bot.SendMessage(tu.Message(tu.ID(msg.Chat.ID), fmt.Sprintf("Whaaat? %s", msg.Text)))
}, th.HasMassage(), th.Not(th.HasCommand()))

bh.Start()
}
}
Expand Down
9 changes: 8 additions & 1 deletion telegohandler/pradicates.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ func Union(predicates ...Predicate) Predicate {
}
}

// Not is true if predicate is false
func Not(predicate Predicate) Predicate {
return func(update telego.Update) bool {
return !predicate(update)
}
}

// HasMassage is true if message isn't nil
func HasMassage() Predicate {
return func(update telego.Update) bool {
Expand All @@ -27,7 +34,7 @@ func HasMassage() Predicate {
}

// CommandRegexp matches to command and has match groups on command and arguments
var CommandRegexp = regexp.MustCompile(`/(\w+) ?(.*)`)
var CommandRegexp = regexp.MustCompile(`^/(\w+) ?(.*)$`)

// HasCommand is true if message isn't nil, and it matches to command regexp
func HasCommand() Predicate {
Expand Down
12 changes: 12 additions & 0 deletions telegohandler/pradicates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ func TestPredicates(t *testing.T) {
update: telego.Update{},
matches: false,
},
{
name: "not_matches",
predicate: Not(func(update telego.Update) bool { return false }),
update: telego.Update{},
matches: true,
},
{
name: "not_not_matches",
predicate: Not(func(update telego.Update) bool { return true }),
update: telego.Update{},
matches: false,
},
{
name: "has_massage_matches",
predicate: HasMassage(),
Expand Down

0 comments on commit 9cc96a9

Please sign in to comment.