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
8 changes: 4 additions & 4 deletions business_updates.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,10 @@ func (u *Update) businessConnectionID() string {
}

// Kind predicates for business updates.
func hasBusinessMessage(u *Update) bool { return u.BusinessMessage != nil }
func hasEditedBusinessMessage(u *Update) bool { return u.EditedBusinessMessage != nil }
func hasBusinessConnection(u *Update) bool { return u.BusinessConnection != nil }
func hasDeletedBusinessMessages(u *Update) bool { return u.DeletedBusinessMessages != nil }
func hasBusinessMessage(c *Context) bool { return c.Update.BusinessMessage != nil }
func hasEditedBusinessMessage(c *Context) bool { return c.Update.EditedBusinessMessage != nil }
func hasBusinessConnection(c *Context) bool { return c.Update.BusinessConnection != nil }
func hasDeletedBusinessMessages(c *Context) bool { return c.Update.DeletedBusinessMessages != nil }

// OnBusinessMessage registers a handler for new messages from a connected
// business account.
Expand Down
29 changes: 25 additions & 4 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ queue. (`PeerRef` is for sending; chat-management methods still take a resolved

## Predicates

Every `On*` method accepts trailing `Predicate`s (`func(*Update) bool`); the
handler runs only when all match. First match wins across handlers.
Every `On*` method accepts trailing `Predicate`s (`func(*botapi.Context) bool`);
the handler runs only when all match. First match wins across handlers.

```go
bot.OnMessage(handler, botapi.HasText(), botapi.Not(botapi.HasPrefix("/")))
Expand All @@ -263,8 +263,8 @@ Built-ins: `Command`, `HasPrefix`, `HasText`, `TextEquals`, `Regex`,
Write your own — it's just a function:

```go
func hasPhoto(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasPhoto(c *botapi.Context) bool {
m := c.Message()
return m != nil && len(m.Photo) > 0
}
```
Expand All @@ -280,6 +280,27 @@ bot.Use(botapi.Recover(), botapi.Timeout(30*time.Second), botapi.Logging())

Built-ins: `Recover` (turns panics into errors), `Timeout`, `Logging`.

## Outer Middleware

An `OuterMiddleware` is also a `func(Handler) Handler`. Register global middleware
that runs before route matching with `UseOuter`:
```go
bot.UseOuter(botapi.Recover(), ChatConfigMiddleware())
```

See [`examples/middleware`](../examples/middleware) for a complete example
showing how data flows from outer middleware to predicates and handlers.

### Pipeline Execution Order

Middlewares and handlers execute in a distinct lifecycle layer (from the outside in).
The visualization below demonstrates how an update travels through the bot:

1. **`UseOuter`** (Always runs first; can short-circuit or inject data into `Context`).
2. **`Predicate` matching** (Evaluates route guards; has access to data from `UseOuter`).
3. **`Use`** (Runs only if a route matches; ideal for logging, telemetry, or lazy-loading user sessions).
4. **`Handler`** (Your core business logic).

## Groups

`Group` scopes shared predicates and middleware to a subset of handlers:
Expand Down
20 changes: 10 additions & 10 deletions examples/advanced/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,28 +435,28 @@ func reverse(s string) string {
return string(r)
}

func hasPhoto(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasPhoto(c *botapi.Context) bool {
m := c.Message()
return m != nil && len(m.Photo) > 0
}

func hasDocument(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasDocument(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Document != nil
}

func hasSticker(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasSticker(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Sticker != nil
}

func hasLocation(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasLocation(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Location != nil
}

func hasContact(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasContact(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Contact != nil
}

Expand Down
20 changes: 10 additions & 10 deletions examples/demo/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,28 +26,28 @@ func reverse(s string) string {

// --- incoming-media predicates, shared by media.go ---

func hasPhoto(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasPhoto(c *botapi.Context) bool {
m := c.Message()
return m != nil && len(m.Photo) > 0
}

func hasDocument(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasDocument(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Document != nil
}

func hasSticker(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasSticker(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Sticker != nil
}

func hasLocation(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasLocation(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Location != nil
}

func hasContact(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasContact(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Contact != nil
}

Expand Down
8 changes: 4 additions & 4 deletions examples/media/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,13 @@ func main() {
}

// hasPhoto matches messages that carry a photo.
func hasPhoto(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasPhoto(c *botapi.Context) bool {
m := c.Message()
return m != nil && len(m.Photo) > 0
}

// hasDocument matches messages that carry a document.
func hasDocument(u *botapi.Update) bool {
m := u.EffectiveMessage()
func hasDocument(c *botapi.Context) bool {
m := c.Message()
return m != nil && m.Document != nil
}
60 changes: 60 additions & 0 deletions examples/middleware/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"context"
"os"
"os/signal"
"strconv"
"time"

"github.com/gotd/log/logzap"
"go.uber.org/zap"

"github.com/gotd/botapi"
"github.com/gotd/botapi/storage"
)

func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()

log, _ := zap.NewProduction()
defer func() { _ = log.Sync() }()

store, err := storage.Open(os.Getenv("STORAGE_PATH"))
if err != nil {
log.Fatal("Open storage", zap.Error(err))
}

defer func() { _ = store.Close() }()

appID, err := strconv.Atoi(os.Getenv("APP_ID"))
if err != nil {
log.Fatal("App ID", zap.Error(err))
}

bot, err := botapi.New(os.Getenv("BOT_TOKEN"), botapi.Options{
AppID: appID,
AppHash: os.Getenv("APP_HASH"),
Logger: logzap.New(log),
Storage: store,
FloodWait: true,
})
if err != nil {
log.Fatal("Create bot", zap.Error(err))
}

bot.UseOuter(func(next botapi.Handler) botapi.Handler {
return func(c *botapi.Context) error {
return next(c)
}
})

bot.Use(botapi.Recover(), botapi.Timeout(time.Minute), botapi.Logging())

log.Info("Starting bot")

if err := bot.Run(ctx); err != nil {
log.Error("Run", zap.Error(err))
}
}
57 changes: 39 additions & 18 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type Handler func(c *Context) error

// Predicate reports whether a Handler should run for an update. A Handler runs
// only if all of its predicates return true.
type Predicate func(u *Update) bool
type Predicate func(c *Context) bool

// Middleware wraps a Handler, returning a new one. Middleware registered with
// Bot.Use runs for every handled update, outermost first.
Expand All @@ -33,9 +33,9 @@ type route struct {
mws []Middleware
}

func (r route) matches(u *Update) bool {
func (r route) matches(c *Context) bool {
for _, p := range r.predicates {
if !p(u) {
if !p(c) {
return false
}
}
Expand All @@ -49,6 +49,7 @@ type router struct {
mu sync.RWMutex
routes []route
mws []Middleware
preMws []Middleware
}

// Use registers global middleware applied to every handled update. Middleware
Expand All @@ -60,6 +61,16 @@ func (b *Bot) Use(mws ...Middleware) {
b.router.mws = append(b.router.mws, mws...)
}

// UseOuter registers global middleware applied to every update BEFORE route matching.
// This is the outermost layer of the pipeline, useful for logging, recovery, and tracing.
// Middleware runs outermost-first in registration order. Call before Run.
func (b *Bot) UseOuter(mws ...Middleware) {
b.router.mu.Lock()
defer b.router.mu.Unlock()

b.router.preMws = append(b.router.preMws, mws...)
}

// on registers a handler guarded by the given predicates.
func (b *Bot) on(handler Handler, predicates ...Predicate) {
b.onWith(handler, nil, predicates)
Expand All @@ -82,31 +93,41 @@ func (b *Bot) route(ctx context.Context, u *Update) {
u.botUsername = b.self.Username
}

c := &Context{Context: ctx, Bot: b, Update: u}

b.router.mu.RLock()

preMws := b.router.preMws
routes := b.router.routes
mws := b.router.mws
b.router.mu.RUnlock()

for _, r := range routes {
if !r.matches(u) {
continue
}
var routingHandler Handler = func(c *Context) error {
for _, r := range routes {
if !r.matches(c) {
continue
}

h := r.handler
for i := len(r.mws) - 1; i >= 0; i-- {
h = r.mws[i](h)
}
h := r.handler
for i := len(r.mws) - 1; i >= 0; i-- {
h = r.mws[i](h)
}

for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}

c := &Context{Context: ctx, Bot: b, Update: u}
if err := h(c); err != nil {
b.logger().Error(ctx, "Handler error", log.Error(err))
return h(c)
}

return
return nil
}

for i := len(preMws) - 1; i >= 0; i-- {
routingHandler = preMws[i](routingHandler)
}

if err := routingHandler(c); err != nil {
b.logger().Error(c.Context, "Pipeline error", log.Error(err))
}
}
41 changes: 40 additions & 1 deletion handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ func TestRouterFirstMatchWins(t *testing.T) {

var calls []string

b.on(func(c *Context) error { calls = append(calls, "skipped"); return nil }, func(u *Update) bool { return false })
b.on(func(c *Context) error { calls = append(calls, "skipped"); return nil }, func(c *Context) bool { return false })
b.on(func(c *Context) error { calls = append(calls, "matched"); return nil })
b.on(func(c *Context) error { calls = append(calls, "second-match"); return nil })

Expand Down Expand Up @@ -59,6 +59,45 @@ func TestMiddlewareOrder(t *testing.T) {
}
}

func TestOuterMiddlewareOrder(t *testing.T) {
b := newTestBot(t)

var order []string

b.UseOuter(func(next Handler) Handler {
return func(c *Context) error {
order = append(order, "outer")
return next(c)
}
})

b.Use(func(next Handler) Handler {
return func(c *Context) error {
order = append(order, "global")
return next(c)
}
})

b.on(func(c *Context) error {
order = append(order, "handler")
return nil
})

b.route(context.Background(), &Update{})

want := []string{"outer", "global", "handler"}

if len(order) != len(want) {
t.Fatalf("order = %v, want %v", order, want)
}

for i := range want {
if order[i] != want[i] {
t.Fatalf("order = %v, want %v", order, want)
}
}
}

func TestRouterHandlerErrorIsContained(t *testing.T) {
b := newTestBot(t)
b.on(func(c *Context) error { return errors.New("boom") })
Expand Down
Loading