Awesome Go

bot

CategoryBot Building
SubcategoryBot Building
Stars1,894

Zero-dependencies Telegram Bot library with additional UI components

About bot

This large README is shown as a plain-text preview. Read the full README at the source

# Golang Telegram Bot

[![Go Report Card](https://goreportcard.com/badge/github.com/go-telegram/bot)](https://goreportcard.com/report/github.com/go-telegram/bot) [![codecov](https://codecov.io/gh/go-telegram/bot/branch/main/graph/badge.svg?token=57B1OR6PCK)](https://codecov.io/gh/go-telegram/bot)

✅ Present in the list of libraries https://core.telegram.org/bots/samples#go

> [Telegram Group](https://t.me/gotelegrambotui)

> Supports Bot API version: [10.5](https://core.telegram.org/bots/api-changelog#november-22-2026) from November 22, 2026

It's a Go zero-dependencies telegram bot framework

A simple example `echo-bot`:

```go
package main

import (
	"context"
	"os"
	"os/signal"

	"github.com/go-telegram/bot"
	"github.com/go-telegram/bot/models"
)

// Send any text message to the bot after the bot has been started

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

	opts := []bot.Option{
		bot.WithDefaultHandler(handler),
	}

	b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", opts...)
	if err != nil {
		panic(err)
	}

	b.Start(ctx)
}

func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
	b.SendMessage(ctx, &bot.SendMessageParams{
		ChatID: update.Message.Chat.ID,
		Text:   update.Message.Text,
	})
}
```

You can find more examples in the [examples](examples) folder.

To run the examples, set the `EXAMPLE_TELEGRAM_BOT_TOKEN` environment variable to your bot token.

## Getting started

Go version: **1.18**

Install the dependencies:

```bash
go get -u github.com/go-telegram/bot
```

Initialize and run the bot:

```go
b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER")

b.Start(context.TODO())
```

On create bot will call the `getMe` method (with 5 sec timeout). And returns error on fail.
If you want to change this timeout, use option `bot.WithCheckInitTimeout`

You can define a default handler for the bot:

```go
b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", bot.WithDefaultHandler(handler))

func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
	// this handler will be called for all updates
}
```

## Webhooks

If you want to use webhooks, instead of using `bot.Start`, you should use the `bot.StartWebhook` method to start the bot.
Also, you should use `bot.WebhookHandler()` method as HTTP handler for your server.

For a valid update, `WebhookHandler` returns HTTP 200 once a worker takes the
update, and the worker then runs its matchers, middlewares and handler. With
`bot.WithNotAsyncHandlers`, a request therefore waits for a free worker. If
`StartWebhook` is not running, or the run stops or the request is canceled
before a worker takes the update, it returns HTTP 503 so Telegram can retry,
and the update is not handled. An unreadable request body gets HTTP 400 for
the same reason.

Cancel the context passed to `StartWebhook` to shut down. Handlers receive a
context derived from it that is canceled when the run stops. `StartWebhook`
waits for running handlers to return. Cancel it before shutting down the HTTP
server, so that requests still waiting for a worker get 503 right away.

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

	opts := []bot.Option{
		bot.WithDefaultHandler(handler),
		bot.WithWebhookSecretToken(os.Getenv("EXAMPLE_TELEGRAM_WEBHOOK_SECRET_TOKEN")),
	}

	b, err := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...)
	if err != nil {
		panic(err)
	}

	// call methods.SetWebhook if needed

	go func() {
		if err := http.ListenAndServe(":2000", b.WebhookHandler()); err != nil {
			log.Printf("webhook server: %v", err)
			cancel()
		}
	}()

	b.StartWebhook(ctx)

	// call methods.DeleteWebhook if needed
}

func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
	b.SendMessage(ctx, &bot.SendMessageParams{
		ChatID: update.Message.Chat.ID,
		Text:   update.Message.Text,
	})
}
```

[Demo in examples](examples/echo_with_webhook/main.go)

### Webhook replies

A handler can also answer an update in the response to the webhook request that
delivered it. However, Telegram does not report whether the call succeeded.
See [Making requests when getting updates](https://core.telegram.org/bots/api#making-requests-when-getting-updates).

Use `bot.WebhookReplyHandler()` as the HTTP handler instead of
`bot.WebhookHandler()`. It runs the handler for each update in the goroutine
serving the request and responds once the handler returns, so `bot.StartWebhook`
is not needed. In the handler, call `bot.WebhookReply` with the method name and
its parameters:

```go
func main() {
	b, _ := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), bot.WithDefaultHandler(handler))

	http.ListenAndServe(":2000", b.WebhookReplyHandler())
}

