diff --git a/callbacks.go b/callbacks.go new file mode 100644 index 0000000..5c11100 --- /dev/null +++ b/callbacks.go @@ -0,0 +1,25 @@ +package nechotron + +import ( + "context" + "strings" +) + +type CallbackFilter func(u *Update) bool + +func CallbackExact(text string) CallbackFilter { + return func(u *Update) bool { + data := u.Callback() + return text == data + } +} + +func CallbackPrefix(text string) CallbackFilter { + return func(u *Update) bool { + data := u.Callback() + if strings.HasPrefix(data, text) { + u.Ctx = context.WithValue(u.Ctx, FilteredValue("cb_"+text), strings.TrimPrefix(data, text+":")) + } + return strings.HasPrefix(data, text) + } +} diff --git a/dispatcher.go b/dispatcher.go index 23d9444..c0b4dd9 100644 --- a/dispatcher.go +++ b/dispatcher.go @@ -54,13 +54,13 @@ func (d *Dispatcher) HandleFilter(filter FilterFn, handler UpdateHandler) *Dispa return d } -func (d *Dispatcher) HandleCallback(callback string, handler UpdateHandler) *Dispatcher { +func (d *Dispatcher) HandleCallback(filter CallbackFilter, handler UpdateHandler) *Dispatcher { newHandler := func(u *Update) (bool, error) { if !u.IsCallback() { return false, nil } defer u.Bot.AnswerCallbackQuery(u.CallbackQuery.ID, &echotron.CallbackQueryOptions{}) - if u.CallbackQuery.Data != callback { + if !filter(u) { return false, nil } err := handler(u) diff --git a/update.go b/update.go index 53f9903..8a91ff8 100644 --- a/update.go +++ b/update.go @@ -230,6 +230,13 @@ func (u *Update) Text() string { return "" } +func (u *Update) Callback() string { + if u.IsCallback() { + return u.CallbackQuery.Data + } + return "" +} + func (u *Update) Entities() []*echotron.MessageEntity { if u.IsText() { return u.Message.Entities