Update vendor go-telegram-bot-api/telegram-bot-api

This commit is contained in:
Wim 2018-05-09 22:46:10 +02:00
parent 8d307d8134
commit 529b188164
5 changed files with 269 additions and 51 deletions

View File

@ -7,6 +7,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
@ -67,33 +68,51 @@ func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse,
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden { var apiResp APIResponse
return APIResponse{}, errors.New(ErrAPIForbidden) bytes, err := bot.decodeAPIResponse(resp.Body, &apiResp)
}
if resp.StatusCode != http.StatusOK {
return APIResponse{}, errors.New(http.StatusText(resp.StatusCode))
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return APIResponse{}, err return apiResp, err
} }
if bot.Debug { if bot.Debug {
log.Println(endpoint, string(bytes)) log.Printf("%s resp: %s", endpoint, bytes)
} }
var apiResp APIResponse
json.Unmarshal(bytes, &apiResp)
if !apiResp.Ok { if !apiResp.Ok {
return apiResp, errors.New(apiResp.Description) parameters := ResponseParameters{}
if apiResp.Parameters != nil {
parameters = *apiResp.Parameters
}
return apiResp, Error{apiResp.Description, parameters}
} }
return apiResp, nil return apiResp, nil
} }
// 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
func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) {
if !bot.Debug {
dec := json.NewDecoder(responseBody)
err = dec.Decode(resp)
return
}
// if debug, read reponse body
data, err := ioutil.ReadAll(responseBody)
if err != nil {
return
}
err = json.Unmarshal(data, resp)
if err != nil {
return
}
return data, nil
}
// makeMessageRequest makes a request to a method that returns a Message. // makeMessageRequest makes a request to a method that returns a Message.
func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) { func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) {
resp, err := bot.MakeRequest(endpoint, params) resp, err := bot.MakeRequest(endpoint, params)
@ -712,24 +731,28 @@ func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIRespo
} }
v.Add("user_id", strconv.Itoa(config.UserID)) v.Add("user_id", strconv.Itoa(config.UserID))
if &config.CanSendMessages != nil { if config.CanSendMessages != nil {
v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages))
} }
if &config.CanSendMediaMessages != nil { if config.CanSendMediaMessages != nil {
v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages))
} }
if &config.CanSendOtherMessages != nil { if config.CanSendOtherMessages != nil {
v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages))
} }
if &config.CanAddWebPagePreviews != nil { if config.CanAddWebPagePreviews != nil {
v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews))
} }
if config.UntilDate != 0 {
v.Add("until_date", strconv.FormatInt(config.UntilDate, 10))
}
bot.debugLog("restrictChatMember", v, nil) bot.debugLog("restrictChatMember", v, nil)
return bot.MakeRequest("restrictChatMember", v) return bot.MakeRequest("restrictChatMember", v)
} }
// PromoteChatMember add admin rights to user
func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) {
v := url.Values{} v := url.Values{}
@ -742,28 +765,28 @@ func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIRespons
} }
v.Add("user_id", strconv.Itoa(config.UserID)) v.Add("user_id", strconv.Itoa(config.UserID))
if &config.CanChangeInfo != nil { if config.CanChangeInfo != nil {
v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo))
} }
if &config.CanPostMessages != nil { if config.CanPostMessages != nil {
v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages))
} }
if &config.CanEditMessages != nil { if config.CanEditMessages != nil {
v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages))
} }
if &config.CanDeleteMessages != nil { if config.CanDeleteMessages != nil {
v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages))
} }
if &config.CanInviteUsers != nil { if config.CanInviteUsers != nil {
v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers))
} }
if &config.CanRestrictMembers != nil { if config.CanRestrictMembers != nil {
v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers))
} }
if &config.CanPinMessages != nil { if config.CanPinMessages != nil {
v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages))
} }
if &config.CanPromoteMembers != nil { if config.CanPromoteMembers != nil {
v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers))
} }
@ -846,6 +869,9 @@ func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) {
} }
resp, err := bot.MakeRequest("exportChatInviteLink", v) resp, err := bot.MakeRequest("exportChatInviteLink", v)
if err != nil {
return "", err
}
var inviteLink string var inviteLink string
err = json.Unmarshal(resp.Result, &inviteLink) err = json.Unmarshal(resp.Result, &inviteLink)
@ -853,7 +879,7 @@ func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) {
return inviteLink, err return inviteLink, err
} }
// Pin message in supergroup // PinChatMessage pin message in supergroup
func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) {
v, err := config.values() v, err := config.values()
if err != nil { if err != nil {
@ -865,7 +891,7 @@ func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, err
return bot.MakeRequest(config.method(), v) return bot.MakeRequest(config.method(), v)
} }
// Unpin message in supergroup // UnpinChatMessage unpin message in supergroup
func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) {
v, err := config.values() v, err := config.values()
if err != nil { if err != nil {
@ -876,3 +902,51 @@ func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse,
return bot.MakeRequest(config.method(), v) return bot.MakeRequest(config.method(), v)
} }
// SetChatTitle change title of chat.
func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) {
v, err := config.values()
if err != nil {
return APIResponse{}, err
}
bot.debugLog(config.method(), v, nil)
return bot.MakeRequest(config.method(), v)
}
// SetChatDescription change description of chat.
func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) {
v, err := config.values()
if err != nil {
return APIResponse{}, err
}
bot.debugLog(config.method(), v, nil)
return bot.MakeRequest(config.method(), v)
}
// SetChatPhoto change photo of chat.
func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) {
params, err := config.params()
if err != nil {
return APIResponse{}, err
}
file := config.getFile()
return bot.UploadFile(config.method(), params, config.name(), file)
}
// DeleteChatPhoto delete photo of chat.
func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) {
v, err := config.values()
if err != nil {
return APIResponse{}, err
}
bot.debugLog(config.method(), v, nil)
return bot.MakeRequest(config.method(), v)
}