func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
	b.WebhookReply(ctx, "sendMessage", &bot.SendMessageParams{
		ChatID: update.Message.Chat.ID,
		Text:   update.Message.Text,
	})
}
```

A handler can reply only once per update, and only before it returns.
Otherwise, `bot.WebhookReply` returns an error wrapping
`bot.ErrorWebhookReplyUnavailable`.

[Demo in examples](examples/inline_mode_webhook_reply/main.go)

Also, you can manually process updates with `bot.ProcessUpdate` method.

```go
update := models.Update{}

json.NewDecoder(req.Body).Decode(&update)

b.ProcessUpdate(ctx, &update)
```

## Middlewares

You can use middlewares with `WithMiddlewares(middlewares ...Middleware)` option.

See an example in [examples](examples/middleware/main.go)

## Available methods

All available methods are listed in the [Telegram Bot API documentation](https://core.telegram.org/bots/api)

You can use all these methods as bot funcs. All methods have name like in official documentation, but with capital first letter.

`bot.SendMessage`, `bot.GetMe`, `bot.SendPhoto`, etc

Most methods take a context and a pointer to a parameters struct and return a response and an error.
`GetMe`, `GetMeLegacy`, `Close`, and `Logout` take only a context.

`<PARAMS>` is a struct with fields that corresponds to Telegram Bot API parameters.
All Params structs have name like for corresponded methods, but with `Params` suffix.

`SendMessageParams` for `SendMessage` method etc.

You should pass params by pointer

```go
bot.SendMessage(ctx, &bot.SendMessageParams{...})
```

### Migrating to Bot API 10.5

`b.GetMe(ctx)` now returns `*models.BotFullInfo`. Code that only reads `me.ID` or
`me.Username` from an inferred result needs no changes. If you used
`me.SupportInlineQueries`, use `me.SupportsInlineQueries` (with an **s** after `Support`).
If a caller still needs `*models.User`, switch that call to `b.GetMeLegacy(ctx)`
while migrating. The legacy method is deprecated.

Expandable quotations in rich messages now contain blocks. Read `Blocks` on
`models.RichBlockExpandableBlockQuotation`; the library no longer populates `Text`.
To send a text quotation, put the rich text in a paragraph block:

```go
quote := models.InputRichBlockExpandableBlockQuotation{
	Blocks: []models.InputRichBlock{{
		Type: models.RichBlockTypeParagraph,
		InputRichBlockParagraph: &models.InputRichBlockParagraph{
			Text: models.RichText{PlainText: "Quoted text"},
		},
	}},
}
```

Sending a nonzero `Text` with no blocks returns `Text is deprecated; use Blocks`
before the request is sent. If both are set, only `Blocks` is used. Ordinary
message text (`SendMessageParams.Text` and `models.Message.Text`) is unchanged.

## Options

You can use options to customize the bot.

```go
b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER", opts...)
```

### Options list (see [options.go](options.go) for more details)

- `WithCheckInitTimeout(timeout time.Duration)` - timeout for check init bot
- `WithMiddlewares(middlewares ...Middleware)` - add middlewares
- `WithMessageTextHandler(pattern string, matchType MatchType, handler HandlerFunc)` - add handler for Message.Text field
- `WithCallbackQueryDataHandler(pattern string, matchType MatchType, handler HandlerFunc)` - add handler for CallbackQuery.Data field
- `WithPhotoCaptionHandler` - add handler for Message.Caption field
- `WithDefaultHandler(handler HandlerFunc)` - add default handler
- `WithDebug()` - enable debug mode
- `WithErrorsHandler(handler ErrorsHandler)` - add errors handler
- `WithDebugHandler(handler DebugHandler)` - add debug handler
- `WithHTTPClient(pollTimeout time.Duration, client HttpClient)` - set custom http client
- `WithServerURL(serverURL string)` - set server url
- `WithSkipGetMe()` - skip `GetMe` during initialization. Command handlers still match `/start`; to also match `/start@username` for the bot's primary or active usernames, call `GetMe` successfully first.
- `WithAllowedUpdates(params AllowedUpdates)` - set [allowed_updates](https://core.telegram.org/bots/api#getupdates) for getUpdates method
- `WithUpdatesChannelCap(cap int)` - set updates channel capacity, by default 1024
- `WithWebhookSecretToken(webhookSecretToken string)` - set X-Telegram-Bot-Api-Secret-Token header sent from telegram servers to confirm validity of update
- `WithWorkers` - set the number of workers that are processing the Updates channel, by default 1
- `UseTestEnvironment()` - use test environment
- `WithNotAsyncHandlers()` - allows to run handlers in the main goroutine
- `WithInitialOffset(offset int64)` - allows to set initial offset for getUpdates method

## Message.Text and CallbackQuery.Data handlers

For your convenience, you can match message text, photo captions, callback data,
inline query text and widget query data.

An example:

```go
b, err := bot.New("YOUR_BOT_TOKEN_FROM_BOTFATHER")

