all repos — telegram-bot-api @ 0a57807db79efce7f6719fbb2c0e0f83fda79aec

Golang bindings for the Telegram Bot API

configs.go (view raw)

  1package tgbotapi
  2
  3import (
  4	"encoding/json"
  5	"io"
  6	"net/url"
  7	"strconv"
  8)
  9
 10// Telegram constants
 11const (
 12	// APIEndpoint is the endpoint for all API methods,
 13	// with formatting for Sprintf.
 14	APIEndpoint = "https://api.telegram.org/bot%s/%s"
 15	// FileEndpoint is the endpoint for downloading a file from Telegram.
 16	FileEndpoint = "https://api.telegram.org/file/bot%s/%s"
 17)
 18
 19// Constant values for ChatActions
 20const (
 21	ChatTyping         = "typing"
 22	ChatUploadPhoto    = "upload_photo"
 23	ChatRecordVideo    = "record_video"
 24	ChatUploadVideo    = "upload_video"
 25	ChatRecordAudio    = "record_audio"
 26	ChatUploadAudio    = "upload_audio"
 27	ChatUploadDocument = "upload_document"
 28	ChatFindLocation   = "find_location"
 29)
 30
 31// API errors
 32const (
 33	// ErrAPIForbidden happens when a token is bad
 34	ErrAPIForbidden = "forbidden"
 35)
 36
 37// Constant values for ParseMode in MessageConfig
 38const (
 39	ModeMarkdown = "Markdown"
 40	ModeHTML     = "HTML"
 41)
 42
 43// Library errors
 44const (
 45	// ErrBadFileType happens when you pass an unknown type
 46	ErrBadFileType = "bad file type"
 47	ErrBadURL      = "bad or empty url"
 48)
 49
 50// Chattable is any config type that can be sent.
 51type Chattable interface {
 52	values() (url.Values, error)
 53	method() string
 54}
 55
 56// Fileable is any config type that can be sent that includes a file.
 57type Fileable interface {
 58	Chattable
 59	params() (map[string]string, error)
 60	name() string
 61	getFile() interface{}
 62	useExistingFile() bool
 63}
 64
 65// BaseChat is base type for all chat config types.
 66type BaseChat struct {
 67	ChatID              int64 // required
 68	ChannelUsername     string
 69	ReplyToMessageID    int
 70	ReplyMarkup         interface{}
 71	DisableNotification bool
 72}
 73
 74// values returns url.Values representation of BaseChat
 75func (chat *BaseChat) values() (url.Values, error) {
 76	v := url.Values{}
 77	if chat.ChannelUsername != "" {
 78		v.Add("chat_id", chat.ChannelUsername)
 79	} else {
 80		v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10))
 81	}
 82
 83	if chat.ReplyToMessageID != 0 {
 84		v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID))
 85	}
 86
 87	if chat.ReplyMarkup != nil {
 88		data, err := json.Marshal(chat.ReplyMarkup)
 89		if err != nil {
 90			return v, err
 91		}
 92
 93		v.Add("reply_markup", string(data))
 94	}
 95
 96	v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification))
 97
 98	return v, nil
 99}
