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