b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, myStartHandler)

b.Start(context.TODO())
```

> also you can use bot init options `WithMessageTextHandler` and `WithCallbackQueryDataHandler`


In this example, the handler will be called when the user sends `/start` message. All other messages will be handled by the default handler.

Handler Types:
- `HandlerTypeMessageText` - for Update.Message.Text field
- `HandlerTypeCallbackQueryData` - for Update.CallbackQuery.Data field
- `HandlerTypeCallbackQueryGameShortName` - for Update.CallbackQuery.GameShortName field
- `HandlerTypePhotoCaption` - for Update.Message.Caption field
- `HandlerTypeInlineQuery` - for Update.InlineQuery.Query field
- `HandlerTypeWidgetQueryData` - for Update.WidgetQuery.Data field
- `HandlerTypeSharedWidgetQueryData` - for Update.SharedWidgetQuery.Data field

Use `RegisterHandlerInlineQuery(handler)` to handle all inline queries, including
empty queries. It returns a handler ID and accepts optional middlewares, like
`RegisterHandler`. To filter inline query text, use `RegisterHandler` with
`HandlerTypeInlineQuery` and `MatchTypeExact`, `MatchTypePrefix`, or
`MatchTypeContains`, or use `RegisterHandlerRegexp`. Inline queries have no message
entities, so command match types do not match them.

Widget query data supports exact, prefix, substring and regular-expression
matching, for example:

```go
b.RegisterHandler(bot.HandlerTypeWidgetQueryData, "buy:", bot.MatchTypePrefix, widgetHandler)
b.RegisterHandler(bot.HandlerTypeSharedWidgetQueryData, "buy:", bot.MatchTypePrefix, sharedWidgetHandler)
```

Read the query ID from `update.WidgetQuery.ID` or `update.SharedWidgetQuery.ID`
and answer it with `b.AnswerWidgetQuery`. Widget queries have no message entities,
so command match types do not match them.

RegisterHandler returns a handler ID string. You can use it to remove the handler later.

```
b.UnregisterHandler(handlerID)
```

Match Types:
- `MatchTypeExact`
- `MatchTypePrefix`
- `MatchTypeContains`
- `MatchTypeCommand`
- `MatchTypeCommandStartOnly`

> For `MatchTypeCommand` and `MatchTypeCommandStartOnly` usage see an [example](examples/command_handler/main.go)

You can use `RegisterHandlerRegexp` to match by regular expression.

```go
re := regexp.MustCompile(`^/start`)

b.RegisterHandlerRegexp(bot.HandlerTypeMessageText, re, myStartHandler)
```

If you want to use custom handler, use `RegisterHandlerMatchFunc`

```go
matchFunc := func(update *models.Update) bool {
	// your checks
	return true
}