100
101// BaseFile is a base type for all file config types.
102type BaseFile struct {
103	BaseChat
104	File        interface{}
105	FileID      string
106	UseExisting bool
107	MimeType    string
108	FileSize    int
109}
110
111// params returns a map[string]string representation of BaseFile.
112func (file BaseFile) params() (map[string]string, error) {
113	params := make(map[string]string)
114
115	if file.ChannelUsername != "" {
116		params["chat_id"] = file.ChannelUsername
117	} else {
118		params["chat_id"] = strconv.FormatInt(file.ChatID, 10)
119	}
120
121	if file.ReplyToMessageID != 0 {
122		params["reply_to_message_id"] = strconv.Itoa(file.ReplyToMessageID)
123	}
124
125	if file.ReplyMarkup != nil {
126		data, err := json.Marshal(file.ReplyMarkup)
127		if err != nil {
128			return params, err
129		}
130
131		params["reply_markup"] = string(data)
132	}
133
134	if file.MimeType != "" {
135		params["mime_type"] = file.MimeType
136	}
137
138	if file.FileSize > 0 {
139		params["file_size"] = strconv.Itoa(file.FileSize)
140	}
141
142	params["disable_notification"] = strconv.FormatBool(file.DisableNotification)
143
144	return params, nil
145}
146
147// getFile returns the file.
148func (file BaseFile) getFile() interface{} {
149	return file.File
150}
151
152// useExistingFile returns if the BaseFile has already been uploaded.
153func (file BaseFile) useExistingFile() bool {
154	return file.UseExisting
155}
156
157// BaseEdit is base type of all chat edits.
158type BaseEdit struct {
159	ChatID          int64
160	ChannelUsername string
161	MessageID       int
162	InlineMessageID string
163	ReplyMarkup     *InlineKeyboardMarkup
164}
165
166func (edit BaseEdit) values() (url.Values, error) {
167	v := url.Values{}
168
169	if edit.InlineMessageID == "" {
170		if edit.ChannelUsername != "" {
171			v.Add("chat_id", edit.ChannelUsername)
172		} else {
173			v.Add("chat_id", strconv.FormatInt(edit.ChatID, 10))
174		}
175		v.Add("message_id", strconv.Itoa(edit.MessageID))
176	} else {
177		v.Add("inline_message_id", edit.InlineMessageID)
178	}
179
180	if edit.ReplyMarkup != nil {
181		data, err := json.Marshal(edit.ReplyMarkup)
182		if err != nil {
183			return v, err
184		}
185		v.Add("reply_markup", string(data))
186	}
187
188	return v, nil
189}
190
191// MessageConfig contains information about a SendMessage request.
192type MessageConfig struct {
193	BaseChat
194	Text                  string
195	ParseMode             string
196	DisableWebPagePreview bool
197}
198
199// values returns a url.Values representation of MessageConfig.
200func (config MessageConfig) values() (url.Values, error) {
201	v, _ := config.BaseChat.values()
202	v.Add("text", config.Text)
203	v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview))
204	if config.ParseMode != "" {
205		v.Add("parse_mode", config.ParseMode)
206	}
207
208	return v, nil
209}
210
211// method returns Telegram API method name for sending Message.
212func (config MessageConfig) method() string {
213	return "sendMessage"
214}
215
216// ForwardConfig contains information about a ForwardMessage request.
217type ForwardConfig struct {
218	BaseChat
219	FromChatID          int64 // required
220	FromChannelUsername string
221	MessageID           int // required
222}
223
224// values returns a url.Values representation of ForwardConfig.
225func (config ForwardConfig) values() (url.Values, error) {
226	v, _ := config.BaseChat.values()
227	v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10))
228	v.Add("message_id", strconv.Itoa(config.MessageID))
229	return v, nil
230}
231
232// method returns Telegram API method name for sending Forward.
233func (config ForwardConfig) method() string {
234	return "forwardMessage"
235}
236
237// PhotoConfig contains information about a SendPhoto request.
238type PhotoConfig struct {
239	BaseFile
240	Caption string
241}
242
243// Params returns a map[string]string representation of PhotoConfig.
244func (config PhotoConfig) params() (map[string]string, error) {
245	params, _ := config.BaseFile.params()
246
247	if config.Caption != "" {
248		params["caption"] = config.Caption
249	}
250
251	return params, nil
252}
253
254// Values returns a url.Values representation of PhotoConfig.
255func (config PhotoConfig) values() (url.Values, error) {
256	v, _ := config.BaseChat.values()
257
258	v.Add(config.name(), config.FileID)
259	if config.Caption != "" {
260		v.Add("caption", config.Caption)
261	}
262	return v, nil
263}
264
265// name returns the field name for the Photo.
266func (config PhotoConfig) name() string {
267	return "photo"
268}
269
270// method returns Telegram API method name for sending Photo.
271func (config PhotoConfig) method() string {
272	return "sendPhoto"
273}
274
275// AudioConfig contains information about a SendAudio request.
276type AudioConfig struct {
277	BaseFile
278	Caption   string
279	Duration  int
280	Performer string
281	Title     string
282}
283
284// values returns a url.Values representation of AudioConfig.
285func (config AudioConfig) values() (url.Values, error) {
286	v, _ := config.BaseChat.values()
287
288	v.Add(config.name(), config.FileID)
289	if config.Duration != 0 {
290		v.Add("duration", strconv.Itoa(config.Duration))
291	}
292
293	if config.Performer != "" {
294		v.Add("performer", config.Performer)
295	}
296	if config.Title != "" {
297		v.Add("title", config.Title)
298	}
299	if config.Caption != "" {
300		v.Add("caption", config.Caption)
301	}
302
303	return v, nil
304}
305
306// params returns a map[string]string representation of AudioConfig.
307func (config AudioConfig) params() (map[string]string, error) {
308	params, _ := config.BaseFile.params()
309
310	if config.Duration != 0 {
311		params["duration"] = strconv.Itoa(config.Duration)
312	}
313
314	if config.Performer != "" {
315		params["performer"] = config.Performer
316	}
317	if config.Title != "" {
318		params["title"] = config.Title
319	}
320	if config.Caption != "" {
321		params["caption"] = config.Caption
322	}
323
324	return params, nil
325}
326
327// name returns the field name for the Audio.
328func (config AudioConfig) name() string {
329	return "audio"
330}
331
332// method returns Telegram API method name for sending Audio.
333func (config AudioConfig) method() string {
334	return "sendAudio"
335}
336
337// DocumentConfig contains information about a SendDocument request.
338type DocumentConfig struct {
339	BaseFile
340}
341
342// values returns a url.Values representation of DocumentConfig.
343func (config DocumentConfig) values() (url.Values, error) {
344	v, _ := config.BaseChat.values()
345
346	v.Add(config.name(), config.FileID)
347
348	return v, nil
349}
350
351// params returns a map[string]string representation of DocumentConfig.
352func (config DocumentConfig) params() (map[string]string, error) {
353	params, _ := config.BaseFile.params()
354
355	return params, nil
356}
357
358// name returns the field name for the Document.
359func (config DocumentConfig) name() string {
360	return "document"
361}
362
363// method returns Telegram API method name for sending Document.
364func (config DocumentConfig) method() string {
365	return "sendDocument"
366}
367
368// StickerConfig contains information about a SendSticker request.
369type StickerConfig struct {
370	BaseFile
371}
372
373// values returns a url.Values representation of StickerConfig.
374func (config StickerConfig) values() (url.Values, error) {
375	v, _ := config.BaseChat.values()
376
377	v.Add(config.name(), config.FileID)
378
379	return v, nil
380}
381
382// params returns a map[string]string representation of StickerConfig.
383func (config StickerConfig) params() (map[string]string, error) {
384	params, _ := config.BaseFile.params()
385
386	return params, nil
387}
388
389// name returns the field name for the Sticker.
390func (config StickerConfig) name() string {
391	return "sticker"
392}
393
394// method returns Telegram API method name for sending Sticker.
395func (config StickerConfig) method() string {
396	return "sendSticker"
397}
398
399// VideoConfig contains information about a SendVideo request.
400type VideoConfig struct {
401	BaseFile
402	Duration int
403	Caption  string
404}
405
406// values returns a url.Values representation of VideoConfig.
407func (config VideoConfig) values() (url.Values, error) {
408	v, _ := config.BaseChat.values()
409
410	v.Add(config.name(), config.FileID)
411	if config.Duration != 0 {
412		v.Add("duration", strconv.Itoa(config.Duration))
413	}
414	if config.Caption != "" {
415		v.Add("caption", config.Caption)
416	}
417
418	return v, nil
419}
420
421// params returns a map[string]string representation of VideoConfig.
422func (config VideoConfig) params() (map[string]string, error) {
423	params, _ := config.BaseFile.params()
424
425	return params, nil
426}
427
428// name returns the field name for the Video.
429func (config VideoConfig) name() string {
430	return "video"
431}
432
433// method returns Telegram API method name for sending Video.
434func (config VideoConfig) method() string {
435	return "sendVideo"
436}
437
438// VoiceConfig contains information about a SendVoice request.
439type VoiceConfig struct {
440	BaseFile
441	Caption  string
442	Duration int
443}
444
445// values returns a url.Values representation of VoiceConfig.
446func (config VoiceConfig) values() (url.Values, error) {
447	v, _ := config.BaseChat.values()
448
449	v.Add(config.name(), config.FileID)
450	if config.Duration != 0 {
451		v.Add("duration", strconv.Itoa(config.Duration))
452	}
453
454	return v, nil
455}
456
457// params returns a map[string]string representation of VoiceConfig.
458func (config VoiceConfig) params() (map[string]string, error) {
459	params, _ := config.BaseFile.params()
460
461	if config.Duration != 0 {
462		params["duration"] = strconv.Itoa(config.Duration)
463	}
464
465	return params, nil
466}
467
468// name returns the field name for the Voice.
469func (config VoiceConfig) name() string {
470	return "voice"
471}
472
473// method returns Telegram API method name for sending Voice.
474func (config VoiceConfig) method() string {
475	return "sendVoice"
476}
477
478// LocationConfig contains information about a SendLocation request.
479type LocationConfig struct {
480	BaseChat
481	Latitude  float64 // required
482	Longitude float64 // required
483}
484
485// values returns a url.Values representation of LocationConfig.
486func (config LocationConfig) values() (url.Values, error) {
487	v, _ := config.BaseChat.values()
488
489	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
490	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
491
492	return v, nil
493}
494
495// method returns Telegram API method name for sending Location.
496func (config LocationConfig) method() string {
497	return "sendLocation"
498}
499
500// VenueConfig contains information about a SendVenue request.
501type VenueConfig struct {
502	BaseChat
503	Latitude     float64 // required
504	Longitude    float64 // required
505	Title        string  // required
506	Address      string  // required
507	FoursquareID string
508}
509
510func (config VenueConfig) values() (url.Values, error) {
511	v, _ := config.BaseChat.values()
512
513	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
514	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
515	v.Add("title", config.Title)
516	v.Add("address", config.Address)
517	if config.FoursquareID != "" {
518		v.Add("foursquare_id", config.FoursquareID)
519	}
520
521	return v, nil
522}
523
524func (config VenueConfig) method() string {
525	return "sendVenue"
526}
527
528// ContactConfig allows you to send a contact.
529type ContactConfig struct {
530	BaseChat
531	PhoneNumber string
532	FirstName   string
533	LastName    string
534}
535
536func (config ContactConfig) values() (url.Values, error) {
537	v, _ := config.BaseChat.values()
538
539	v.Add("phone_number", config.PhoneNumber)
540	v.Add("first_name", config.FirstName)
541	v.Add("last_name", config.LastName)
542
543	return v, nil
544}
545
546func (config ContactConfig) method() string {
547	return "sendContact"
548}
549
550// GameConfig allows you to send a game.
551type GameConfig struct {
552	BaseChat
553	GameShortName string
554}
555
556func (config GameConfig) values() (url.Values, error) {
557	v, _ := config.BaseChat.values()
558
559	v.Add("game_short_name", config.GameShortName)
560
561	return v, nil
562}
563
564func (config GameConfig) method() string {
565	return "sendGame"
566}
567
568// SetGameScoreConfig allows you to update the game score in a chat.
569type SetGameScoreConfig struct {
570	UserID             int
571	Score              int
572	Force              bool
573	DisableEditMessage bool
574	ChatID             int
575	ChannelUsername    string
576	MessageID          int
577	InlineMessageID    string
578}
579
580func (config SetGameScoreConfig) values() (url.Values, error) {
581	v := url.Values{}
582
583	v.Add("user_id", strconv.Itoa(config.UserID))
584	v.Add("score", strconv.Itoa(config.Score))
585	if config.InlineMessageID == "" {
586		if config.ChannelUsername == "" {
587			v.Add("chat_id", strconv.Itoa(config.ChatID))
588		} else {
589			v.Add("chat_id", config.ChannelUsername)
590		}
591		v.Add("message_id", strconv.Itoa(config.MessageID))
592	} else {
593		v.Add("inline_message_id", config.InlineMessageID)
594	}
595	v.Add("disable_edit_message", strconv.FormatBool(config.DisableEditMessage))
596
597	return v, nil
598}
599
600func (config SetGameScoreConfig) method() string {
601	return "setGameScore"
602}
603
604// GetGameHighScoresConfig allows you to fetch the high scores for a game.
605type GetGameHighScoresConfig struct {
606	UserID          int
607	ChatID          int
608	ChannelUsername string
609	MessageID       int
610	InlineMessageID string
611}
612
613func (config GetGameHighScoresConfig) values() (url.Values, error) {
614	v := url.Values{}
615
616	v.Add("user_id", strconv.Itoa(config.UserID))
617	if config.InlineMessageID == "" {
618		if config.ChannelUsername == "" {
619			v.Add("chat_id", strconv.Itoa(config.ChatID))
620		} else {
621			v.Add("chat_id", config.ChannelUsername)
622		}
623		v.Add("message_id", strconv.Itoa(config.MessageID))
624	} else {
625		v.Add("inline_message_id", config.InlineMessageID)
626	}
627
628	return v, nil
629}
630
631func (config GetGameHighScoresConfig) method() string {
632	return "getGameHighScores"
633}
634
635// ChatActionConfig contains information about a SendChatAction request.
636type ChatActionConfig struct {
637	BaseChat
638	Action string // required
639}
640
641// values returns a url.Values representation of ChatActionConfig.
642func (config ChatActionConfig) values() (url.Values, error) {
643	v, _ := config.BaseChat.values()
644	v.Add("action", config.Action)
645	return v, nil
646}
647
648// method returns Telegram API method name for sending ChatAction.
649func (config ChatActionConfig) method() string {
650	return "sendChatAction"
651}
652
653// EditMessageTextConfig allows you to modify the text in a message.
654type EditMessageTextConfig struct {
655	BaseEdit
656	Text                  string
657	ParseMode             string
658	DisableWebPagePreview bool
659}
660
661func (config EditMessageTextConfig) values() (url.Values, error) {
662	v, _ := config.BaseEdit.values()
663
664	v.Add("text", config.Text)
665	v.Add("parse_mode", config.ParseMode)
666	v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview))
667
668	return v, nil
669}
670
671func (config EditMessageTextConfig) method() string {
672	return "editMessageText"
673}
674
675// EditMessageCaptionConfig allows you to modify the caption of a message.
676type EditMessageCaptionConfig struct {
677	BaseEdit
678	Caption string
679}
680
681func (config EditMessageCaptionConfig) values() (url.Values, error) {
682	v, _ := config.BaseEdit.values()
683
684	v.Add("caption", config.Caption)
685
686	return v, nil
687}
688
689func (config EditMessageCaptionConfig) method() string {
690	return "editMessageCaption"
691}
692
693// EditMessageReplyMarkupConfig allows you to modify the reply markup
694// of a message.
695type EditMessageReplyMarkupConfig struct {
696	BaseEdit
697}
698
699func (config EditMessageReplyMarkupConfig) values() (url.Values, error) {
700	return config.BaseEdit.values()
701}
702
703func (config EditMessageReplyMarkupConfig) method() string {
704	return "editMessageReplyMarkup"
705}
706
707// UserProfilePhotosConfig contains information about a
708// GetUserProfilePhotos request.
709type UserProfilePhotosConfig struct {
710	UserID int
711	Offset int
712	Limit  int
713}
714
715// FileConfig has information about a file hosted on Telegram.
716type FileConfig struct {
717	FileID string
718}
719
720// UpdateConfig contains information about a GetUpdates request.
721type UpdateConfig struct {
722	Offset  int
723	Limit   int
724	Timeout int
725}
726
727// WebhookConfig contains information about a SetWebhook request.
728type WebhookConfig struct {
729	URL         *url.URL
730	Certificate interface{}
731}
732
733// FileBytes contains information about a set of bytes to upload
734// as a File.
735type FileBytes struct {
736	Name  string
737	Bytes []byte
738}
739
740// FileReader contains information about a reader to upload as a File.
741// If Size is -1, it will read the entire Reader into memory to
742// calculate a Size.
743type FileReader struct {
744	Name   string
745	Reader io.Reader
746	Size   int64
747}
748
749// InlineConfig contains information on making an InlineQuery response.
750type InlineConfig struct {
751	InlineQueryID     string        `json:"inline_query_id"`
752	Results           []interface{} `json:"results"`
753	CacheTime         int           `json:"cache_time"`
754	IsPersonal        bool          `json:"is_personal"`
755	NextOffset        string        `json:"next_offset"`
756	SwitchPMText      string        `json:"switch_pm_text"`
757	SwitchPMParameter string        `json:"switch_pm_parameter"`
758}
759
760// CallbackConfig contains information on making a CallbackQuery response.
761type CallbackConfig struct {
762	CallbackQueryID string `json:"callback_query_id"`
763	Text            string `json:"text"`
764	ShowAlert       bool   `json:"show_alert"`
765	URL             string `json:"url"`
766	CacheTime       int    `json:"cache_time"`
767}
768
769// ChatMemberConfig contains information about a user in a chat for use
770// with administrative functions such as kicking or unbanning a user.
771type ChatMemberConfig struct {
772	ChatID             int64
773	SuperGroupUsername string
774	UserID             int
775}
776
777// ChatConfig contains information about getting information on a chat.
778type ChatConfig struct {
779	ChatID             int64
780	SuperGroupUsername string
781}
782
783// ChatConfigWithUser contains information about getting information on
784// a specific user within a chat.
785type ChatConfigWithUser struct {
786	ChatID             int64
787	SuperGroupUsername string
788	UserID             int
789}