Skip to content

Commit e8dfdee

Browse files
author
Syfaro
committed
Major documentation and code cleanup.
All documention is now less than 80 characters wide. Old methods now show deprecated warnings. The Values/Params/Method functions are now private. Types and configs have required and optional comments on them. Simplified some function logic.
1 parent 1ae7803 commit e8dfdee

File tree

5 files changed

+414
-306
lines changed

5 files changed

+414
-306
lines changed

README.md

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,22 @@
44
[![Travis](https://travis-ci.org/Syfaro/telegram-bot-api.svg)](https://travis-ci.org/Syfaro/telegram-bot-api)
55

66
All methods have been added, and all features should be available.
7-
If you want a feature that hasn't been added yet or something is broken, open an issue and I'll see what I can do.
7+
If you want a feature that hasn't been added yet or something is broken,
8+
open an issue and I'll see what I can do.
89

9-
All methods are fairly self explanatory, and reading the godoc page should explain everything. If something isn't clear, open an issue or submit a pull request.
10+
All methods are fairly self explanatory, and reading the godoc page should
11+
explain everything. If something isn't clear, open an issue or submit
12+
a pull request.
1013

11-
The scope of this project is just to provide a wrapper around the API without any additional features. There are other projects for creating something with plugins and command handlers without having to design all that yourself.
12-
13-
Note to previous users, there was just a large change that broke some methods. The main changes are that all the `Send*` functions have been replaced with a single `Send`, and `UpdatesChan` was renamed `GetUpdatesChan` and returns `(chan, err)` instead of storing the chan in `Updates`.
14+
The scope of this project is just to provide a wrapper around the API
15+
without any additional features. There are other projects for creating
16+
something with plugins and command handlers without having to design
17+
all that yourself.
1418

1519
## Example
1620

17-
This is a very simple bot that just displays any gotten updates, then replies it to that chat.
21+
This is a very simple bot that just displays any gotten updates,
22+
then replies it to that chat.
1823

1924
```go
2025
package main
@@ -50,7 +55,8 @@ func main() {
5055
}
5156
```
5257

53-
If you need to use webhooks for some reason (such as running on Google App Engine), you may use a slightly different method.
58+
If you need to use webhooks (if you wish to run on Google App Engine),
59+
you may use a slightly different method.
5460

5561
```go
5662
package main
@@ -85,8 +91,12 @@ func main() {
8591
}
8692
```
8793

88-
If you need, you may generate a self signed certficate, as this requires HTTPS / TLS. The above example tells Telegram that this is your certificate and that it should be trusted, even though it is not properly signed.
94+
If you need, you may generate a self signed certficate, as this requires
95+
HTTPS / TLS. The above example tells Telegram that this is your
96+
certificate and that it should be trusted, even though it is not
97+
properly signed.
8998

9099
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes
91100

92-
Now that [Let's Encrypt](https://letsencrypt.org) has entered public beta, you may wish to generate your free TLS certificate there.
101+
Now that [Let's Encrypt](https://letsencrypt.org) has entered public beta,
102+
you may wish to generate your free TLS certificate there.

bot.go

Lines changed: 59 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// Package tgbotapi has bindings for interacting with the Telegram Bot API.
1+
// Package tgbotapi has functions and types used for interacting with
2+
// the Telegram Bot API.
23
package tgbotapi
34

45
import (
@@ -17,7 +18,7 @@ import (
1718
"time"
1819
)
1920

20-
// BotAPI has methods for interacting with all of Telegram's Bot API endpoints.
21+
// BotAPI allows you to interact with the Telegram Bot API.
2122
type BotAPI struct {
2223
Token string `json:"token"`
2324
Debug bool `json:"debug"`
@@ -26,13 +27,16 @@ type BotAPI struct {
2627
}
2728

2829
// NewBotAPI creates a new BotAPI instance.
29-
// Requires a token, provided by @BotFather on Telegram
30+
//
31+
// It requires a token, provided by @BotFather on Telegram.
3032
func NewBotAPI(token string) (*BotAPI, error) {
3133
return NewBotAPIWithClient(token, &http.Client{})
3234
}
3335

34-
// NewBotAPIWithClient creates a new BotAPI instance passing an http.Client.
35-
// Requires a token, provided by @BotFather on Telegram
36+
// NewBotAPIWithClient creates a new BotAPI instance
37+
// and allows you to pass a http.Client.
38+
//
39+
// It requires a token, provided by @BotFather on Telegram.
3640
func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
3741
bot := &BotAPI{
3842
Token: token,
@@ -50,9 +54,10 @@ func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
5054
}
5155

5256
// MakeRequest makes a request to a specific endpoint with our token.
53-
// All requests are POSTs because Telegram doesn't care, and it's easier.
5457
func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
55-
resp, err := bot.Client.PostForm(fmt.Sprintf(APIEndpoint, bot.Token, endpoint), params)
58+
method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
59+
60+
resp, err := bot.Client.PostForm(method, params)
5661
if err != nil {
5762
return APIResponse{}, err
5863
}
@@ -81,6 +86,7 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse,
8186
return apiResp, nil
8287
}
8388

89+
// makeMessageRequest makes a request to a method that returns a Message.
8490
func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
8591
resp, err := bot.MakeRequest(endpoint, params)
8692
if err != nil {
@@ -98,7 +104,11 @@ func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Messa
98104
// UploadFile makes a request to the API with a file.
99105
//
100106
// Requires the parameter to hold the file not be in the params.
101-
// File should be a string to a file path, a FileBytes struct, or a FileReader struct.
107+
// File should be a string to a file path, a FileBytes struct,
108+
// or a FileReader struct.
109+
//
110+
// Note that if your FileReader has a size set to -1, it will read
111+
// the file into memory to calculate a size.
102112
func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
103113
ms := multipartstreamer.New()
104114
ms.WriteFields(params)
@@ -139,7 +149,9 @@ func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldna
139149
return APIResponse{}, errors.New("bad file type")
140150
}
141151

142-
req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), nil)
152+
method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
153+
154+
req, err := http.NewRequest("POST", method, nil)
143155
if err != nil {
144156
return APIResponse{}, err
145157
}
@@ -173,7 +185,7 @@ func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldna
173185

174186
// GetFileDirectURL returns direct URL to file
175187
//
176-
// Requires fileID
188+
// It requires the FileID.
177189
func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
178190
file, err := bot.GetFile(FileConfig{fileID})
179191

@@ -186,7 +198,9 @@ func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
186198

187199
// GetMe fetches the currently authenticated bot.
188200
//
189-
// There are no parameters for this method.
201+
// This method is called upon creation to validate the token,
202+
// and so you may get this data from BotAPI.Self without the need for
203+
// another request.
190204
func (bot *BotAPI) GetMe() (User, error) {
191205
resp, err := bot.MakeRequest("getMe", nil)
192206
if err != nil {
@@ -201,16 +215,16 @@ func (bot *BotAPI) GetMe() (User, error) {
201215
return user, nil
202216
}
203217

204-
// IsMessageToMe returns true if message directed to this bot
218+
// IsMessageToMe returns true if message directed to this bot.
205219
//
206-
// Requires message
220+
// It requires the Message.
207221
func (bot *BotAPI) IsMessageToMe(message Message) bool {
208222
return strings.Contains(message.Text, "@"+bot.Self.UserName)
209223
}
210224

211-
// Send will send event(Message, Photo, Audio, ChatAction, anything) to Telegram
225+
// Send will send a Chattable item to Telegram.
212226
//
213-
// Requires Chattable
227+
// It requires the Chattable to send.
214228
func (bot *BotAPI) Send(c Chattable) (Message, error) {
215229
switch c.(type) {
216230
case Fileable:
@@ -220,15 +234,19 @@ func (bot *BotAPI) Send(c Chattable) (Message, error) {
220234
}
221235
}
222236

237+
// debugLog checks if the bot is currently running in debug mode, and if
238+
// so will display information about the request and response in the
239+
// debug log.
223240
func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
224241
if bot.Debug {
225242
log.Printf("%s req : %+v\n", context, v)
226243
log.Printf("%s resp: %+v\n", context, message)
227244
}
228245
}
229246

247+
// sendExisting will send a Message with an existing file to Telegram.
230248
func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
231-
v, err := config.Values()
249+
v, err := config.values()
232250

233251
if err != nil {
234252
return Message{}, err
@@ -242,44 +260,46 @@ func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error)
242260
return message, nil
243261
}
244262

263+
// uploadAndSend will send a Message with a new file to Telegram.
245264
func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
246-
params, err := config.Params()
265+
params, err := config.params()
247266
if err != nil {
248267
return Message{}, err
249268
}
250269

251-
file := config.GetFile()
270+
file := config.getFile()
252271

253-
resp, err := bot.UploadFile(method, params, config.Name(), file)
272+
resp, err := bot.UploadFile(method, params, config.name(), file)
254273
if err != nil {
255274
return Message{}, err
256275
}
257276

258277
var message Message
259278
json.Unmarshal(resp.Result, &message)
260279

261-
if bot.Debug {
262-
log.Printf("%s resp: %+v\n", method, message)
263-
}
280+
bot.debugLog(method, nil, message)
264281

265282
return message, nil
266283
}
267284

285+
// sendFile determines if the file is using an existing file or uploading
286+
// a new file, then sends it as needed.
268287
func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
269-
if config.UseExistingFile() {
270-
return bot.sendExisting(config.Method(), config)
288+
if config.useExistingFile() {
289+
return bot.sendExisting(config.method(), config)
271290
}
272291

273-
return bot.uploadAndSend(config.Method(), config)
292+
return bot.uploadAndSend(config.method(), config)
274293
}
275294

295+
// sendChattable sends a Chattable.
276296
func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
277-
v, err := config.Values()
297+
v, err := config.values()
278298
if err != nil {
279299
return Message{}, err
280300
}
281301

282-
message, err := bot.makeMessageRequest(config.Method(), v)
302+
message, err := bot.makeMessageRequest(config.method(), v)
283303

284304
if err != nil {
285305
return Message{}, err
@@ -290,7 +310,7 @@ func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
290310

291311
// GetUserProfilePhotos gets a user's profile photos.
292312
//
293-
// Requires UserID.
313+
// It requires UserID.
294314
// Offset and Limit are optional.
295315
func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
296316
v := url.Values{}
@@ -315,7 +335,7 @@ func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserPro
315335
return profilePhotos, nil
316336
}
317337

318-
// GetFile returns a file_id required to download a file.
338+
// GetFile returns a File which can download a file from Telegram.
319339
//
320340
// Requires FileID.
321341
func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
@@ -339,8 +359,9 @@ func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
339359
// If a WebHook is set, this will not return any data!
340360
//
341361
// Offset, Limit, and Timeout are optional.
342-
// To not get old items, set Offset to one higher than the previous item.
343-
// Set Timeout to a large number to reduce requests and get responses instantly.
362+
// To avoid stale items, set Offset to one higher than the previous item.
363+
// Set Timeout to a large number to reduce requests so you can get updates
364+
// instantly instead of having to wait between requests.
344365
func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
345366
v := url.Values{}
346367
if config.Offset > 0 {
@@ -361,24 +382,22 @@ func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
361382
var updates []Update
362383
json.Unmarshal(resp.Result, &updates)
363384

364-
if bot.Debug {
365-
log.Printf("getUpdates: %+v\n", updates)
366-
}
385+
bot.debugLog("getUpdates", v, updates)
367386

368387
return updates, nil
369388
}
370389

371-
// RemoveWebhook removes webhook
372-
//
373-
// There are no parameters for this method.
390+
// RemoveWebhook unsets the webhook.
374391
func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
375392
return bot.MakeRequest("setWebhook", url.Values{})
376393
}
377394

378395
// SetWebhook sets a webhook.
396+
//
379397
// If this is set, GetUpdates will not get any data!
380398
//
381-
// Requires URL OR to set Clear to true.
399+
// If you do not have a legitmate TLS certificate, you need to include
400+
// your self signed certificate with the config.
382401
func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
383402
if config.Certificate == nil {
384403
v := url.Values{}
@@ -406,8 +425,6 @@ func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
406425
}
407426

408427
// GetUpdatesChan starts and returns a channel for getting updates.
409-
//
410-
// Requires UpdateConfig
411428
func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (<-chan Update, error) {
412429
updatesChan := make(chan Update, 100)
413430

@@ -453,6 +470,8 @@ func (bot *BotAPI) ListenForWebhook(pattern string) (<-chan Update, http.Handler
453470
}
454471

455472
// AnswerInlineQuery sends a response to an inline query.
473+
//
474+
// Note that you must respond to an inline query within 30 seconds.
456475
func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
457476
v := url.Values{}
458477

0 commit comments

Comments
 (0)