telegram-bot-api/bot.go

634 lines
14 KiB
Go
Raw Normal View History

// Package tgbotapi has functions and types used for interacting with
// the Telegram Bot API.
package tgbotapi
import (
2015-11-20 11:42:26 +01:00
"bytes"
"encoding/json"
"errors"
"fmt"
2017-10-29 22:03:48 +01:00
"io"
2015-11-20 11:42:26 +01:00
"io/ioutil"
"net/http"
2015-11-20 11:42:26 +01:00
"net/url"
"os"
2015-11-21 14:33:58 +01:00
"strings"
2015-11-21 15:39:19 +01:00
"time"
"github.com/technoweenie/multipartstreamer"
)
// BotAPI allows you to interact with the Telegram Bot API.
type BotAPI struct {
Token string `json:"token"`
Debug bool `json:"debug"`
Buffer int `json:"buffer"`
2019-05-24 12:14:48 +02:00
Self User `json:"-"`
Client *http.Client `json:"-"`
shutdownChannel chan interface{}
2019-05-24 12:14:48 +02:00
apiEndpoint string
}
// NewBotAPI creates a new BotAPI instance.
//
// It requires a token, provided by @BotFather on Telegram.
func NewBotAPI(token string) (*BotAPI, error) {
return NewBotAPIWithClient(token, &http.Client{})
}
// NewBotAPIWithClient creates a new BotAPI instance
// and allows you to pass a http.Client.
//
// It requires a token, provided by @BotFather on Telegram.
2015-07-28 18:14:13 +02:00
func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
bot := &BotAPI{
2019-05-24 12:14:48 +02:00
Token: token,
Client: client,
Buffer: 100,
shutdownChannel: make(chan interface{}),
2019-05-24 12:14:48 +02:00
apiEndpoint: APIEndpoint,
}
2015-06-26 06:44:14 +02:00
self, err := bot.GetMe()
if err != nil {
return nil, err
2015-06-26 06:44:14 +02:00
}
bot.Self = self
2015-06-26 06:45:56 +02:00
return bot, nil
}
2015-11-20 11:42:26 +01:00
2020-03-30 22:35:53 +02:00
// SetAPIEndpoint changes the Telegram Bot API endpoint used by the instance.
func (bot *BotAPI) SetAPIEndpoint(apiEndpoint string) {
bot.apiEndpoint = apiEndpoint
2019-05-24 12:14:48 +02:00
}
func buildParams(in Params) (out url.Values) {
if in == nil {
return url.Values{}
}
out = url.Values{}
for key, value := range in {
out.Set(key, value)
}
return
}
2015-11-20 11:42:26 +01:00
// MakeRequest makes a request to a specific endpoint with our token.
func (bot *BotAPI) MakeRequest(endpoint string, params Params) (APIResponse, error) {
if bot.Debug {
log.Printf("Endpoint: %s, params: %v\n", endpoint, params)
}
2019-05-24 12:14:48 +02:00
method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint)
values := buildParams(params)
resp, err := bot.Client.PostForm(method, values)
2015-11-20 11:42:26 +01:00
if err != nil {
return APIResponse{}, err
}
defer resp.Body.Close()
2017-10-29 22:03:48 +01:00
var apiResp APIResponse
bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp)
if err != nil {
return apiResp, err
}
2017-10-31 00:34:34 +01:00
2017-10-29 22:03:48 +01:00
if bot.Debug {
log.Printf("Endpoint: %s, response: %s\n", endpoint, string(bytes))
2017-10-29 22:03:48 +01:00
}
if !apiResp.Ok {
2018-03-26 19:22:16 +02:00
var parameters ResponseParameters
if apiResp.Parameters != nil {
parameters = *apiResp.Parameters
}
2018-03-26 19:22:16 +02:00
return apiResp, Error{
2020-02-15 14:08:58 +01:00
Code: apiResp.ErrorCode,
2018-03-26 19:22:16 +02:00
Message: apiResp.Description,
ResponseParameters: parameters,
}
2015-11-20 11:42:26 +01:00
}
2017-10-29 22:03:48 +01:00
return apiResp, nil
}
2017-11-07 03:17:06 +01:00
// decodeAPIResponse decode response and return slice of bytes if debug enabled.
// If debug disabled, just decode http.Response.Body stream to APIResponse struct
// for efficient memory usage
2017-10-29 22:03:48 +01:00
func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) {
if !bot.Debug {
dec := json.NewDecoder(responseBody)
err = dec.Decode(resp)
return
2015-11-20 11:42:26 +01:00
}
2017-10-29 22:03:48 +01:00
// if debug, read reponse body
data, err := ioutil.ReadAll(responseBody)
if err != nil {
return
}
2015-11-20 11:42:26 +01:00
2017-10-29 22:03:48 +01:00
err = json.Unmarshal(data, resp)
if err != nil {
return
2015-11-20 11:42:26 +01:00
}
2017-10-31 00:34:34 +01:00
return data, nil
2015-11-20 11:42:26 +01:00
}
// UploadFile makes a request to the API with a file.
//
// Requires the parameter to hold the file not be in the params.
// File should be a string to a file path, a FileBytes struct,
// a FileReader struct, or a url.URL.
//
// Note that if your FileReader has a size set to -1, it will read
// the file into memory to calculate a size.
func (bot *BotAPI) UploadFile(endpoint string, params Params, fieldname string, file interface{}) (APIResponse, error) {
2015-11-20 11:42:26 +01:00
ms := multipartstreamer.New()
switch f := file.(type) {
case string:
ms.WriteFields(params)
2015-11-20 11:42:26 +01:00
fileHandle, err := os.Open(f)
if err != nil {
return APIResponse{}, err
}
defer fileHandle.Close()
fi, err := os.Stat(f)
if err != nil {
return APIResponse{}, err
}
ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle)
case FileBytes:
ms.WriteFields(params)
2015-11-20 11:42:26 +01:00
buf := bytes.NewBuffer(f.Bytes)
ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf)
case FileReader:
ms.WriteFields(params)
if f.Size != -1 {
ms.WriteReader(fieldname, f.Name, f.Size, f.Reader)
2015-11-20 11:42:26 +01:00
break
}
data, err := ioutil.ReadAll(f.Reader)
if err != nil {
return APIResponse{}, err
}
buf := bytes.NewBuffer(data)
ms.WriteReader(fieldname, f.Name, int64(len(data)), buf)
case url.URL:
params[fieldname] = f.String()
ms.WriteFields(params)
2015-11-20 11:42:26 +01:00
default:
return APIResponse{}, errors.New(ErrBadFileType)
2015-11-20 11:42:26 +01:00
}
if bot.Debug {
log.Printf("Endpoint: %s, fieldname: %s, params: %v, file: %T\n", endpoint, fieldname, params, file)
}
2019-05-24 12:14:48 +02:00
method := fmt.Sprintf(bot.apiEndpoint, bot.Token, endpoint)
req, err := http.NewRequest("POST", method, nil)
2015-11-20 11:42:26 +01:00
if err != nil {
return APIResponse{}, err
}
ms.SetupRequest(req)
2015-11-20 11:42:26 +01:00
res, err := bot.Client.Do(req)
if err != nil {
return APIResponse{}, err
}
defer res.Body.Close()
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return APIResponse{}, err
}
if bot.Debug {
log.Printf("Endpoint: %s, response: %s\n", endpoint, string(bytes))
2015-11-20 11:42:26 +01:00
}
var apiResp APIResponse
err = json.Unmarshal(bytes, &apiResp)
if err != nil {
return APIResponse{}, err
}
2015-11-20 11:42:26 +01:00
if !apiResp.Ok {
return APIResponse{}, errors.New(apiResp.Description)
}
return apiResp, nil
}
2015-11-21 17:43:24 +01:00
// GetFileDirectURL returns direct URL to file
//
// It requires the FileID.
2015-11-21 17:43:24 +01:00
func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) {
file, err := bot.GetFile(FileConfig{fileID})
2015-11-21 14:25:59 +01:00
if err != nil {
return "", err
}
2015-11-21 17:43:24 +01:00
return file.Link(bot.Token), nil
2015-11-21 14:25:59 +01:00
}
2015-11-20 11:42:26 +01:00
// GetMe fetches the currently authenticated bot.
//
// This method is called upon creation to validate the token,
// and so you may get this data from BotAPI.Self without the need for
// another request.
2015-11-20 11:42:26 +01:00
func (bot *BotAPI) GetMe() (User, error) {
resp, err := bot.MakeRequest("getMe", nil)
if err != nil {
return User{}, err
}
var user User
2017-12-30 04:55:58 +01:00
err = json.Unmarshal(resp.Result, &user)
2015-11-20 11:42:26 +01:00
2017-12-30 04:55:58 +01:00
return user, err
2015-11-20 11:42:26 +01:00
}
// IsMessageToMe returns true if message directed to this bot.
2015-11-21 17:43:24 +01:00
//
// It requires the Message.
2015-11-21 15:39:19 +01:00
func (bot *BotAPI) IsMessageToMe(message Message) bool {
2015-11-21 14:33:58 +01:00
return strings.Contains(message.Text, "@"+bot.Self.UserName)
}
2017-12-29 08:26:54 +01:00
// Request sends a Chattable to Telegram, and returns the APIResponse.
func (bot *BotAPI) Request(c Chattable) (APIResponse, error) {
params, err := c.params()
2015-11-20 15:08:53 +01:00
if err != nil {
return APIResponse{}, err
2015-11-20 15:08:53 +01:00
}
switch t := c.(type) {
case Fileable:
if t.useExistingFile() {
return bot.MakeRequest(t.method(), params)
}
2015-11-20 15:08:53 +01:00
return bot.UploadFile(t.method(), params, t.name(), t.getFile())
default:
return bot.MakeRequest(c.method(), params)
2015-11-20 15:31:01 +01:00
}
}
2017-12-29 08:26:54 +01:00
// Send will send a Chattable item to Telegram and provides the
// returned Message.
func (bot *BotAPI) Send(c Chattable) (Message, error) {
resp, err := bot.Request(c)
2015-11-20 15:31:01 +01:00
if err != nil {
return Message{}, err
}
var message Message
2017-12-29 08:26:54 +01:00
err = json.Unmarshal(resp.Result, &message)
2015-11-20 15:31:01 +01:00
2017-12-29 08:26:54 +01:00
return message, err
2015-11-20 15:31:01 +01:00
}
2018-12-25 22:44:01 +01:00
// SendMediaGroup sends a media group and returns the resulting messages.
func (bot *BotAPI) SendMediaGroup(config MediaGroupConfig) ([]Message, error) {
params, _ := config.params()
2015-11-20 15:31:01 +01:00
2018-12-25 22:44:01 +01:00
resp, err := bot.MakeRequest(config.method(), params)
2015-11-20 12:06:51 +01:00
if err != nil {
2018-12-25 22:44:01 +01:00
return nil, err
2015-11-20 11:42:26 +01:00
}
2018-12-25 22:44:01 +01:00
var messages []Message
err = json.Unmarshal(resp.Result, &messages)
2015-11-20 11:42:26 +01:00
2018-12-25 22:44:01 +01:00
return messages, err
2015-11-20 15:08:53 +01:00
}
2015-11-20 11:42:26 +01:00
// GetUserProfilePhotos gets a user's profile photos.
//
// It requires UserID.
2015-11-20 11:42:26 +01:00
// Offset and Limit are optional.
func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
params, _ := config.params()
2015-11-20 11:42:26 +01:00
resp, err := bot.MakeRequest(config.method(), params)
2015-11-20 11:42:26 +01:00
if err != nil {
return UserProfilePhotos{}, err
}
var profilePhotos UserProfilePhotos
2017-12-30 04:55:58 +01:00
err = json.Unmarshal(resp.Result, &profilePhotos)
2015-11-20 11:42:26 +01:00
2017-12-30 04:55:58 +01:00
return profilePhotos, err
2015-11-20 11:42:26 +01:00
}
// GetFile returns a File which can download a file from Telegram.
2015-11-20 11:42:26 +01:00
//
// Requires FileID.
func (bot *BotAPI) GetFile(config FileConfig) (File, error) {
params, _ := config.params()
2015-11-20 11:42:26 +01:00
resp, err := bot.MakeRequest(config.method(), params)
2015-11-20 11:42:26 +01:00
if err != nil {
return File{}, err
}
var file File
2017-12-30 04:55:58 +01:00
err = json.Unmarshal(resp.Result, &file)
2015-11-20 11:42:26 +01:00
2017-12-30 04:55:58 +01:00
return file, err
2015-11-20 11:42:26 +01:00
}
// GetUpdates fetches updates.
// If a WebHook is set, this will not return any data!
//
// Offset, Limit, and Timeout are optional.
// To avoid stale items, set Offset to one higher than the previous item.
// Set Timeout to a large number to reduce requests so you can get updates
// instantly instead of having to wait between requests.
2015-11-20 11:42:26 +01:00
func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) {
params, _ := config.params()
2015-11-20 11:42:26 +01:00
resp, err := bot.MakeRequest(config.method(), params)
2015-11-20 11:42:26 +01:00
if err != nil {
return []Update{}, err
}
var updates []Update
2017-12-30 04:55:58 +01:00
err = json.Unmarshal(resp.Result, &updates)
2015-11-20 11:42:26 +01:00
2017-12-30 04:55:58 +01:00
return updates, err
2015-11-20 11:42:26 +01:00
}
// GetWebhookInfo allows you to fetch information about a webhook and if
// one currently is set, along with pending update count and error messages.
func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) {
resp, err := bot.MakeRequest("getWebhookInfo", nil)
if err != nil {
return WebhookInfo{}, err
}
var info WebhookInfo
err = json.Unmarshal(resp.Result, &info)
return info, err
}
2015-11-21 17:43:24 +01:00
// GetUpdatesChan starts and returns a channel for getting updates.
func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) UpdatesChannel {
ch := make(chan Update, bot.Buffer)
2015-11-20 11:42:26 +01:00
go func() {
for {
select {
case <-bot.shutdownChannel:
return
default:
}
2019-05-24 12:14:48 +02:00
2015-11-20 11:42:26 +01:00
updates, err := bot.GetUpdates(config)
if err != nil {
log.Println(err)
log.Println("Failed to get updates, retrying in 3 seconds...")
time.Sleep(time.Second * 3)
continue
}
for _, update := range updates {
if update.UpdateID >= config.Offset {
config.Offset = update.UpdateID + 1
ch <- update
}
2015-11-20 11:42:26 +01:00
}
}
}()
return ch
2015-11-20 11:42:26 +01:00
}
// StopReceivingUpdates stops the go routine which receives updates
func (bot *BotAPI) StopReceivingUpdates() {
if bot.Debug {
log.Println("Stopping the update receiver routine...")
}
close(bot.shutdownChannel)
}
2015-11-20 11:42:26 +01:00
// ListenForWebhook registers a http handler for a webhook.
func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
ch := make(chan Update, bot.Buffer)
2015-11-20 11:42:26 +01:00
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
2015-11-20 11:42:26 +01:00
bytes, _ := ioutil.ReadAll(r.Body)
2018-12-10 15:02:58 +01:00
r.Body.Close()
2015-11-20 11:42:26 +01:00
var update Update
json.Unmarshal(bytes, &update)
ch <- update
2015-11-20 11:42:26 +01:00
})
2015-11-21 12:22:08 +01:00
return ch
2015-11-20 11:42:26 +01:00
}
// WriteToHTTPResponse writes the request to the HTTP ResponseWriter.
//
// It doesn't support uploading files.
//
// See https://core.telegram.org/bots/api#making-requests-when-getting-updates
// for details.
func WriteToHTTPResponse(w http.ResponseWriter, c Chattable) error {
params, err := c.params()
if err != nil {
return err
}
if t, ok := c.(Fileable); ok {
if !t.useExistingFile() {
2020-03-30 22:35:53 +02:00
return errors.New("unable to use http response to upload files")
}
}
values := buildParams(params)
values.Set("method", c.method())
w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
_, err = w.Write([]byte(values.Encode()))
return err
}
2016-05-22 17:16:28 +02:00
// GetChat gets information about a chat.
func (bot *BotAPI) GetChat(config ChatInfoConfig) (Chat, error) {
params, _ := config.params()
2016-05-22 17:16:28 +02:00
resp, err := bot.MakeRequest(config.method(), params)
2016-05-22 17:16:28 +02:00
if err != nil {
return Chat{}, err
}
var chat Chat
err = json.Unmarshal(resp.Result, &chat)
return chat, err
}
// GetChatAdministrators gets a list of administrators in the chat.
//
// If none have been appointed, only the creator will be returned.
// Bots are not shown, even if they are an administrator.
func (bot *BotAPI) GetChatAdministrators(config ChatAdministratorsConfig) ([]ChatMember, error) {
params, _ := config.params()
2016-05-22 17:16:28 +02:00
resp, err := bot.MakeRequest(config.method(), params)
2016-05-22 17:16:28 +02:00
if err != nil {
return []ChatMember{}, err
}
var members []ChatMember
err = json.Unmarshal(resp.Result, &members)
return members, err
}
// GetChatMembersCount gets the number of users in a chat.
func (bot *BotAPI) GetChatMembersCount(config ChatMemberCountConfig) (int, error) {
params, _ := config.params()
2016-05-22 17:16:28 +02:00
resp, err := bot.MakeRequest(config.method(), params)
2016-05-22 17:16:28 +02:00
if err != nil {
return -1, err
}
var count int
err = json.Unmarshal(resp.Result, &count)
return count, err
}
// GetChatMember gets a specific chat member.
func (bot *BotAPI) GetChatMember(config GetChatMemberConfig) (ChatMember, error) {
params, _ := config.params()
2016-05-22 17:16:28 +02:00
resp, err := bot.MakeRequest(config.method(), params)
2016-05-22 17:16:28 +02:00
if err != nil {
return ChatMember{}, err
}
var member ChatMember
err = json.Unmarshal(resp.Result, &member)
return member, err
}
// GetGameHighScores allows you to get the high scores for a game.
func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) {
params, _ := config.params()
resp, err := bot.MakeRequest(config.method(), params)
if err != nil {
return []GameHighScore{}, err
}
var highScores []GameHighScore
err = json.Unmarshal(resp.Result, &highScores)
return highScores, err
}
2017-06-02 22:18:42 +02:00
2017-07-17 19:48:51 +02:00
// GetInviteLink get InviteLink for a chat
func (bot *BotAPI) GetInviteLink(config ChatInviteLinkConfig) (string, error) {
params, _ := config.params()
2017-07-17 19:48:51 +02:00
resp, err := bot.MakeRequest(config.method(), params)
2017-11-09 19:51:50 +01:00
if err != nil {
return "", err
}
2017-07-17 19:48:51 +02:00
var inviteLink string
err = json.Unmarshal(resp.Result, &inviteLink)
2017-07-17 19:48:51 +02:00
return inviteLink, err
2017-07-17 19:48:51 +02:00
}
// GetStickerSet returns a StickerSet.
func (bot *BotAPI) GetStickerSet(config GetStickerSetConfig) (StickerSet, error) {
params, _ := config.params()
resp, err := bot.MakeRequest(config.method(), params)
if err != nil {
return StickerSet{}, err
}
var stickers StickerSet
err = json.Unmarshal(resp.Result, &stickers)
return stickers, err
}
// StopPoll stops a poll and returns the result.
func (bot *BotAPI) StopPoll(config StopPollConfig) (Poll, error) {
2018-03-05 16:04:37 +01:00
params, err := config.params()
if err != nil {
return Poll{}, err
2018-03-05 16:04:37 +01:00
}
resp, err := bot.MakeRequest(config.method(), params)
2018-03-05 16:12:56 +01:00
if err != nil {
return Poll{}, err
2018-03-05 16:12:56 +01:00
}
var poll Poll
err = json.Unmarshal(resp.Result, &poll)
2018-03-05 16:12:56 +01:00
return poll, err
2018-03-05 16:12:56 +01:00
}
2020-03-30 22:35:53 +02:00
// GetMyCommands gets the currently registered commands.
func (bot *BotAPI) GetMyCommands() ([]BotCommand, error) {
config := GetMyCommandsConfig{}
params, err := config.params()
if err != nil {
return nil, err
}
resp, err := bot.MakeRequest(config.method(), params)
if err != nil {
return nil, err
}
var commands []BotCommand
err = json.Unmarshal(resp.Result, &commands)
return commands, err
}