lightningtipbot/internal/telegram/intercept/callback.go
gohumble fbbe18d7a7
add interceptor and handler context (#69)
* add interceptor for handler context

* remove user load

* remove UserInitializedWallet

* remove getuser invocation

* add lnbits user to inlineFaucet

* set wallet client

* lnbits user to inline receive

* lnbits user to inline send

* add context to handleInlineReceiveQuery

* add handler.go

* fix help message

* fix handler registration

* rename

* check if reply to is nil

* remove unwanted stuff

* error handlers

* remove client from wallet

* rename force to require

* string fixes

* add intercept.Func

* add PrivateChat check

* remove private chat requirement for anytexthandler

* fix callback

* errors fixed

* fix callback

* loadUser

* do not require

* check type in interceptor

* check type in interceptor

* check for user wallets

* allow send for toUser with wallet but not initialized

* fix reply to context

* mdescape

* strfux

* set state columns only

* update str

* set user now

* anytext should not load user outside pm

* rename endpoint to donationEndpoint

* register uppercase endpoints and add comments

* fix photos in logMessageInterceptor

* reduce log level to trace

Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-09-21 21:35:10 +02:00

64 lines
1.5 KiB
Go

package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
type Func func(ctx context.Context, message interface{}) (context.Context, error)
type handlerCallbackInterceptor struct {
handler CallbackFuncHandler
before CallbackChain
after CallbackChain
}
type CallbackChain []Func
type CallbackInterceptOption func(*handlerCallbackInterceptor)
func WithBeforeCallback(chain ...Func) CallbackInterceptOption {
return func(a *handlerCallbackInterceptor) {
a.before = chain
}
}
func WithAfterCallback(chain ...Func) CallbackInterceptOption {
return func(a *handlerCallbackInterceptor) {
a.after = chain
}
}
func interceptCallback(ctx context.Context, message *tb.Callback, hm CallbackChain) (context.Context, error) {
if ctx == nil {
ctx = context.Background()
}
if hm != nil {
var err error
for _, m := range hm {
ctx, err = m(ctx, message)
if err != nil {
return ctx, err
}
}
}
return ctx, nil
}
func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackInterceptOption) func(Callback *tb.Callback) {
hm := &handlerCallbackInterceptor{handler: handler}
for _, opt := range option {
opt(hm)
}
return func(c *tb.Callback) {
ctx, err := interceptCallback(context.Background(), c, hm.before)
if err != nil {
log.Traceln(err)
return
}
hm.handler(ctx, c)
_, err = interceptCallback(ctx, c, hm.after)
if err != nil {
log.Traceln(err)
}
}
}