all repos — telegram-bot-api @ d3f7ac7197622f37672b08a9fec9743132cbf802

Golang bindings for the Telegram Bot API

bot.go (view raw)

  1// Package tgbotapi has bindings for interacting with the Telegram Bot API.
  2package tgbotapi
  3
  4import (
  5	"bytes"
  6	"encoding/json"
  7	"errors"
  8	"fmt"
  9	"github.com/technoweenie/multipartstreamer"
 10	"io/ioutil"
 11	"log"
 12	"net/http"
 13	"net/url"
 14	"os"
 15	"strconv"
 16	"time"
 17)
 18
 19// BotAPI has methods for interacting with all of Telegram's Bot API endpoints.
 20type BotAPI struct {
 21	Token   string       `json:"token"`
 22	Debug   bool         `json:"debug"`
 23	Self    User         `json:"-"`
 24	Updates chan Update  `json:"-"`
 25	Client  *http.Client `json:"-"`
 26}
 27
 28// NewBotAPI creates a new BotAPI instance.
 29// Requires a token, provided by @BotFather on Telegram
 30func NewBotAPI(token string) (*BotAPI, error) {
 31	return NewBotAPIWithClient(token, &http.Client{})
 32}
 33
 34// NewBotAPIWithClient creates a new BotAPI instance passing an http.Client.
 35// Requires a token, provided by @BotFather on Telegram
 36func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
 37	bot := &BotAPI{
 38		Token:  token,
 39		Client: client,
 40	}
 41
 42	self, err := bot.GetMe()
 43	if err != nil {
 44		return &BotAPI{}, err
 45	}
 46
 47	bot.Self = self
 48
 49	return bot, nil
 50}
 51
 52// 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.
 54func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
 55	resp, err := bot.Client.PostForm(fmt.Sprintf(APIEndpoint, bot.Token, endpoint), params)
 56	if err != nil {
 57		return APIResponse{}, err
 58	}
 59	defer resp.Body.Close()
 60
 61	if resp.StatusCode == http.StatusForbidden {
 62		return APIResponse{}, errors.New(APIForbidden)
 63	}
 64
 65	bytes, err := ioutil.ReadAll(resp.Body)
 66	if err != nil {
 67		return APIResponse{}, err
 68	}
 69
 70	if bot.Debug {
 71		log.Println(endpoint, string(bytes))
 72	}
 73
 74	var apiResp APIResponse
 75	json.Unmarshal(bytes, &apiResp)
 76
 77	if !apiResp.Ok {
 78		return APIResponse{}, errors.New(apiResp.Description)
 79	}
 80
 81	return apiResp, nil
 82}
 83
 84func (bot *BotAPI) MakeMessageRequest(endpoint string, params url.Values) (Message, error) {
 85	resp, err := bot.MakeRequest(endpoint, params)
 86	if err != nil {
 87		return Message{}, err
 88	}
 89
 90	var message Message
 91	json.Unmarshal(resp.Result, &message)
 92
 93	bot.DebugLog(endpoint, params, message)
 94
 95	return message, nil
 96}
 97
 98// UploadFile makes a request to the API with a file.
 99//
