bot.go (view raw)
1// Package tgbotapi has functions and types used for interacting with
2// the Telegram Bot API.
3package tgbotapi
4
5import (
6 "bytes"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io/ioutil"
11 "log"
12 "net/http"
13 "net/url"
14 "os"
15 "strconv"
16 "strings"
17 "time"
18
19 "github.com/technoweenie/multipartstreamer"
20)
21
22// BotAPI allows you to interact with the Telegram Bot API.
23type BotAPI struct {
24 Token string `json:"token"`
25 Debug bool `json:"debug"`
26 Self User `json:"-"`
27 Client *http.Client `json:"-"`
28}
29
30// NewBotAPI creates a new BotAPI instance.
31//
32// It requires a token, provided by @BotFather on Telegram.
33func NewBotAPI(token string) (*BotAPI, error) {
34 return NewBotAPIWithClient(token, &http.Client{})
35}
36
37// NewBotAPIWithClient creates a new BotAPI instance
38// and allows you to pass a http.Client.
39//
40// It requires a token, provided by @BotFather on Telegram.
41func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
42 bot := &BotAPI{
43 Token: token,
44 Client: client,
45 }
46
47 self, err := bot.GetMe()
48 if err != nil {
49 return &BotAPI{}, err
50 }
51
52 bot.Self = self
53
54 return bot, nil
55}
56
57// MakeRequest makes a request to a specific endpoint with our token.
58func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
59 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
60
61 resp, err := bot.Client.PostForm(method, params)
62 if err != nil {
63 return APIResponse{}, err
64 }
65 defer resp.Body.Close()
66
67 if resp.StatusCode == http.StatusForbidden {
68 return APIResponse{}, errors.New(ErrAPIForbidden)
69 }
70
71 bytes, err := ioutil.ReadAll(resp.Body)
72 if err != nil {
73 return APIResponse{}, err
74 }
75
76 if bot.Debug {
77 log.Println(endpoint, string(bytes))
78 }
79
80 var apiResp APIResponse
81 json.Unmarshal(bytes, &apiResp)
82
83 if !apiResp.Ok {
84 return apiResp, errors.New(apiResp.Description)
85 }
86
87 return apiResp, nil
88}
89
90// makeMessageRequest makes a request to a method that returns a Message.
91func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
92 resp, err := bot.MakeRequest(endpoint, params)
93 if err != nil {
94 return Message{}, err
95 }
96
97 var message Message
98 json.Unmarshal(resp.Result, &message)
99
100 bot.debugLog(endpoint, params, message)
101
102 return message, nil
103}
104
105// UploadFile makes a request to the API with a file.
106//
107// Requires the parameter to hold the file not be in the params.
108// File should be a string to a file path, a FileBytes struct,
109// a FileReader struct, or a url.URL.
110//
111// Note that if your FileReader has a size set to -1, it will read
112// the file into memory to calculate a size.
113func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
114 ms := multipartstreamer.New()
115
116 switch f := file.(type) {
117 case string:
118 ms.WriteFields(params)
119
120 fileHandle, err := os.Open(f)
121 if err != nil {
122 return APIResponse{}, err
123 }
124 defer fileHandle.Close()
125
126 fi, err := os.Stat(f)
127 if err != nil {
128 return APIResponse{}, err
129 }
130
131 ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
132 case FileBytes:
133 ms.WriteFields(params)
134
135 buf := bytes.NewBuffer(f.Bytes)
136 ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
137 case FileReader:
138 ms.WriteFields(params)
139
140 if f.Size != -1 {
141 ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
142
143 break
144 }
145
146 data, err := ioutil.ReadAll(f.Reader)
147 if err != nil {
148 return APIResponse{}, err
149 }
150
151 buf := bytes.NewBuffer(data)
152
153 ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
154 case url.URL:
155 params[fieldname] = f.String()
156
157 ms.WriteFields(params)
158 default:
159 return APIResponse{}, errors.New(ErrBadFileType)
160 }
161
162 method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint)
163
164 req, err := http.NewRequest("POST", method, nil)
165 if err != nil {
166 return APIResponse{}, err
167 }
168
169 ms.SetupRequest(req)
170
171 res, err := bot.Client.Do(req)
172 if err != nil {
173 return APIResponse{}, err
174 }
175 defer res.Body.Close()
176
177 bytes, err := ioutil.ReadAll(res.Body)
178 if err != nil {
179 return APIResponse{}, err
180 }
181
182 if bot.Debug {
183 log.Println(string(bytes))
184 }
185
186 var apiResp APIResponse
187 json.Unmarshal(bytes, &apiResp)
188
189 if !apiResp.Ok {
190 return APIResponse{}, errors.New(apiResp.Description)
191 }
192
193 return apiResp, nil
194}
195
196// GetFileDirectURL returns direct URL to file
197//
198// It requires the FileID.
199func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
200 file, err := bot.GetFile(FileConfig{fileID})
201
202 if err != nil {
203 return "", err
204 }
205
206 return file.Link(bot.Token), nil
207}
208
209// GetMe fetches the currently authenticated bot.
210//
211// This method is called upon creation to validate the token,
212// and so you may get this data from BotAPI.Self without the need for
213// another request.
214func (bot *BotAPI) GetMe() (User, error) {
215 resp, err := bot.MakeRequest("getMe", nil)
216 if err != nil {
217 return User{}, err
218 }
219
220 var user User
221 json.Unmarshal(resp.Result, &user)
222
223 bot.debugLog("getMe", nil, user)
224
225 return user, nil
226}
227
228// IsMessageToMe returns true if message directed to this bot.
229//
230// It requires the Message.
231func (bot *BotAPI) IsMessageToMe(message Message) bool {
232 return strings.Contains(message.Text, "@"+bot.Self.UserName)
233}
234
235// Send will send a Chattable item to Telegram.
236//
237// It requires the Chattable to send.
238func (bot *BotAPI) Send(c Chattable) (Message, error) {
239 switch c.(type) {
240 case Fileable:
241 return bot.sendFile(c.(Fileable))
242 default:
243 return bot.sendChattable(c)
244 }
245}
246
247// debugLog checks if the bot is currently running in debug mode, and if
248// so will display information about the request and response in the
249// debug log.
250func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) {
251 if bot.Debug {
252 log.Printf("%s req : %+v\n", context, v)
253 log.Printf("%s resp: %+v\n", context, message)
254 }
255}
256
257// sendExisting will send a Message with an existing file to Telegram.
258func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
259 v, err := config.values()
260
261 if err != nil {
262 return Message{}, err
263 }
264
265 message, err := bot.makeMessageRequest(method, v)
266 if err != nil {
267 return Message{}, err
268 }
269
270 return message, nil
271}
272
273// uploadAndSend will send a Message with a new file to Telegram.
274func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
275 params, err := config.params()
276 if err != nil {
277 return Message{}, err
278 }
279
280 file := config.getFile()
281
282 resp, err := bot.UploadFile(method, params, config.name(), file)
283 if err != nil {
284 return Message{}, err
285 }
286
287 var message Message
288 json.Unmarshal(resp.Result, &message)
289
290 bot.debugLog(method, nil, message)
291
292 return message, nil
293}
294
295// sendFile determines if the file is using an existing file or uploading
296// a new file, then sends it as needed.
297func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
298 if config.useExistingFile() {
299 return bot.sendExisting(config.method(), config)
300 }
301
302 return bot.uploadAndSend(config.method(), config)
303}
304
305// sendChattable sends a Chattable.
306func (bot *BotAPI) sendChattable(config Chattable) (Message, error) {
307 v, err := config.values()
308 if err != nil {
309 return Message{}, err
310 }
311
312 message, err := bot.makeMessageRequest(config.method(), v)
313
314 if err != nil {
315 return Message{}, err
316 }
317
318 return message, nil
319}
320
321// GetUserProfilePhotos gets a user's profile photos.
322//
323// It requires UserID.
324// Offset and Limit are optional.
325func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
326 v := url.Values{}
327 v.Add("user_id", strconv.Itoa(config.UserID))
328 if config.Offset != 0 {
329 v.Add("offset", strconv.Itoa(config.Offset))
330 }
331 if config.Limit != 0 {
332 v.Add("limit", strconv.Itoa(config.Limit))
333 }
334
335 resp, err := bot.MakeRequest("getUserProfilePhotos", v)
336 if err != nil {
337 return UserProfilePhotos{}, err
338 }
339
340 var profilePhotos UserProfilePhotos
341 json.Unmarshal(resp.Result, &profilePhotos)
342
343 bot.debugLog("GetUserProfilePhoto", v, profilePhotos)
344
345 return profilePhotos, nil
346}
347
348// GetFile returns a File which can download a file from Telegram.
349//
350// Requires FileID.
351func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
352 v := url.Values{}
353 v.Add("file_id", config.FileID)
354
355 resp, err := bot.MakeRequest("getFile", v)
356 if err != nil {
357 return File{}, err
358 }
359
360 var file File
361 json.Unmarshal(resp.Result, &file)
362
363 bot.debugLog("GetFile", v, file)
364
365 return file, nil
366}
367
368// GetUpdates fetches updates.
369// If a WebHook is set, this will not return any data!
370//
371// Offset, Limit, and Timeout are optional.
372// To avoid stale items, set Offset to one higher than the previous item.
373// Set Timeout to a large number to reduce requests so you can get updates
374// instantly instead of having to wait between requests.
375func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
376 v := url.Values{}
377 if config.Offset != 0 {
378 v.Add("offset", strconv.Itoa(config.Offset))
379 }
380 if config.Limit > 0 {
381 v.Add("limit", strconv.Itoa(config.Limit))
382 }
383 if config.Timeout > 0 {
384 v.Add("timeout", strconv.Itoa(config.Timeout))
385 }
386
387 resp, err := bot.MakeRequest("getUpdates", v)
388 if err != nil {
389 return []Update{}, err
390 }
391
392 var updates []Update
393 json.Unmarshal(resp.Result, &updates)
394
395 bot.debugLog("getUpdates", v, updates)
396
397 return updates, nil
398}
399
400// RemoveWebhook unsets the webhook.
401func (bot *BotAPI) RemoveWebhook() (APIResponse, error) {
402 return bot.MakeRequest("setWebhook", url.Values{})
403}
404
405// SetWebhook sets a webhook.
406//
407// If this is set, GetUpdates will not get any data!
408//
409// If you do not have a legitimate TLS certificate, you need to include
410// your self signed certificate with the config.
411func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
412
413 if config.Certificate == nil {
414 v := url.Values{}
415 v.Add("url", config.URL.String())
416 if config.MaxConnections != 0 {
417 v.Add("max_connections", strconv.Itoa(config.MaxConnections))
418 }
419
420 return bot.MakeRequest("setWebhook", v)
421 }
422
423 params := make(map[string]string)
424 params["url"] = config.URL.String()
425 if config.MaxConnections != 0 {
426 params["max_connections"] = strconv.Itoa(config.MaxConnections)
427 }
428
429 resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
430 if err != nil {
431 return APIResponse{}, err
432 }
433
434 var apiResp APIResponse
435 json.Unmarshal(resp.Result, &apiResp)
436
437 if bot.Debug {
438 log.Printf("setWebhook resp: %+v\n", apiResp)
439 }
440
441 return apiResp, nil
442}
443
444// GetWebhookInfo allows you to fetch information about a webhook and if
445// one currently is set, along with pending update count and error messages.
446func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
447 resp, err := bot.MakeRequest("getWebhookInfo", url.Values{})
448 if err != nil {
449 return WebhookInfo{}, err
450 }
451
452 var info WebhookInfo
453 err = json.Unmarshal(resp.Result, &info)
454
455 return info, err
456}
457
458// GetUpdatesChan starts and returns a channel for getting updates.
459func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) {
460 ch := make(chan Update, 100)
461
462 go func() {
463 for {
464 updates, err := bot.GetUpdates(config)
465 if err != nil {
466 log.Println(err)
467 log.Println("Failed to get updates, retrying in 3 seconds...")
468 time.Sleep(time.Second * 3)
469
470 continue
471 }
472
473 for _, update := range updates {
474 if update.UpdateID >= config.Offset {
475 config.Offset = update.UpdateID + 1
476 ch <- update
477 }
478 }
479 }
480 }()
481
482 return ch, nil
483}
484
485// ListenForWebhook registers a http handler for a webhook.
486func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
487 ch := make(chan Update, 100)
488
489 http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
490 bytes, _ := ioutil.ReadAll(r.Body)
491
492 var update Update
493 json.Unmarshal(bytes, &update)
494
495 ch <- update
496 })
497
498 return ch
499}
500
501// AnswerInlineQuery sends a response to an inline query.
502//
503// Note that you must respond to an inline query within 30 seconds.
504func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) {
505 v := url.Values{}
506
507 v.Add("inline_query_id", config.InlineQueryID)
508 v.Add("cache_time", strconv.Itoa(config.CacheTime))
509 v.Add("is_personal", strconv.FormatBool(config.IsPersonal))
510 v.Add("next_offset", config.NextOffset)
511 data, err := json.Marshal(config.Results)
512 if err != nil {
513 return APIResponse{}, err
514 }
515 v.Add("results", string(data))
516 v.Add("switch_pm_text", config.SwitchPMText)
517 v.Add("switch_pm_parameter", config.SwitchPMParameter)
518
519 bot.debugLog("answerInlineQuery", v, nil)
520
521 return bot.MakeRequest("answerInlineQuery", v)
522}
523
524// AnswerCallbackQuery sends a response to an inline query callback.
525func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
526 v := url.Values{}
527
528 v.Add("callback_query_id", config.CallbackQueryID)
529 if config.Text != "" {
530 v.Add("text", config.Text)
531 }
532 v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
533 if config.URL != "" {
534 v.Add("url", config.URL)
535 }
536 v.Add("cache_time", strconv.Itoa(config.CacheTime))
537
538 bot.debugLog("answerCallbackQuery", v, nil)
539
540 return bot.MakeRequest("answerCallbackQuery", v)
541}
542
543// KickChatMember kicks a user from a chat. Note that this only will work
544// in supergroups, and requires the bot to be an admin. Also note they
545// will be unable to rejoin until they are unbanned.
546func (bot *BotAPI) KickChatMember(config ChatMemberConfig) (APIResponse, error) {
547 v := url.Values{}
548
549 if config.SuperGroupUsername == "" {
550 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
551 } else {
552 v.Add("chat_id", config.SuperGroupUsername)
553 }
554 v.Add("user_id", strconv.Itoa(config.UserID))
555
556 bot.debugLog("kickChatMember", v, nil)
557
558 return bot.MakeRequest("kickChatMember", v)
559}
560
561// LeaveChat makes the bot leave the chat.
562func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) {
563 v := url.Values{}
564
565 if config.SuperGroupUsername == "" {
566 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
567 } else {
568 v.Add("chat_id", config.SuperGroupUsername)
569 }
570
571 bot.debugLog("leaveChat", v, nil)
572
573 return bot.MakeRequest("leaveChat", v)
574}
575
576// GetChat gets information about a chat.
577func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) {
578 v := url.Values{}
579
580 if config.SuperGroupUsername == "" {
581 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
582 } else {
583 v.Add("chat_id", config.SuperGroupUsername)
584 }
585
586 resp, err := bot.MakeRequest("getChat", v)
587 if err != nil {
588 return Chat{}, err
589 }
590
591 var chat Chat
592 err = json.Unmarshal(resp.Result, &chat)
593
594 bot.debugLog("getChat", v, chat)
595
596 return chat, err
597}
598
599// GetChatAdministrators gets a list of administrators in the chat.
600//
601// If none have been appointed, only the creator will be returned.
602// Bots are not shown, even if they are an administrator.
603func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) {
604 v := url.Values{}
605
606 if config.SuperGroupUsername == "" {
607 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
608 } else {
609 v.Add("chat_id", config.SuperGroupUsername)
610 }
611
612 resp, err := bot.MakeRequest("getChatAdministrators", v)
613 if err != nil {
614 return []ChatMember{}, err
615 }
616
617 var members []ChatMember
618 err = json.Unmarshal(resp.Result, &members)
619
620 bot.debugLog("getChatAdministrators", v, members)
621
622 return members, err
623}
624
625// GetChatMembersCount gets the number of users in a chat.
626func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) {
627 v := url.Values{}
628
629 if config.SuperGroupUsername == "" {
630 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
631 } else {
632 v.Add("chat_id", config.SuperGroupUsername)
633 }
634
635 resp, err := bot.MakeRequest("getChatMembersCount", v)
636 if err != nil {
637 return -1, err
638 }
639
640 var count int
641 err = json.Unmarshal(resp.Result, &count)
642
643 bot.debugLog("getChatMembersCount", v, count)
644
645 return count, err
646}
647
648// GetChatMember gets a specific chat member.
649func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) {
650 v := url.Values{}
651
652 if config.SuperGroupUsername == "" {
653 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
654 } else {
655 v.Add("chat_id", config.SuperGroupUsername)
656 }
657 v.Add("user_id", strconv.Itoa(config.UserID))
658
659 resp, err := bot.MakeRequest("getChatMember", v)
660 if err != nil {
661 return ChatMember{}, err
662 }
663
664 var member ChatMember
665 err = json.Unmarshal(resp.Result, &member)
666
667 bot.debugLog("getChatMember", v, member)
668
669 return member, err
670}
671
672// UnbanChatMember unbans a user from a chat. Note that this only will work
673// in supergroups, and requires the bot to be an admin.
674func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) {
675 v := url.Values{}
676
677 if config.SuperGroupUsername == "" {
678 v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
679 } else {
680 v.Add("chat_id", config.SuperGroupUsername)
681 }
682 v.Add("user_id", strconv.Itoa(config.UserID))
683
684 bot.debugLog("unbanChatMember", v, nil)
685
686 return bot.MakeRequest("unbanChatMember", v)
687}
688
689// GetGameHighScores allows you to get the high scores for a game.
690func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
691 v, _ := config.values()
692
693 resp, err := bot.MakeRequest(config.method(), v)
694 if err != nil {
695 return []GameHighScore{}, err
696 }
697
698 var highScores []GameHighScore
699 err = json.Unmarshal(resp.Result, &highScores)
700
701 return highScores, err
702}