mirror of
https://github.com/lukaszraczylo/go-telegram.git
synced 2026-06-05 22:43:59 +00:00
Initial release of go-telegram
A fully-generated, strongly-typed Go client for the Telegram Bot API. * 176 methods + 301 types generated from Bot API v10.0 * 1408 auto-generated tests (8 scenarios per method) * Typed unions throughout — no 'any' in the public surface * Pluggable HTTP transport and JSON codec (default goccy/go-json) * Built-in retry middleware honouring Telegram's retry_after * Generic dispatcher with filters and conversation handlers * Self-verifying codegen pipeline (regen → audit → emit → run tests) * 14 example bots covering common patterns
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
# echo
|
||||
|
||||
Long-poll echo bot. Replies to `/start` with a greeting and echoes any other text.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
export TELEGRAM_BOT_TOKEN=123456:ABC...
|
||||
go run ./examples/echo
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/lukaszraczylo/go-telegram/api"
|
||||
"github.com/lukaszraczylo/go-telegram/dispatch"
|
||||
)
|
||||
|
||||
// register wires all handlers onto the router. Exposed so tests can call
|
||||
// handlers directly without going through the router run loop.
|
||||
func register(r *dispatch.Router) {
|
||||
r.OnCommand("/start", handleStart)
|
||||
r.OnText(`.+`, handleEcho)
|
||||
}
|
||||
|
||||
func handleStart(c *dispatch.Context, m *api.Message) error {
|
||||
_, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{
|
||||
ChatID: api.ChatIDFromInt(m.Chat.ID),
|
||||
Text: fmt.Sprintf("hello %s, send me anything to echo", m.From.FirstName),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func handleEcho(c *dispatch.Context, m *api.Message) error {
|
||||
_, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{
|
||||
ChatID: api.ChatIDFromInt(m.Chat.ID),
|
||||
Text: m.Text,
|
||||
ReplyParameters: &api.ReplyParameters{MessageID: m.MessageID},
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/go-telegram/api"
|
||||
"github.com/lukaszraczylo/go-telegram/client"
|
||||
"github.com/lukaszraczylo/go-telegram/dispatch"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// mockDoer satisfies client.HTTPDoer via testify/mock.
|
||||
type mockDoer struct{ mock.Mock }
|
||||
|
||||
func (m *mockDoer) Do(r *http.Request) (*http.Response, error) {
|
||||
args := m.Called(r)
|
||||
if v := args.Get(0); v != nil {
|
||||
return v.(*http.Response), args.Error(1)
|
||||
}
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
|
||||
func okResp(body string) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: io.NopCloser(bytes.NewBufferString(body)),
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
}
|
||||
}
|
||||
|
||||
const sendMsgResult = `{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":42,"type":"private"}}}`
|
||||
|
||||
func makeCtx(bot *client.Bot, upd *api.Update) *dispatch.Context {
|
||||
return dispatch.NewContext(context.Background(), bot, upd)
|
||||
}
|
||||
|
||||
func TestHandleStart_GreetsUser(t *testing.T) {
|
||||
m := &mockDoer{}
|
||||
m.On("Do", mock.MatchedBy(func(r *http.Request) bool {
|
||||
if !strings.HasSuffix(r.URL.Path, "/sendMessage") {
|
||||
return false
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
_, _ = buf.ReadFrom(r.Body)
|
||||
body := buf.String()
|
||||
return strings.Contains(body, `"text"`) && strings.Contains(body, "Alice")
|
||||
})).Return(okResp(sendMsgResult), nil)
|
||||
|
||||
bot := client.New("test:token", client.WithHTTPClient(m))
|
||||
msg := &api.Message{
|
||||
MessageID: 1,
|
||||
Chat: api.Chat{ID: 42, Type: string(api.ChatTypePrivate)},
|
||||
From: &api.User{ID: 7, FirstName: "Alice"},
|
||||
Text: "/start",
|
||||
}
|
||||
upd := &api.Update{UpdateID: 1, Message: msg}
|
||||
|
||||
require.NoError(t, handleStart(makeCtx(bot, upd), msg))
|
||||
m.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestHandleEcho_RepliesWithSameText(t *testing.T) {
|
||||
m := &mockDoer{}
|
||||
m.On("Do", mock.MatchedBy(func(r *http.Request) bool {
|
||||
if !strings.HasSuffix(r.URL.Path, "/sendMessage") {
|
||||
return false
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
_, _ = buf.ReadFrom(r.Body)
|
||||
body := buf.String()
|
||||
// text is echoed and reply_to_message_id is set to source message ID (5)
|
||||
return strings.Contains(body, `"hello echo"`) &&
|
||||
strings.Contains(body, `"message_id":5`)
|
||||
})).Return(okResp(sendMsgResult), nil)
|
||||
|
||||
bot := client.New("test:token", client.WithHTTPClient(m))
|
||||
msg := &api.Message{
|
||||
MessageID: 5,
|
||||
Chat: api.Chat{ID: 42, Type: string(api.ChatTypePrivate)},
|
||||
From: &api.User{ID: 7, FirstName: "Alice"},
|
||||
Text: "hello echo",
|
||||
}
|
||||
upd := &api.Update{UpdateID: 1, Message: msg}
|
||||
|
||||
require.NoError(t, handleEcho(makeCtx(bot, upd), msg))
|
||||
m.AssertExpectations(t)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Package main is a long-poll echo bot. Run with:
|
||||
//
|
||||
// TELEGRAM_BOT_TOKEN=xxx go run ./examples/echo
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/lukaszraczylo/go-telegram/api"
|
||||
"github.com/lukaszraczylo/go-telegram/client"
|
||||
"github.com/lukaszraczylo/go-telegram/dispatch"
|
||||
"github.com/lukaszraczylo/go-telegram/transport"
|
||||
)
|
||||
|
||||
func main() {
|
||||
token := os.Getenv("TELEGRAM_BOT_TOKEN")
|
||||
if token == "" {
|
||||
log.Fatal("TELEGRAM_BOT_TOKEN required")
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
bot := client.New(token,
|
||||
client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())))
|
||||
me, err := api.GetMe(ctx, bot, &api.GetMeParams{})
|
||||
if err != nil {
|
||||
log.Fatalf("getMe: %v", err)
|
||||
}
|
||||
log.Printf("running as @%s", me.Username)
|
||||
|
||||
router := dispatch.New(bot)
|
||||
register(router)
|
||||
|
||||
poller := transport.NewLongPoller(bot)
|
||||
if err := router.Run(ctx, poller); err != nil && err != context.Canceled {
|
||||
log.Printf("router exited: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user