b.RegisterHandlerMatchFunc(matchFunc, myHandler)
```

## Update user and chat

Use `update.EffectiveUser()` and `update.EffectiveChat()` when a handler or
middleware works with multiple update types:

```go
if user := update.EffectiveUser(); user != nil {
    log.Printf("user ID: %d", user.ID)
}
if chat := update.EffectiveChat(); chat != nil {
    log.Printf("chat ID: %d", chat.ID)
}
```

Both helpers return pointers into the original update and are safe to call on a
nil update. A user or chat may be unavailable, so check each result for nil.
For widget queries, `EffectiveUser` returns the sender; `EffectiveChat` returns
the widget's chat when present. Inline widget queries and shared widget queries
have no chat.

## InputFile

For some methods, like `SendPhoto`, `SendAudio` etc, you can send file by file path or file contents.

To send a file by URL or FileID, you can use `&models.InputFileString{Data: string}`:

```go
// file id of uploaded image
inputFileData := "AgACAgIAAxkDAAIBOWJimnCJHQJiJ4P3aasQCPNyo6mlAALDuzEbcD0YSxzjB-vmkZ6BAQADAgADbQADJAQ"
// or URL image path
// inputFileData := "https://example.com/image.png"

params := &bot.SendPhotoParams{
    ChatID:  chatID,
    Photo:   &models.InputFileString{Data: inputFileData},
}

bot.SendPhoto(ctx, params)
```

[Demo in examples](examples/send_photo/main.go)

To send an image file by its contents, you can use `&models.InputFileUpload{Filename: string, Data: io.Reader}`:

```go
fileContent, _ := os.ReadFile("/path/to/image.png")

params := &bot.SendPhotoParams{
    ChatID:  chatID,
    Photo:   &models.InputFileUpload{Filename: "image.png", Data: bytes.NewReader(fileContent)},
}

bot.SendPhoto(ctx, params)
```

[Demo in examples](examples/send_photo_upload/main.go)

## InputMedia

For methods like `SendMediaGroup` or `EditMessageMedia` you can send media by file path or file contents.

[Official documentation InputMedia](https://core.telegram.org/bots/api#inputmedia)

> field `media`: File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name.

If you want to use `attach://` format, you should to define `MediaAttachment` field with file content reader.

```go
fileContent, _ := os.ReadFile("/path/to/image.png")

media1 := &models.InputMediaPhoto{
	Media: "https://telegram.org/img/t_logo.png",
}

media2 := &models.InputMediaPhoto{
	Media: "attach://image.png",
	Caption: "2",
	MediaAttachment: bytes.NewReader(fileContent),
}

params := &bot.SendMediaGroupParams{
    ChatID: update.Message.Chat.ID,
    Media: []models.InputMedia{
        media1,
        media2,
    },
}

bot.SendMediaGroup(ctx, params)
```

[Demo in examples](examples/send_media_group/main.go)

Telegram does not accept a reused file as a thumbnail, so a thumbnail is normally an
`InputFileUpload`: it is sent as a separate part and referenced by `attach://`, with
`Filename` as the part name. An `InputFileString` is passed through unchanged, so a
`file_id` or an URL reaches the API as written.

A part name identifies one file within a request. Referencing the same file from
several entries under one name is fine — the part is written once and every reference
resolves to it — but two different files sharing a name are rejected with an error,
since Telegram would resolve both references to the first of them. A file part and a
form field cannot share a name either.

```go
thumbContent, _ := os.ReadFile("/path/to/thumb.jpg")

media := &models.InputMediaVideo{
	Media:           "attach://video.mp4",
	MediaAttachment: bytes.NewReader(videoContent),
	Thumbnail:       &models.InputFileUpload{Filename: "thumb.jpg", Data: bytes.NewReader(thumbContent)},
}
```

## InputSticker

For `CreateNewStickerSet` method you can send sticker by file path or file contents.

