all repos — telegram-bot-api @ a1204e7ea14d507197409f0d784f66b853b175aa

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	Duration  int
279	Performer string
280	Title     string
281}
282
283// values returns a url.Values representation of AudioConfig.
284func (config AudioConfig) values() (url.Values, error) {
285	v, _ := config.BaseChat.values()
286
287	v.Add(config.name(), config.FileID)
288	if config.Duration != 0 {
289		v.Add("duration", strconv.Itoa(config.Duration))
290	}
291
292	if config.Performer != "" {
293		v.Add("performer", config.Performer)
294	}
295	if config.Title != "" {
296		v.Add("title", config.Title)
297	}
298
299	return v, nil
300}
301
302// params returns a map[string]string representation of AudioConfig.
303func (config AudioConfig) params() (map[string]string, error) {
304	params, _ := config.BaseFile.params()
305
306	if config.Duration != 0 {
307		params["duration"] = strconv.Itoa(config.Duration)
308	}
309
310	if config.Performer != "" {
311		params["performer"] = config.Performer
312	}
313	if config.Title != "" {
314		params["title"] = config.Title
315	}
316
317	return params, nil
318}
319
320// name returns the field name for the Audio.
321func (config AudioConfig) name() string {
322	return "audio"
323}
324
325// method returns Telegram API method name for sending Audio.
326func (config AudioConfig) method() string {
327	return "sendAudio"
328}
329
330// DocumentConfig contains information about a SendDocument request.
331type DocumentConfig struct {
332	BaseFile
333}
334
335// values returns a url.Values representation of DocumentConfig.
336func (config DocumentConfig) values() (url.Values, error) {
337	v, _ := config.BaseChat.values()
338
339	v.Add(config.name(), config.FileID)
340
341	return v, nil
342}
343
344// params returns a map[string]string representation of DocumentConfig.
345func (config DocumentConfig) params() (map[string]string, error) {
346	params, _ := config.BaseFile.params()
347
348	return params, nil
349}
350
351// name returns the field name for the Document.
352func (config DocumentConfig) name() string {
353	return "document"
354}
355
356// method returns Telegram API method name for sending Document.
357func (config DocumentConfig) method() string {
358	return "sendDocument"
359}
360
361// StickerConfig contains information about a SendSticker request.
362type StickerConfig struct {
363	BaseFile
364}
365
366// values returns a url.Values representation of StickerConfig.
367func (config StickerConfig) values() (url.Values, error) {
368	v, _ := config.BaseChat.values()
369
370	v.Add(config.name(), config.FileID)
371
372	return v, nil
373}
374
375// params returns a map[string]string representation of StickerConfig.
376func (config StickerConfig) params() (map[string]string, error) {
377	params, _ := config.BaseFile.params()
378
379	return params, nil
380}
381
382// name returns the field name for the Sticker.
383func (config StickerConfig) name() string {
384	return "sticker"
385}
386
387// method returns Telegram API method name for sending Sticker.
388func (config StickerConfig) method() string {
389	return "sendSticker"
390}
391
392// VideoConfig contains information about a SendVideo request.
393type VideoConfig struct {
394	BaseFile
395	Duration int
396	Caption  string
397}
398
399// values returns a url.Values representation of VideoConfig.
400func (config VideoConfig) values() (url.Values, error) {
401	v, _ := config.BaseChat.values()
402
403	v.Add(config.name(), config.FileID)
404	if config.Duration != 0 {
405		v.Add("duration", strconv.Itoa(config.Duration))
406	}
407	if config.Caption != "" {
408		v.Add("caption", config.Caption)
409	}
410
411	return v, nil
412}
413
414// params returns a map[string]string representation of VideoConfig.
415func (config VideoConfig) params() (map[string]string, error) {
416	params, _ := config.BaseFile.params()
417
418	return params, nil
419}
420
421// name returns the field name for the Video.
422func (config VideoConfig) name() string {
423	return "video"
424}
425
426// method returns Telegram API method name for sending Video.
427func (config VideoConfig) method() string {
428	return "sendVideo"
429}
430
431// VoiceConfig contains information about a SendVoice request.
432type VoiceConfig struct {
433	BaseFile
434	Duration int
435}
436
437// values returns a url.Values representation of VoiceConfig.
438func (config VoiceConfig) values() (url.Values, error) {
439	v, _ := config.BaseChat.values()
440
441	v.Add(config.name(), config.FileID)
442	if config.Duration != 0 {
443		v.Add("duration", strconv.Itoa(config.Duration))
444	}
445
446	return v, nil
447}
448
449// params returns a map[string]string representation of VoiceConfig.
450func (config VoiceConfig) params() (map[string]string, error) {
451	params, _ := config.BaseFile.params()
452
453	if config.Duration != 0 {
454		params["duration"] = strconv.Itoa(config.Duration)
455	}
456
457	return params, nil
458}
459
460// name returns the field name for the Voice.
461func (config VoiceConfig) name() string {
462	return "voice"
463}
464
465// method returns Telegram API method name for sending Voice.
466func (config VoiceConfig) method() string {
467	return "sendVoice"
468}
469
470// LocationConfig contains information about a SendLocation request.
471type LocationConfig struct {
472	BaseChat
473	Latitude  float64 // required
474	Longitude float64 // required
475}
476
477// values returns a url.Values representation of LocationConfig.
478func (config LocationConfig) values() (url.Values, error) {
479	v, _ := config.BaseChat.values()
480
481	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
482	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
483
484	return v, nil
485}
486
487// method returns Telegram API method name for sending Location.
488func (config LocationConfig) method() string {
489	return "sendLocation"
490}
491
492// VenueConfig contains information about a SendVenue request.
493type VenueConfig struct {
494	BaseChat
495	Latitude     float64 // required
496	Longitude    float64 // required
497	Title        string  // required
498	Address      string  // required
499	FoursquareID string
500}
501
502func (config VenueConfig) values() (url.Values, error) {
503	v, _ := config.BaseChat.values()
504
505	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
506	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
507	v.Add("title", config.Title)
508	v.Add("address", config.Address)
509	if config.FoursquareID != "" {
510		v.Add("foursquare_id", config.FoursquareID)
511	}
512
513	return v, nil
514}
515
516func (config VenueConfig) method() string {
517	return "sendVenue"
518}
519
520// ContactConfig allows you to send a contact.
521type ContactConfig struct {
522	BaseChat
523	PhoneNumber string
524	FirstName   string
525	LastName    string
526}
527
528func (config ContactConfig) values() (url.Values, error) {
529	v, _ := config.BaseChat.values()
530
531	v.Add("phone_number", config.PhoneNumber)
532	v.Add("first_name", config.FirstName)
533	v.Add("last_name", config.LastName)
534
535	return v, nil
536}
537
538func (config ContactConfig) method() string {
539	return "sendContact"
540}
541
542// ChatActionConfig contains information about a SendChatAction request.
543type ChatActionConfig struct {
544	BaseChat
545	Action string // required
546}
547
548// values returns a url.Values representation of ChatActionConfig.
549func (config ChatActionConfig) values() (url.Values, error) {
550	v, _ := config.BaseChat.values()
551	v.Add("action", config.Action)
552	return v, nil
553}
554
555// method returns Telegram API method name for sending ChatAction.
556func (config ChatActionConfig) method() string {
557	return "sendChatAction"
558}
559
560// EditMessageTextConfig allows you to modify the text in a message.
561type EditMessageTextConfig struct {
562	BaseEdit
563	Text                  string
564	ParseMode             string
565	DisableWebPagePreview bool
566}
567
568func (config EditMessageTextConfig) values() (url.Values, error) {
569	v, _ := config.BaseEdit.values()
570
571	v.Add("text", config.Text)
572	v.Add("parse_mode", config.ParseMode)
573	v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview))
574
575	return v, nil
576}
577
578func (config EditMessageTextConfig) method() string {
579	return "editMessageText"
580}
581
582// EditMessageCaptionConfig allows you to modify the caption of a message.
583type EditMessageCaptionConfig struct {
584	BaseEdit
585	Caption string
586}
587
588func (config EditMessageCaptionConfig) values() (url.Values, error) {
589	v, _ := config.BaseEdit.values()
590
591	v.Add("caption", config.Caption)
592
593	return v, nil
594}
595
596func (config EditMessageCaptionConfig) method() string {
597	return "editMessageCaption"
598}
599
600// EditMessageReplyMarkupConfig allows you to modify the reply markup
601// of a message.
602type EditMessageReplyMarkupConfig struct {
603	BaseEdit
604}
605
606func (config EditMessageReplyMarkupConfig) values() (url.Values, error) {
607	return config.BaseEdit.values()
608}
609
610func (config EditMessageReplyMarkupConfig) method() string {
611	return "editMessageReplyMarkup"
612}
613
614// UserProfilePhotosConfig contains information about a
615// GetUserProfilePhotos request.
616type UserProfilePhotosConfig struct {
617	UserID int
618	Offset int
619	Limit  int
620}
621
622// FileConfig has information about a file hosted on Telegram.
623type FileConfig struct {
624	FileID string
625}
626
627// UpdateConfig contains information about a GetUpdates request.
628type UpdateConfig struct {
629	Offset  int
630	Limit   int
631	Timeout int
632}
633
634// WebhookConfig contains information about a SetWebhook request.
635type WebhookConfig struct {
636	URL         *url.URL
637	Certificate interface{}
638}
639
640// FileBytes contains information about a set of bytes to upload
641// as a File.
642type FileBytes struct {
643	Name  string
644	Bytes []byte
645}
646
647// FileReader contains information about a reader to upload as a File.
648// If Size is -1, it will read the entire Reader into memory to
649// calculate a Size.
650type FileReader struct {
651	Name   string
652	Reader io.Reader
653	Size   int64
654}
655
656// InlineConfig contains information on making an InlineQuery response.
657type InlineConfig struct {
658	InlineQueryID     string        `json:"inline_query_id"`
659	Results           []interface{} `json:"results"`
660	CacheTime         int           `json:"cache_time"`
661	IsPersonal        bool          `json:"is_personal"`
662	NextOffset        string        `json:"next_offset"`
663	SwitchPMText      string        `json:"switch_pm_text"`
664	SwitchPMParameter string        `json:"switch_pm_parameter"`
665}
666
667// CallbackConfig contains information on making a CallbackQuery response.
668type CallbackConfig struct {
669	CallbackQueryID string `json:"callback_query_id"`
670	Text            string `json:"text"`
671	ShowAlert       bool   `json:"show_alert"`
672}
673
674// ChatMemberConfig contains information about a user in a chat for use
675// with administrative functions such as kicking or unbanning a user.
676type ChatMemberConfig struct {
677	ChatID             int64
678	SuperGroupUsername string
679	UserID             int
680}
681
682// ChatConfig contains information about getting information on a chat.
683type ChatConfig struct {
684	ChatID             int64
685	SuperGroupUsername string
686}
687
688// ChatConfigWithUser contains information about getting information on
689// a specific user within a chat.
690type ChatConfigWithUser struct {
691	ChatID             int64
692	SuperGroupUsername string
693	UserID             int
694}