-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (56 loc) · 1.54 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"context"
"fmt"
"reflect"
"time"
"go.uber.org/zap"
"github.com/gotd/td/bin"
"github.com/gotd/td/examples"
"github.com/gotd/td/tdp"
"github.com/gotd/td/telegram"
"github.com/gotd/td/tg"
)
// prettyMiddleware pretty-prints request and response.
func prettyMiddleware() telegram.MiddlewareFunc {
return func(next tg.Invoker) telegram.InvokeFunc {
return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error {
fmt.Println("→", formatObject(input))
start := time.Now()
if err := next.Invoke(ctx, input, output); err != nil {
fmt.Println("←", err)
return err
}
fmt.Printf("← (%s) %s\n", time.Since(start).Round(time.Millisecond), formatObject(output))
return nil
}
}
}
func formatObject(input interface{}) string {
o, ok := input.(tdp.Object)
if !ok {
// Handle tg.*Box values.
rv := reflect.Indirect(reflect.ValueOf(input))
for i := 0; i < rv.NumField(); i++ {
if v, ok := rv.Field(i).Interface().(tdp.Object); ok {
return formatObject(v)
}
}
return fmt.Sprintf("%T (not object)", input)
}
return tdp.Format(o)
}
func main() {
examples.Run(func(ctx context.Context, log *zap.Logger) error {
return telegram.BotFromEnvironment(ctx, telegram.Options{
UpdateHandler: telegram.UpdateHandlerFunc(func(ctx context.Context, u tg.UpdatesClass) error {
// Print all incoming updates.
fmt.Println("u:", formatObject(u))
return nil
}),
Middlewares: []telegram.Middleware{
prettyMiddleware(),
},
}, nil, telegram.RunUntilCanceled)
})
}