[Official documentation InputSticker]((https://core.telegram.org/bots/api#inputsticker)

> field `sticker`: The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new file using multipart/form-data under <file_attach_name> name. Animated and video stickers can't be uploaded via HTTP URL.

If you want to use `attach://` format, you should to define `StickerAttachment` field with file content reader.

```go
fileContent, _ := os.ReadFile("/path/to/telegram.png")

inputSticker1 := models.InputSticker{
	Sticker:   "https://github.com/go-telegram/bot/blob/main/examples/create_new_sticker_set/images/telegram.png?raw=true",
	Format:    "static",
	EmojiList: []string{"1️⃣"},
}

inputSticker2 := models.InputSticker{
	Sticker:           "attach://telegram.png",
	Format:            "static",
	EmojiList:         []string{"2️⃣"},
	StickerAttachment: bytes.NewReader(fileContent),
}

params := &bot.CreateNewStickerSetParams{
	UserID: update.Message.Chat.ID,
	Name:   fmt.Sprintf("Example%d_by_%s", time.Now().Unix(), botUsername),
	Title:  "Example sticker set",
	Stickers: []models.InputSticker{
		inputSticker1,
		inputSticker2,
	},
}

b.CreateNewStickerSet(ctx, params)
```

[Demo in examples](examples/create_new_sticker_set/main.go)

## Helpers

### `EscapeMarkdown(s string) string`

Escape special symbols for Telegram MarkdownV2 syntax

### `EscapeMarkdownUnescaped(s string) string`

Escape only unescaped special symbols for Telegram MarkdownV2 syntax

### `RandomString(n int) string`

Returns fast random a-zA-Z string with n length

### `True() bool`, `False() bool`

Allows you to define `*bool` values for params, which require `*bool`, like `SendPollParams`

```go
p := &bot.SendPollParams{
    ChatID: chatID,
    Question: "Question",
    Options: []string{"Option 1", "Option 2"},
    IsAnonymous: bot.False(),
}

b.SendPoll(ctx, p)
```

### `ValidateWebappRequest(values url.Values, token string) (user *WebAppUser, ok bool)`

Validate request from Telegram Webapp

https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app

Load the bot token at startup.

```go
token := os.Getenv("TELEGRAM_BOT_TOKEN")
if token == "" {
    log.Fatal("TELEGRAM_BOT_TOKEN is not set or empty")
}
```

In the request handler, pass the decoded query values.

```go
user, ok := bot.ValidateWebappRequest(req.URL.Query(), token)
if !ok {
    http.Error(w, "Unauthorized", http.StatusUnauthorized)
    return
}
log.Println(user.ID)
```

It returns only the user. Use `ValidateWebAppInitData` when the full init data is needed.

### `ValidateWebAppInitData(initData, token string) (*WebAppInitData, error)`

Parse the raw `Telegram.WebApp.initData` string and validate its hash with the bot token

https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app

```go
data, err := bot.ValidateWebAppInitData(initData, token)
if err == nil {
    err = data.CheckAuthDate(time.Hour)
}
if errors.Is(err, bot.ErrorWebAppInitDataExpired) {
    http.Error(w, "Expired", http.StatusUnauthorized)
    return
}
if err != nil {
    http.Error(w, "Unauthorized", http.StatusUnauthorized)
    return
}
if data.User != nil {
    log.Println(data.User.ID)
}
```

### `ValidateWebAppInitDataSignature(initData string, botID int64, publicKey ed25519.PublicKey) (*WebAppInitData, error)`

Parse the raw `Telegram.WebApp.initData` string and validate its Ed25519 signature, for a third party that has the bot ID but not the token

The returned `Hash` is passed through without verification.

https://core.telegram.org/bots/webapps#validating-data-for-third-party-use

Decode the public key at startup.

```go

Frequently Asked Questions

What is bot?

bot is a Bot Building library for the Go programming language. Zero-dependencies Telegram Bot library with additional UI components

How many GitHub stars does bot have?

bot has 1,894 GitHub stars in the directory's latest synchronization.

How do I install bot?

Install bot with the Go module system using `go get go-telegram/bot`. Check the repository for the current installation instructions.

What category does bot belong to?

bot is listed under Bot Building, specifically Bot Building.

← Back to Bot Building