View File

@ -676,7 +676,7 @@ type SetGameScoreConfig struct {
Score int Score int
Force bool Force bool
DisableEditMessage bool DisableEditMessage bool
ChatID int ChatID int64
ChannelUsername string ChannelUsername string
MessageID int MessageID int
InlineMessageID string InlineMessageID string
@ -689,7 +689,7 @@ func (config SetGameScoreConfig) values() (url.Values, error) {
v.Add("score", strconv.Itoa(config.Score)) v.Add("score", strconv.Itoa(config.Score))
if config.InlineMessageID == "" { if config.InlineMessageID == "" {
if config.ChannelUsername == "" { if config.ChannelUsername == "" {
v.Add("chat_id", strconv.Itoa(config.ChatID)) v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
} else { } else {
v.Add("chat_id", config.ChannelUsername) v.Add("chat_id", config.ChannelUsername)
} }
@ -1038,8 +1038,8 @@ func (config DeleteMessageConfig) values() (url.Values, error) {
// PinChatMessageConfig contains information of a message in a chat to pin. // PinChatMessageConfig contains information of a message in a chat to pin.
type PinChatMessageConfig struct { type PinChatMessageConfig struct {
ChatID int64 ChatID int64
MessageID int MessageID int
DisableNotification bool DisableNotification bool
} }
@ -1073,3 +1073,73 @@ func (config UnpinChatMessageConfig) values() (url.Values, error) {
return v, nil return v, nil
} }
// SetChatTitleConfig contains information for change chat title.
type SetChatTitleConfig struct {
ChatID int64
Title string
}
func (config SetChatTitleConfig) method() string {
return "setChatTitle"
}
func (config SetChatTitleConfig) values() (url.Values, error) {
v := url.Values{}
v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
v.Add("title", config.Title)
return v, nil
}
// SetChatDescriptionConfig contains information for change chat description.
type SetChatDescriptionConfig struct {
ChatID int64
Description string
}
func (config SetChatDescriptionConfig) method() string {
return "setChatDescription"
}
func (config SetChatDescriptionConfig) values() (url.Values, error) {
v := url.Values{}
v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
v.Add("description", config.Description)
return v, nil
}
// SetChatPhotoConfig contains information for change chat photo
type SetChatPhotoConfig struct {
BaseFile
}
// name returns the field name for the Photo.
func (config SetChatPhotoConfig) name() string {
return "photo"
}
// method returns Telegram API method name for sending Photo.
func (config SetChatPhotoConfig) method() string {
return "setChatPhoto"
}
// DeleteChatPhotoConfig contains information for delete chat photo.
type DeleteChatPhotoConfig struct {
ChatID int64
}
func (config DeleteChatPhotoConfig) method() string {
return "deleteChatPhoto"
}
func (config DeleteChatPhotoConfig) values() (url.Values, error) {
v := url.Values{}
v.Add("chat_id", strconv.FormatInt(config.ChatID, 10))
return v, nil
}

View File

@ -19,6 +19,13 @@ func NewMessage(chatID int64, text string) MessageConfig {
} }
} }
func NewDeleteMessage(chatID int64, messageID int) DeleteMessageConfig {
return DeleteMessageConfig{
ChatID: chatID,
MessageID: messageID,
}
}
// NewMessageToChannel creates a new Message that is sent to a channel // NewMessageToChannel creates a new Message that is sent to a channel
// by username. // by username.
// //
@ -641,7 +648,7 @@ func NewCallbackWithAlert(id, text string) CallbackConfig {
} }
} }
// NewInvoice created a new Invoice request to the user. // NewInvoice creates a new Invoice request to the user.
func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices *[]LabeledPrice) InvoiceConfig { func NewInvoice(chatID int64, title, description, payload, providerToken, startParameter, currency string, prices *[]LabeledPrice) InvoiceConfig {
return InvoiceConfig{ return InvoiceConfig{
BaseChat: BaseChat{ChatID: chatID}, BaseChat: BaseChat{ChatID: chatID},
@ -653,3 +660,34 @@ func NewInvoice(chatID int64, title, description, payload, providerToken, startP
Currency: currency, Currency: currency,
Prices: prices} Prices: prices}
} }
// NewSetChatPhotoUpload creates a new chat photo uploader.
//
// chatID is where to send it, file is a string path to the file,
// FileReader, or FileBytes.
//
// Note that you must send animated GIFs as a document.
func NewSetChatPhotoUpload(chatID int64, file interface{}) SetChatPhotoConfig {
return SetChatPhotoConfig{
BaseFile: BaseFile{
BaseChat: BaseChat{ChatID: chatID},
File: file,
UseExisting: false,
},
}
}
// NewSetChatPhotoShare shares an existing photo.
// You may use this to reshare an existing photo without reuploading it.
//
// chatID is where to send it, fileID is the ID of the file
// already uploaded.
func NewSetChatPhotoShare(chatID int64, fileID string) SetChatPhotoConfig {
return SetChatPhotoConfig{
BaseFile: BaseFile{
BaseChat: BaseChat{ChatID: chatID},
FileID: fileID,
UseExisting: true,
},
}
}

View File

@ -56,6 +56,7 @@ type User struct {
LastName string `json:"last_name"` // optional LastName string `json:"last_name"` // optional
UserName string `json:"username"` // optional UserName string `json:"username"` // optional
LanguageCode string `json:"language_code"` // optional LanguageCode string `json:"language_code"` // optional
IsBot bool `json:"is_bot"` // optional
} }
// String displays a simple text version of a user. // String displays a simple text version of a user.
@ -173,21 +174,23 @@ func (m *Message) Time() time.Time {
return time.Unix(int64(m.Date), 0) return time.Unix(int64(m.Date), 0)
} }
// IsCommand returns true if message starts with '/'. // IsCommand returns true if message starts with a "bot_command" entity.
func (m *Message) IsCommand() bool { func (m *Message) IsCommand() bool {
return m.Text != "" && m.Text[0] == '/' if m.Entities == nil || len(*m.Entities) == 0 {
return false
}
entity := (*m.Entities)[0]
return entity.Offset == 0 && entity.Type == "bot_command"
} }
// Command checks if the message was a command and if it was, returns the // Command checks if the message was a command and if it was, returns the
// command. If the Message was not a command, it returns an empty string. // command. If the Message was not a command, it returns an empty string.
// //
// If the command contains the at bot syntax, it removes the bot name. // If the command contains the at name syntax, it is removed. Use
// CommandWithAt() if you do not want that.
func (m *Message) Command() string { func (m *Message) Command() string {
if !m.IsCommand() { command := m.CommandWithAt()
return ""
}
command := strings.SplitN(m.Text, " ", 2)[0][1:]
if i := strings.Index(command, "@"); i != -1 { if i := strings.Index(command, "@"); i != -1 {
command = command[:i] command = command[:i]
@ -196,20 +199,42 @@ func (m *Message) Command() string {
return command return command
} }
// CommandWithAt checks if the message was a command and if it was, returns the
// command. If the Message was not a command, it returns an empty string.
//
// If the command contains the at name syntax, it is not removed. Use Command()
// if you want that.
func (m *Message) CommandWithAt() string {
if !m.IsCommand() {
return ""
}
// IsCommand() checks that the message begins with a bot_command entity
entity := (*m.Entities)[0]
return m.Text[1:entity.Length]
}
// CommandArguments checks if the message was a command and if it was, // CommandArguments checks if the message was a command and if it was,
// returns all text after the command name. If the Message was not a // returns all text after the command name. If the Message was not a
// command, it returns an empty string. // command, it returns an empty string.
//
// Note: The first character after the command name is omitted:
// - "/foo bar baz" yields "bar baz", not " bar baz"
// - "/foo-bar baz" yields "bar baz", too
// Even though the latter is not a command conforming to the spec, the API
// marks "/foo" as command entity.
func (m *Message) CommandArguments() string { func (m *Message) CommandArguments() string {
if !m.IsCommand() { if !m.IsCommand() {
return "" return ""
} }
split := strings.SplitN(m.Text, " ", 2) // IsCommand() checks that the message begins with a bot_command entity
if len(split) != 2 { entity := (*m.Entities)[0]
return "" if len(m.Text) == entity.Length {
return "" // The command makes up the whole message
} }
return split[1] return m.Text[entity.Length+1:]
} }
// MessageEntity contains information about data in a Message. // MessageEntity contains information about data in a Message.
@ -265,6 +290,7 @@ type Sticker struct {
Thumbnail *PhotoSize `json:"thumb"` // optional Thumbnail *PhotoSize `json:"thumb"` // optional
Emoji string `json:"emoji"` // optional Emoji string `json:"emoji"` // optional
FileSize int `json:"file_size"` // optional FileSize int `json:"file_size"` // optional
SetName string `json:"set_name"` // optional
} }
// Video contains information about a video. // Video contains information about a video.
@ -385,7 +411,7 @@ type InlineKeyboardButton struct {
SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` // optional SwitchInlineQuery *string `json:"switch_inline_query,omitempty"` // optional
SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` // optional SwitchInlineQueryCurrentChat *string `json:"switch_inline_query_current_chat,omitempty"` // optional
CallbackGame *CallbackGame `json:"callback_game,omitempty"` // optional CallbackGame *CallbackGame `json:"callback_game,omitempty"` // optional
Pay bool `json:"pay,omitempty"` // optional Pay bool `json:"pay,omitempty"` // optional
} }
// CallbackQuery is data sent when a keyboard button with callback data // CallbackQuery is data sent when a keyboard button with callback data
@ -632,7 +658,7 @@ type InlineQueryResultGame struct {
Type string `json:"type"` Type string `json:"type"`
ID string `json:"id"` ID string `json:"id"`
GameShortName string `json:"game_short_name"` GameShortName string `json:"game_short_name"`
ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup"` ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
} }
// ChosenInlineResult is an inline query result chosen by a User // ChosenInlineResult is an inline query result chosen by a User
@ -746,3 +772,13 @@ type PreCheckoutQuery struct {
ShippingOptionID string `json:"shipping_option_id,omitempty"` ShippingOptionID string `json:"shipping_option_id,omitempty"`
OrderInfo *OrderInfo `json:"order_info,omitempty"` OrderInfo *OrderInfo `json:"order_info,omitempty"`
} }
// Error is an error containing extra information returned by the Telegram API.
type Error struct {
Message string
ResponseParameters
}
func (e Error) Error() string {
return e.Message
}

2
vendor/manifest vendored
View File

@ -207,7 +207,7 @@
"importpath": "github.com/go-telegram-bot-api/telegram-bot-api", "importpath": "github.com/go-telegram-bot-api/telegram-bot-api",
"repository": "https://github.com/go-telegram-bot-api/telegram-bot-api", "repository": "https://github.com/go-telegram-bot-api/telegram-bot-api",
"vcs": "git", "vcs": "git",
"revision": "9dda67c714e5e2cba837b28a0172cca2ed54f078", "revision": "212b1541150cbfcc268fbeb3b15c14383e638409",
"branch": "master", "branch": "master",
"notests": true "notests": true
}, },