Skip to content

Commit 4301fd8

Browse files
ernadoclaude
andcommitted
docs(examples): add echo bot demonstrating the handler framework
A minimal, runnable bot: Recover+Timeout middleware, /start via OnCommand, and an echo handler guarded by HasText + Not(HasPrefix("/")) that replies with the message text. Exercises the full incoming pipe end to end. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent bccfe63 commit 4301fd8

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

examples/echo/main.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Command echo is a minimal bot built on github.com/gotd/botapi: it greets on
2+
// /start and echoes any other text message back as a reply.
3+
//
4+
// Run it with an MTProto app identity (https://my.telegram.org) and a BotFather
5+
// token:
6+
//
7+
// APP_ID=12345 APP_HASH=abcdef BOT_TOKEN=123:abc go run ./examples/echo
8+
package main
9+
10+
import (
11+
"context"
12+
"os"
13+
"os/signal"
14+
"strconv"
15+
"time"
16+
17+
"go.uber.org/zap"
18+
19+
"github.com/gotd/botapi"
20+
)
21+
22+
func main() {
23+
log, _ := zap.NewDevelopment()
24+
defer func() { _ = log.Sync() }()
25+
26+
appID, err := strconv.Atoi(os.Getenv("APP_ID"))
27+
if err != nil {
28+
log.Fatal("APP_ID must be a number (see https://my.telegram.org)", zap.Error(err))
29+
}
30+
31+
bot, err := botapi.New(os.Getenv("BOT_TOKEN"), botapi.Options{
32+
AppID: appID,
33+
AppHash: os.Getenv("APP_HASH"),
34+
Logger: log,
35+
})
36+
if err != nil {
37+
log.Fatal("Create bot", zap.Error(err))
38+
}
39+
40+
// Middleware applies to every handler.
41+
bot.Use(botapi.Recover(), botapi.Timeout(30*time.Second))
42+
43+
bot.OnCommand("start", func(c *botapi.Context) error {
44+
_, err := c.Reply("Hi! Send me any text and I'll echo it back.")
45+
return err
46+
})
47+
48+
// Any text message that is not a command.
49+
bot.OnMessage(func(c *botapi.Context) error {
50+
_, err := c.Reply(c.Message().Text)
51+
return err
52+
}, botapi.HasText(), botapi.Not(botapi.HasPrefix("/")))
53+
54+
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
55+
defer cancel()
56+
57+
log.Info("Starting echo bot")
58+
if err := bot.Run(ctx); err != nil {
59+
log.Fatal("Run", zap.Error(err))
60+
}
61+
}

0 commit comments

Comments
 (0)