Skip to content

Commit a02a8b5

Browse files
trakhimenokCopilot
andcommitted
docs: rewrite all README files
- Root README: fix import paths, fix example code (remove logus references, add correct module imports), add Packages table, fix webhook example, fix self-signed cert command, restructure sections, fix GoDoc badge URL - tglogin/README: fix type name TelegramUser→LoginUser, fix method name IsValid→IsFromTelegram, add usage example and exported API table - tgwebapp/README: fix AuthenticateTelegramWebApp signature (was wrong), document all four parameters, add InitData struct docs, document NewInitDataFromUrlValues, add Telegram docs links Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 0166466 commit a02a8b5

3 files changed

Lines changed: 235 additions & 65 deletions

File tree

README.md

Lines changed: 100 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,113 +1,160 @@
1-
# Golang bindings for the Telegram Bot API
1+
# Go bindings for the Telegram Bot API
22

33
[![Go CI](https://github.com/bots-go-framework/bots-api-telegram/actions/workflows/ci.yml/badge.svg)](https://github.com/bots-go-framework/bots-api-telegram/actions/workflows/ci.yml)
44
[![Go Report Card](https://goreportcard.com/badge/github.com/bots-go-framework/bots-api-telegram)](https://goreportcard.com/report/github.com/bots-go-framework/bots-api-telegram)
5-
[![GoDoc](https://godoc.org/github.com/bots-go-framework/bots-api-telegram?status.svg)](http://godoc.org/github.com/bots-go-framework/bots-api-telegram)
5+
[![GoDoc](https://pkg.go.dev/badge/github.com/bots-go-framework/bots-api-telegram)](https://pkg.go.dev/github.com/bots-go-framework/bots-api-telegram)
66

7-
All methods have been added, and all features should be available.
8-
If you want a feature that hasn't been added yet or something is broken,
9-
open an issue and I'll see what I can do.
7+
Go bindings for the [Telegram Bot API](https://core.telegram.org/bots/api), tracking **Bot API 9.5**.
108

11-
All methods are fairly self explanatory, and reading the godoc page should
12-
explain everything. If something isn't clear, open an issue or submit
13-
a pull request.
9+
This module also includes sub-packages for [Telegram Login Widget](#tglogin) and [Telegram Web Apps](#tgwebapp).
1410

15-
The scope of this project is just to provide a wrapper around the API
16-
without any additional features. There are other projects for creating
17-
something with plugins and command handlers without having to design
18-
all that yourself.
11+
## Packages
1912

20-
Use `github.com/go-telegram-bot-api/telegram-bot-api` for the latest
21-
version, or use `gopkg.in/telegram-bot-api.v1` for the stable build.
13+
| Package | Import path | Description |
14+
|---|---|---|
15+
| `tgbotapi` | `github.com/bots-go-framework/bots-api-telegram/tgbotapi` | Core Bot API types and HTTP client |
16+
| `tglogin` | `github.com/bots-go-framework/bots-api-telegram/tglogin` | Telegram Login Widget authentication |
17+
| `tgwebapp` | `github.com/bots-go-framework/bots-api-telegram/tgwebapp` | Telegram Web App (Mini App) init-data validation |
2218

23-
## Example
19+
## Installation
2420

25-
This is a very simple bot that just displays any gotten updates,
26-
then replies it to that chat.
21+
```sh
22+
go get github.com/bots-go-framework/bots-api-telegram
23+
```
24+
25+
## Examples
26+
27+
### Long-polling
28+
29+
A minimal bot that echoes every message back to the sender:
2730

2831
```go
2932
package main
3033

3134
import (
3235
"log"
33-
"gopkg.in/telegram-bot-api.v1"
36+
37+
"github.com/bots-go-framework/bots-api-telegram/tgbotapi"
3438
)
3539

3640
func main() {
37-
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
38-
if err != nil {
39-
logus.Panic(err)
40-
}
41+
bot := tgbotapi.NewBotAPI("MyAwesomeBotToken")
4142

42-
bot.Debug = true
43-
44-
logus.Printf("Authorized on account %s", bot.Self.UserName)
43+
log.Printf("Authorized on account %s", bot.Self.UserName)
4544

4645
u := tgbotapi.NewUpdate(0)
4746
u.Timeout = 60
4847

4948
updates, err := bot.GetUpdatesChan(u)
49+
if err != nil {
50+
log.Fatal(err)
51+
}
5052

5153
for update := range updates {
52-
logus.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
54+
if update.Message == nil {
55+
continue
56+
}
57+
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
5358

5459
msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
5560
msg.ReplyToMessageID = update.Message.MessageID
5661

57-
bot.Send(msg)
62+
if _, err := bot.Send(msg); err != nil {
63+
log.Println(err)
64+
}
5865
}
5966
}
6067
```
6168

62-
If you need to use webhooks (if you wish to run on Google App Engine),
63-
you may use a slightly different method.
69+
### Webhook
70+
71+
To receive updates via webhook your server must be reachable over HTTPS.
72+
Telegram supports ports **443, 80, 88, and 8443**.
6473

6574
```go
6675
package main
6776

6877
import (
69-
"gopkg.in/telegram-bot-api.v1"
7078
"log"
7179
"net/http"
80+
81+
"github.com/bots-go-framework/bots-api-telegram/tgbotapi"
7282
)
7383

7484
func main() {
75-
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
76-
if err != nil {
77-
logus.Fatal(err)
78-
}
79-
80-
bot.Debug = true
85+
bot := tgbotapi.NewBotAPI("MyAwesomeBotToken")
8186

82-
logus.Printf("Authorized on account %s", bot.Self.UserName)
87+
log.Printf("Authorized on account %s", bot.Self.UserName)
8388

84-
_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
89+
_, err := bot.SetWebhook(tgbotapi.NewWebhookWithCert(
90+
"https://example.com:8443/"+bot.Token, "cert.pem",
91+
))
8592
if err != nil {
86-
logus.Fatal(err)
93+
log.Fatal(err)
8794
}
8895

89-
updates, _ := bot.ListenForWebhook("/" + bot.Token)
90-
go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
96+
updates := bot.ListenForWebhook("/" + bot.Token)
97+
go func() {
98+
if err := http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil); err != nil {
99+
log.Fatal(err)
100+
}
101+
}()
91102

92103
for update := range updates {
93-
logus.Printf("%+v\n", update)
104+
log.Printf("%+v\n", update)
94105
}
95106
}
96107
```
97108

98-
If you need, you may generate a self signed certficate, as this requires
99-
HTTPS / TLS. The above example tells Telegram that this is your
100-
certificate and that it should be trusted, even though it is not
101-
properly signed.
109+
#### Self-signed TLS certificate
110+
111+
If you don't have a certificate from a trusted CA (e.g. [Let's Encrypt](https://letsencrypt.org)),
112+
you can generate a self-signed one. Pass the public certificate to `NewWebhookWithCert` so
113+
Telegram knows to trust it.
114+
115+
```sh
116+
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 \
117+
-subj "/O=Org/CN=example.com" -nodes
118+
```
119+
120+
## tglogin
121+
122+
The `tglogin` sub-package validates data received from the
123+
[Telegram Login Widget](https://core.telegram.org/widgets/login).
124+
125+
```go
126+
import "github.com/bots-go-framework/bots-api-telegram/tglogin"
127+
128+
user := tglogin.LoginUser{ /* fields from the widget callback */ }
129+
if user.IsFromTelegram(botToken) {
130+
// user data is authentic
131+
}
132+
```
133+
134+
See [`tglogin/README.md`](tglogin/README.md) for full details.
102135

103-
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes
136+
## tgwebapp
104137

105-
Now that [Let's Encrypt](https://letsencrypt.org) has entered public beta,
106-
you may wish to generate your free TLS certificate there.
138+
The `tgwebapp` sub-package validates init data received from a
139+
[Telegram Web App (Mini App)](https://core.telegram.org/bots/webapps).
140+
141+
```go
142+
import "github.com/bots-go-framework/bots-api-telegram/tgwebapp"
143+
144+
tgwebapp.AuthenticateTelegramWebApp(w, r,
145+
func(bot string) string { return myBotToken },
146+
func(initData *tgwebapp.InitData) {
147+
// initData is verified and ready to use
148+
},
149+
)
150+
```
151+
152+
See [`tgwebapp/README.md`](tgwebapp/README.md) for full details.
107153

108154
## Used by
109-
This package is used in production by:
110-
* https://debtstracker.io/ - an app and [Telegram bot](https://t.me/DebtsTrackerBot) to track your personal debts
111155

112-
## Frameworks that utilise this `strongo/db` package
113-
* [`bots-go-framework`](https://github.com/bots-go-framework) - a framework to build chat bots in Go language.
156+
- [debtstracker.io](https://debtstracker.io/) — personal debt tracking app with a [Telegram bot](https://t.me/DebtsTrackerBot)
157+
158+
## Related
159+
160+
- [`bots-go-framework`](https://github.com/bots-go-framework) — framework for building Telegram bots in Go

tglogin/README.md

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,55 @@
1-
# tglogin - Provides authentication for Telegram login widget
1+
# tglogin Telegram Login Widget authentication
22

3-
## Exports
3+
The `tglogin` package validates user data received from the
4+
[Telegram Login Widget](https://core.telegram.org/widgets/login).
45

5-
- `TelegramUser struct` - contains user data and a hash for authentication
6-
- `IsValid(botToken string) bool` - returns true if TelegramUser is valid
6+
## Installation
77

8-
## Documentation from Telegram
8+
```sh
9+
go get github.com/bots-go-framework/bots-api-telegram/tglogin
10+
```
911

10-
- https://telegram.org/blog/login
11-
- https://core.telegram.org/widgets/login
12+
## Usage
13+
14+
```go
15+
import "github.com/bots-go-framework/bots-api-telegram/tglogin"
16+
17+
// Populate from the widget callback query parameters
18+
user := tglogin.LoginUser{
19+
ID: 123456789,
20+
FirstName: "Alice",
21+
AuthDate: 1700000000,
22+
Hash: "<hash from Telegram>",
23+
}
24+
25+
if user.IsFromTelegram(botToken) {
26+
// Data is authentic — safe to create a session for this user
27+
} else {
28+
// Reject: data was not signed by Telegram
29+
}
30+
```
31+
32+
## Exported API
33+
34+
### `LoginUser`
35+
36+
```go
37+
type LoginUser struct {
38+
ID int `json:"id"`
39+
FirstName string `json:"first_name"`
40+
LastName string `json:"last_name,omitempty"`
41+
Username string `json:"username,omitempty"`
42+
PhotoUrl string `json:"photo_url,omitempty"`
43+
AuthDate int `json:"auth_date"`
44+
Hash string `json:"hash"`
45+
}
46+
```
47+
48+
| Method | Description |
49+
|---|---|
50+
| `IsFromTelegram(botToken string) bool` | Returns `true` if the struct fields are authentically signed by Telegram using the given bot token |
51+
52+
## Telegram documentation
53+
54+
- [Telegram Login blog post](https://telegram.org/blog/login)
55+
- [Login widget reference](https://core.telegram.org/widgets/login)

tgwebapp/README.md

Lines changed: 84 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,86 @@
1-
# tgwebapp - Provides authentication for Telegram web app
1+
# tgwebapp — Telegram Web App (Mini App) init-data validation
22

3-
## Exports
4-
- `func AuthenticateTelegramWebApp(w http.ResponseWriter, r *http.Request, authenticated func() error)`
3+
The `tgwebapp` package validates the `initData` received from a
4+
[Telegram Web App (Mini App)](https://core.telegram.org/bots/webapps)
5+
and parses it into a typed `InitData` struct.
56

6-
## Documentation from Telegram
7-
- https://core.telegram.org/bots/webapps
7+
## Installation
8+
9+
```sh
10+
go get github.com/bots-go-framework/bots-api-telegram/tgwebapp
11+
```
12+
13+
## Usage
14+
15+
Call `AuthenticateTelegramWebApp` from your HTTP handler. It reads the
16+
POST body, validates the HMAC signature, and invokes `complete` with the
17+
parsed `InitData`. On any error it writes the appropriate HTTP status and
18+
calls `complete` with an empty `InitData`.
19+
20+
```go
21+
import "github.com/bots-go-framework/bots-api-telegram/tgwebapp"
22+
23+
http.HandleFunc("/webapp", func(w http.ResponseWriter, r *http.Request) {
24+
tgwebapp.AuthenticateTelegramWebApp(w, r,
25+
func(bot string) string {
26+
return os.Getenv("TELEGRAM_BOT_TOKEN")
27+
},
28+
func(initData *tgwebapp.InitData) {
29+
if initData.QueryID == "" {
30+
return // authentication failed; HTTP error already written
31+
}
32+
// initData is verified — handle the request
33+
fmt.Fprintf(w, "Hello, auth_date=%d", initData.AuthDate)
34+
},
35+
)
36+
})
37+
```
38+
39+
## Exported API
40+
41+
### `AuthenticateTelegramWebApp`
42+
43+
```go
44+
func AuthenticateTelegramWebApp(
45+
w http.ResponseWriter,
46+
r *http.Request,
47+
getToken func(bot string) string,
48+
complete func(initData *InitData),
49+
)
50+
```
51+
52+
Validates the request and calls `complete` with the parsed init data.
53+
The `bot` parameter passed to `getToken` comes from the `?bot=` query
54+
string of the request URL, allowing a single handler to serve multiple bots.
55+
56+
### `InitData`
57+
58+
Parsed representation of the
59+
[`WebAppInitData`](https://core.telegram.org/bots/webapps#webappinitdata)
60+
object:
61+
62+
```go
63+
type InitData struct {
64+
QueryID string `json:"query_id"`
65+
ChatType string `json:"chat_type,omitempty"`
66+
ChatInstance string `json:"chat_instance,omitempty"`
67+
StartParam string `json:"start_param,omitempty"`
68+
CanSendAfter int `json:"can_send_after,omitempty"`
69+
AuthDate int `json:"auth_date"`
70+
Hash string `json:"hash"`
71+
}
72+
```
73+
74+
### `NewInitDataFromUrlValues`
75+
76+
```go
77+
func NewInitDataFromUrlValues(values url.Values) InitData
78+
```
79+
80+
Parses a `url.Values` map (e.g. from a POST body) into an `InitData` struct.
81+
82+
## Telegram documentation
83+
84+
- [Web Apps overview](https://core.telegram.org/bots/webapps)
85+
- [Validating init data](https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app)
86+
- [`WebAppInitData` reference](https://core.telegram.org/bots/webapps#webappinitdata)

0 commit comments

Comments
 (0)