100// 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.
102func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) {
103	ms := multipartstreamer.New()
104	ms.WriteFields(params)
105
106	switch f := file.(type) {
107	case string:
108		fileHandle, err := os.Open(f)
109		if err != nil {
110			return APIResponse{}, err
111		}
112		defer fileHandle.Close()
113
114		fi, err := os.Stat(f)
115		if err != nil {
116			return APIResponse{}, err
117		}
118
119		ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
120	case FileBytes:
121		buf := bytes.NewBuffer(f.Bytes)
122		ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
123	case FileReader:
124		if f.Size == -1 {
125			data, err := ioutil.ReadAll(f.Reader)
126			if err != nil {
127				return APIResponse{}, err
128			}
129			buf := bytes.NewBuffer(data)
130
131			ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
132
133			break
134		}
135
136		ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
137	default:
138		return APIResponse{}, errors.New("bad file type")
139	}
140
141	req, err := http.NewRequest("POST", fmt.Sprintf(APIEndpoint, bot.Token, endpoint), nil)
142	ms.SetupRequest(req)
143	if err != nil {
144		return APIResponse{}, err
145	}
146
147	res, err := bot.Client.Do(req)
148	if err != nil {
149		return APIResponse{}, err
150	}
151	defer res.Body.Close()
152
153	bytes, err := ioutil.ReadAll(res.Body)
154	if err != nil {
155		return APIResponse{}, err
156	}
157
158	if bot.Debug {
159		log.Println(string(bytes[:]))
160	}
161
162	var apiResp APIResponse
163	json.Unmarshal(bytes, &apiResp)
164
165	if !apiResp.Ok {
166		return APIResponse{}, errors.New(apiResp.Description)
167	}
168
169	return apiResp, nil
170}
171
172// GetMe fetches the currently authenticated bot.
173//
174// There are no parameters for this method.
175func (bot *BotAPI) GetMe() (User, error) {
176	resp, err := bot.MakeRequest("getMe", nil)
177	if err != nil {
178		return User{}, err
179	}
180
181	var user User
182	json.Unmarshal(resp.Result, &user)
183
184	if bot.Debug {
185		log.Printf("getMe: %+v\n", user)
186	}
187
188	return user, nil
189}
190
191func (bot *BotAPI) Send(c BaseChat) error {
192	return nil
193}
194
195func (bot *BotAPI) DebugLog(context string, v url.Values, message interface{}) {
196	if bot.Debug {
197		log.Printf("%s req : %+v\n", context, v)
198		log.Printf("%s resp: %+v\n", context, message)
199	}
200}
201
202func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) {
203	v, err := config.Values()
204
205	if err != nil {
206		return Message{}, err
207	}
208
209	message, err := bot.MakeMessageRequest(method, v)
210	if err != nil {
211		return Message{}, err
212	}
213
214	return message, nil
215}
216
217func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
218	params, err := config.Params()
219	if err != nil {
220		return Message{}, err
221	}
222
223	file := config.GetFile()
224
225	resp, err := bot.UploadFile(method, params, config.Name(), file)
226	if err != nil {
227		return Message{}, err
228	}
229
230	var message Message
231	json.Unmarshal(resp.Result, &message)
232
233	if bot.Debug {
234		log.Printf("%s resp: %+v\n", method, message)
235	}
236
237	return message, nil
238}
239
240func (bot *BotAPI) sendFile(method string, config Fileable) (Message, error) {
241	if config.UseExistingFile() {
242		return bot.sendExisting(method, config)
243	}
244
245	return bot.uploadAndSend(method, config)
246}
247
248// SendMessage sends a Message to a chat.
249//
250// Requires ChatID and Text.
251// DisableWebPagePreview, ReplyToMessageID, and ReplyMarkup are optional.
252func (bot *BotAPI) SendMessage(config MessageConfig) (Message, error) {
253	v, err := config.Values()
254	if err != nil {
255		return Message{}, err
256	}
257
258	message, err := bot.MakeMessageRequest("SendMessage", v)
259
260	if err != nil {
261		return Message{}, err
262	}
263
264	return message, nil
265}
266
267// ForwardMessage forwards a message from one chat to another.
268//
269// Requires ChatID (destination), FromChatID (source), and MessageID.
270func (bot *BotAPI) ForwardMessage(config ForwardConfig) (Message, error) {
271	v, err := config.Values()
272	if err != nil {
273		return Message{}, err
274	}
275
276	message, err := bot.MakeMessageRequest("forwardMessage", v)
277	if err != nil {
278		return Message{}, err
279	}
280
281	return message, nil
282}
283
284// SendLocation sends a location to a chat.
285//
286// Requires ChatID, Latitude, and Longitude.
287// ReplyToMessageID and ReplyMarkup are optional.
288func (bot *BotAPI) SendLocation(config LocationConfig) (Message, error) {
289	v, err := config.Values()
290	if err != nil {
291		return Message{}, err
292	}
293
294	message, err := bot.MakeMessageRequest("sendLocation", v)
295	if err != nil {
296		return Message{}, err
297	}
298
299	return message, nil
300}
301
302// SendPhoto sends or uploads a photo to a chat.
303//
304// Requires ChatID and FileID OR File.
305// Caption, ReplyToMessageID, and ReplyMarkup are optional.
306// File should be either a string, FileBytes, or FileReader.
307func (bot *BotAPI) SendPhoto(config PhotoConfig) (Message, error) {
308	return bot.sendFile("SendPhoto", config)
309}
310
311// SendAudio sends or uploads an audio clip to a chat.
312// If using a file, the file must be in the .mp3 format.
313//
314// When the fields title and performer are both empty and
315// the mime-type of the file to be sent is not audio/mpeg,
316// the file must be an .ogg file encoded with OPUS.
317// You may use the tgutils.EncodeAudio func to assist you with this, if needed.
318//
319// Requires ChatID and FileID OR File.
320// ReplyToMessageID and ReplyMarkup are optional.
321// File should be either a string, FileBytes, or FileReader.
322func (bot *BotAPI) SendAudio(config AudioConfig) (Message, error) {
323	return bot.sendFile("sendAudio", config)
324}
325
326// SendDocument sends or uploads a document to a chat.
327//
328// Requires ChatID and FileID OR File.
329// ReplyToMessageID and ReplyMarkup are optional.
330// File should be either a string, FileBytes, or FileReader.
331func (bot *BotAPI) SendDocument(config DocumentConfig) (Message, error) {
332	return bot.sendFile("sendDocument", config)
333}
334
335// SendVoice sends or uploads a playable voice to a chat.
336// If using a file, the file must be encoded as an .ogg with OPUS.
337// You may use the tgutils.EncodeAudio func to assist you with this, if needed.
338//
339// Requires ChatID and FileID OR File.
340// ReplyToMessageID and ReplyMarkup are optional.
341// File should be either a string, FileBytes, or FileReader.
342func (bot *BotAPI) SendVoice(config VoiceConfig) (Message, error) {
343	return bot.sendFile("sendVoice", config)
344}
345
346// SendSticker sends or uploads a sticker to a chat.
347//
348// Requires ChatID and FileID OR File.
349// ReplyToMessageID and ReplyMarkup are optional.
350// File should be either a string, FileBytes, or FileReader.
351func (bot *BotAPI) SendSticker(config StickerConfig) (Message, error) {
352	return bot.sendFile("sendSticker", config)
353}
354
355// SendVideo sends or uploads a video to a chat.
356//
357// Requires ChatID and FileID OR File.
358// ReplyToMessageID and ReplyMarkup are optional.
359// File should be either a string, FileBytes, or FileReader.
360func (bot *BotAPI) SendVideo(config VideoConfig) (Message, error) {
361	return bot.sendFile("sendVideo", config)
362}
363
364// SendChatAction sets a current action in a chat.
365//
366// Requires ChatID and a valid Action (see Chat constants).
367func (bot *BotAPI) SendChatAction(config ChatActionConfig) error {
368	v, err := config.Values()
369	if err != nil {
370		return err
371	}
372
373	_, err = bot.MakeRequest("sendChatAction", v)
374	if err != nil {
375		return err
376	}
377
378	return nil
379}
380
381// GetUserProfilePhotos gets a user's profile photos.
382//
383// Requires UserID.
384// Offset and Limit are optional.
385func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
386	v := url.Values{}
387	v.Add("user_id", strconv.Itoa(config.UserID))
388	if config.Offset != 0 {
389		v.Add("offset", strconv.Itoa(config.Offset))
390	}
391	if config.Limit != 0 {
392		v.Add("limit", strconv.Itoa(config.Limit))
393	}
394
395	resp, err := bot.MakeRequest("getUserProfilePhotos", v)
396	if err != nil {
397		return UserProfilePhotos{}, err
398	}
399
400	var profilePhotos UserProfilePhotos
401	json.Unmarshal(resp.Result, &profilePhotos)
402
403	bot.DebugLog("GetUserProfilePhoto", v, profilePhotos)
404
405	return profilePhotos, nil
406}
407
408// GetFile returns a file_id required to download a file.
409//
410// Requires FileID.
411func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
412	v := url.Values{}
413	v.Add("file_id", config.FileID)
414
415	resp, err := bot.MakeRequest("getFile", v)
416	if err != nil {
417		return File{}, err
418	}
419
420	var file File
421	json.Unmarshal(resp.Result, &file)
422
423	bot.DebugLog("GetFile", v, file)
424
425	return file, nil
426}
427
428// GetUpdates fetches updates.
429// If a WebHook is set, this will not return any data!
430//
431// Offset, Limit, and Timeout are optional.
432// To not get old items, set Offset to one higher than the previous item.
433// Set Timeout to a large number to reduce requests and get responses instantly.
434func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
435	v := url.Values{}
436	if config.Offset > 0 {
437		v.Add("offset", strconv.Itoa(config.Offset))
438	}
439	if config.Limit > 0 {
440		v.Add("limit", strconv.Itoa(config.Limit))
441	}
442	if config.Timeout > 0 {
443		v.Add("timeout", strconv.Itoa(config.Timeout))
444	}
445
446	resp, err := bot.MakeRequest("getUpdates", v)
447	if err != nil {
448		return []Update{}, err
449	}
450
451	var updates []Update
452	json.Unmarshal(resp.Result, &updates)
453
454	if bot.Debug {
455		log.Printf("getUpdates: %+v\n", updates)
456	}
457
458	return updates, nil
459}
460
461// SetWebhook sets a webhook.
462// If this is set, GetUpdates will not get any data!
463//
464// Requires URL OR to set Clear to true.
465func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) {
466	if config.Certificate == nil {
467		v := url.Values{}
468		if !config.Clear {
469			v.Add("url", config.URL.String())
470		}
471
472		return bot.MakeRequest("setWebhook", v)
473	}
474
475	params := make(map[string]string)
476	params["url"] = config.URL.String()
477
478	resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate)
479	if err != nil {
480		return APIResponse{}, err
481	}
482
483	var apiResp APIResponse
484	json.Unmarshal(resp.Result, &apiResp)
485
486	if bot.Debug {
487		log.Printf("setWebhook resp: %+v\n", apiResp)
488	}
489
490	return apiResp, nil
491}
492
493// UpdatesChan starts a channel for getting updates.
494func (bot *BotAPI) UpdatesChan(config UpdateConfig) error {
495	bot.Updates = make(chan Update, 100)
496
497	go func() {
498		for {
499			updates, err := bot.GetUpdates(config)
500			if err != nil {
501				log.Println(err)
502				log.Println("Failed to get updates, retrying in 3 seconds...")
503				time.Sleep(time.Second * 3)
504
505				continue
506			}
507
508			for _, update := range updates {
509				if update.UpdateID >= config.Offset {
510					config.Offset = update.UpdateID + 1
511					bot.Updates <- update
512				}
513			}
514		}
515	}()
516
517	return nil
518}
519
520// ListenForWebhook registers a http handler for a webhook.
521func (bot *BotAPI) ListenForWebhook(pattern string) {
522	bot.Updates = make(chan Update, 100)
523
524	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
525		bytes, _ := ioutil.ReadAll(r.Body)
526
527		var update Update
528		json.Unmarshal(bytes, &update)
529
530		bot.Updates <- update
531	})
532}