telebot: clarify and fix all naming issues

pull/341/head
Demian 4 years ago
parent 2f11c43bd9
commit 5a1a187e87

@ -150,8 +150,10 @@ func (b *Bot) Promote(chat *Chat, member *ChatMember) error {
//
// On success, returns an Array of ChatMember objects that
// contains information about all chat administrators except other bots.
//
// If the chat is a group or a supergroup and
// no administrators were appointed, only the creator will be returned.
//
func (b *Bot) AdminsOf(chat *Chat) ([]ChatMember, error) {
params := map[string]string{
"chat_id": chat.Recipient(),

@ -61,7 +61,7 @@ func (b *Bot) Raw(method string, payload interface{}) ([]byte, error) {
}
func (b *Bot) sendFiles(method string, files map[string]File, params map[string]string) ([]byte, error) {
rawFiles := map[string]interface{}{}
rawFiles := make(map[string]interface{})
for name, f := range files {
switch {
case f.InCloud():
@ -73,7 +73,7 @@ func (b *Bot) sendFiles(method string, files map[string]File, params map[string]
case f.FileReader != nil:
rawFiles[name] = f.FileReader
default:
return nil, errors.Errorf("telebot: File for field %s doesn't exist", name)
return nil, errors.Errorf("telebot: file for field %s doesn't exist", name)
}
}
@ -139,7 +139,7 @@ func addFileToWriter(writer *multipart.Writer, filename, field string, file inte
defer f.Close()
reader = f
} else {
return errors.Errorf("telebot: File for field %v should be an io.ReadCloser or string", field)
return errors.Errorf("telebot: file for field %v should be an io.ReadCloser or string", field)
}
part, err := writer.CreateFormFile(field, filename)

117
bot.go

@ -149,7 +149,7 @@ type Command struct {
// b.Handle(tb.OnText, func (m *tb.Message) {})
// b.Handle(tb.OnQuery, func (q *tb.Query) {})
//
// // make a hook for one of your preserved (by-pointer) inline buttons.
// // make a hook for one of your preserved inline buttons.
// b.Handle(&inlineButton, func (c *tb.Callback) {})
//
func (b *Bot) Handle(endpoint interface{}, handler interface{}) {
@ -460,7 +460,6 @@ func (b *Bot) handle(end string, m *Message) bool {
}
b.runHandler(func() { handler(m) })
return true
}
@ -502,7 +501,8 @@ func (b *Bot) handleMedia(m *Message) bool {
// Send accepts 2+ arguments, starting with destination chat, followed by
// some Sendable (or string!) and optional send options.
//
// Note: since most arguments are of type interface{}, but have pointer
// NOTE:
// Since most arguments are of type interface{}, but have pointer
// method receivers, make sure to pass them by-pointer, NOT by-value.
//
// What is a send option exactly? It can be one of the following types:
@ -512,12 +512,12 @@ func (b *Bot) handleMedia(m *Message) bool {
// - Option (a shortcut flag for popular options)
// - ParseMode (HTML, Markdown, etc)
//
func (b *Bot) Send(to Recipient, what interface{}, options ...interface{}) (*Message, error) {
func (b *Bot) Send(to Recipient, what interface{}, opts ...interface{}) (*Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
switch object := what.(type) {
case string:
@ -530,9 +530,8 @@ func (b *Bot) Send(to Recipient, what interface{}, options ...interface{}) (*Mes
}
// SendAlbum sends multiple instances of media as a single message.
//
// From all existing options, it only supports tb.Silent.
func (b *Bot) SendAlbum(to Recipient, a Album, options ...interface{}) ([]Message, error) {
func (b *Bot) SendAlbum(to Recipient, a Album, opts ...interface{}) ([]Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
@ -602,7 +601,7 @@ func (b *Bot) SendAlbum(to Recipient, a Album, options ...interface{}) ([]Messag
"media": "[" + strings.Join(media, ",") + "]",
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.sendFiles("sendMediaGroup", files, params)
@ -634,10 +633,9 @@ func (b *Bot) SendAlbum(to Recipient, a Album, options ...interface{}) ([]Messag
}
// Reply behaves just like Send() with an exception of "reply-to" indicator.
//
// This function will panic upon nil Message.
func (b *Bot) Reply(to *Message, what interface{}, options ...interface{}) (*Message, error) {
sendOpts := extractOptions(options)
func (b *Bot) Reply(to *Message, what interface{}, opts ...interface{}) (*Message, error) {
sendOpts := extractOptions(opts)
if sendOpts == nil {
sendOpts = &SendOptions{}
}
@ -647,9 +645,8 @@ func (b *Bot) Reply(to *Message, what interface{}, options ...interface{}) (*Mes
}
// Forward behaves just like Send() but of all options it only supports Silent (see Bots API).
//
// This function will panic upon nil Editable.
func (b *Bot) Forward(to Recipient, msg Editable, options ...interface{}) (*Message, error) {
func (b *Bot) Forward(to Recipient, msg Editable, opts ...interface{}) (*Message, error) {
if to == nil {
return nil, ErrBadRecipient
}
@ -661,7 +658,7 @@ func (b *Bot) Forward(to Recipient, msg Editable, options ...interface{}) (*Mess
"message_id": msgID,
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("forwardMessage", params)
@ -673,6 +670,7 @@ func (b *Bot) Forward(to Recipient, msg Editable, options ...interface{}) (*Mess
}
// Edit is magic, it lets you change already sent message.
// This function will panic upon nil Editable.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
@ -685,8 +683,7 @@ func (b *Bot) Forward(to Recipient, msg Editable, options ...interface{}) (*Mess
// b.Edit(m, &tb.Photo{File: ...})
// b.Edit(m, tb.Location{42.1337, 69.4242})
//
// This function will panic upon nil Editable.
func (b *Bot) Edit(msg Editable, what interface{}, options ...interface{}) (*Message, error) {
func (b *Bot) Edit(msg Editable, what interface{}, opts ...interface{}) (*Message, error) {
var (
method string
params = make(map[string]string)
@ -696,7 +693,7 @@ func (b *Bot) Edit(msg Editable, what interface{}, options ...interface{}) (*Mes
case *ReplyMarkup:
return b.EditReplyMarkup(msg, v)
case InputMedia:
return b.EditMedia(msg, v, options...)
return b.EditMedia(msg, v, opts...)
case string:
method = "editMessageText"
params["text"] = v
@ -717,7 +714,7 @@ func (b *Bot) Edit(msg Editable, what interface{}, options ...interface{}) (*Mes
params["message_id"] = msgID
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw(method, params)
@ -729,13 +726,12 @@ func (b *Bot) Edit(msg Editable, what interface{}, options ...interface{}) (*Mes
}
// EditReplyMarkup edits reply markup of already sent message.
// This function will panic upon nil Editable.
// Pass nil or empty ReplyMarkup to delete it from the message.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
//
// On success, returns edited message object.
// This function will panic upon nil Editable.
func (b *Bot) EditReplyMarkup(msg Editable, markup *ReplyMarkup) (*Message, error) {
msgID, chatID := msg.MessageSig()
params := make(map[string]string)
@ -765,13 +761,12 @@ func (b *Bot) EditReplyMarkup(msg Editable, markup *ReplyMarkup) (*Message, erro
}
// EditCaption edits already sent photo caption with known recipient and message id.
// This function will panic upon nil Editable.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
//
// On success, returns edited message object.
// This function will panic upon nil Editable.
func (b *Bot) EditCaption(msg Editable, caption string, options ...interface{}) (*Message, error) {
func (b *Bot) EditCaption(msg Editable, caption string, opts ...interface{}) (*Message, error) {
msgID, chatID := msg.MessageSig()
params := map[string]string{
@ -785,7 +780,7 @@ func (b *Bot) EditCaption(msg Editable, caption string, options ...interface{})
params["message_id"] = msgID
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("editMessageCaption", params)
@ -797,6 +792,7 @@ func (b *Bot) EditCaption(msg Editable, caption string, options ...interface{})
}
// EditMedia edits already sent media with known recipient and message id.
// This function will panic upon nil Editable.
//
// If edited message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
@ -806,8 +802,7 @@ func (b *Bot) EditCaption(msg Editable, caption string, options ...interface{})
// b.EditMedia(m, &tb.Photo{File: tb.FromDisk("chicken.jpg")})
// b.EditMedia(m, &tb.Video{File: tb.FromURL("http://video.mp4")})
//
// This function will panic upon nil Editable.
func (b *Bot) EditMedia(msg Editable, media InputMedia, options ...interface{}) (*Message, error) {
func (b *Bot) EditMedia(msg Editable, media InputMedia, opts ...interface{}) (*Message, error) {
var (
repr string
thumb *Photo
@ -899,7 +894,7 @@ func (b *Bot) EditMedia(msg Editable, media InputMedia, options ...interface{})
msgID, chatID := msg.MessageSig()
params := make(map[string]string)
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
if sendOpts != nil {
@ -928,18 +923,18 @@ func (b *Bot) EditMedia(msg Editable, media InputMedia, options ...interface{})
return extractMessage(data)
}
// Delete removes the message, including service messages,
// with the following limitations:
// Delete removes the message, including service messages.
// This function will panic upon nil Editable.
//
// * A message can only be deleted if it was sent less than 48 hours ago.
// * Bots can delete outgoing messages in groups and supergroups.
// * Bots granted can_post_messages permissions can delete outgoing
// messages in channels.
// * A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
// * Bots can delete outgoing messages in private chats, groups, and supergroups.
// * Bots can delete incoming messages in private chats.
// * Bots granted can_post_messages permissions can delete outgoing messages in channels.
// * If the bot is an administrator of a group, it can delete any message there.
// * If the bot has can_delete_messages permission in a supergroup or a
// channel, it can delete any message there.
//
// This function will panic upon nil Editable.
func (b *Bot) Delete(msg Editable) error {
msgID, chatID := msg.MessageSig()
@ -961,6 +956,7 @@ func (b *Bot) Delete(msg Editable) error {
//
// Currently, Telegram supports only a narrow range of possible
// actions, these are aligned as constants of this package.
//
func (b *Bot) Notify(to Recipient, action ChatAction) error {
if to == nil {
return ErrBadRecipient
@ -1071,6 +1067,7 @@ func (b *Bot) Respond(c *Callback, resp ...*CallbackResponse) error {
//
// Usually, Telegram-provided File objects miss FilePath so you might need to
// perform an additional request to fetch them.
//
func (b *Bot) FileByID(fileID string) (File, error) {
params := map[string]string{
"file_id": fileID,
@ -1091,12 +1088,11 @@ func (b *Bot) FileByID(fileID string) (File, error) {
}
// Download saves the file from Telegram servers locally.
//
// Maximum file size to download is 20 MB.
func (b *Bot) Download(file *File, localFilename string) error {
reader, err := b.GetFile(file)
reader, err := b.File(file)
if err != nil {
return wrapError(err)
return err
}
defer reader.Close()
@ -1115,8 +1111,8 @@ func (b *Bot) Download(file *File, localFilename string) error {
return nil
}
// GetFile gets a file from Telegram servers.
func (b *Bot) GetFile(file *File) (io.ReadCloser, error) {
// File gets a file from Telegram servers.
func (b *Bot) File(file *File) (io.ReadCloser, error) {
f, err := b.FileByID(file.FileID)
if err != nil {
return nil, err
@ -1146,12 +1142,13 @@ func (b *Bot) GetFile(file *File) (io.ReadCloser, error) {
// StopLiveLocation stops broadcasting live message location
// before Location.LivePeriod expires.
//
// It supports ReplyMarkup.
// This function will panic upon nil Editable.
//
// If the message is sent by the bot, returns it,
// otherwise returns nil and ErrTrueResult.
//
// It supports tb.ReplyMarkup.
// This function will panic upon nil Editable.
func (b *Bot) StopLiveLocation(msg Editable, options ...interface{}) (*Message, error) {
func (b *Bot) StopLiveLocation(msg Editable, opts ...interface{}) (*Message, error) {
msgID, chatID := msg.MessageSig()
params := map[string]string{
@ -1159,7 +1156,7 @@ func (b *Bot) StopLiveLocation(msg Editable, options ...interface{}) (*Message,
"message_id": msgID,
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("stopMessageLiveLocation", params)
@ -1175,7 +1172,8 @@ func (b *Bot) StopLiveLocation(msg Editable, options ...interface{}) (*Message,
//
// It supports ReplyMarkup.
// This function will panic upon nil Editable.
func (b *Bot) StopPoll(msg Editable, options ...interface{}) (*Poll, error) {
//
func (b *Bot) StopPoll(msg Editable, opts ...interface{}) (*Poll, error) {
msgID, chatID := msg.MessageSig()
params := map[string]string{
@ -1183,7 +1181,7 @@ func (b *Bot) StopPoll(msg Editable, options ...interface{}) (*Poll, error) {
"message_id": msgID,
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
data, err := b.Raw("stopPoll", params)
@ -1200,8 +1198,8 @@ func (b *Bot) StopPoll(msg Editable, options ...interface{}) (*Poll, error) {
return resp.Result, nil
}
// GetInviteLink should be used to export chat's invite link.
func (b *Bot) GetInviteLink(chat *Chat) (string, error) {
// InviteLink should be used to export chat's invite link.
func (b *Bot) InviteLink(chat *Chat) (string, error) {
params := map[string]string{
"chat_id": chat.Recipient(),
}
@ -1306,9 +1304,10 @@ func (b *Bot) Leave(chat *Chat) error {
// Pin pins a message in a supergroup or a channel.
//
// It supports tb.Silent option.
// It supports Silent option.
// This function will panic upon nil Editable.
func (b *Bot) Pin(msg Editable, options ...interface{}) error {
//
func (b *Bot) Pin(msg Editable, opts ...interface{}) error {
msgID, chatID := msg.MessageSig()
params := map[string]string{
@ -1316,7 +1315,7 @@ func (b *Bot) Pin(msg Editable, options ...interface{}) error {
"message_id": msgID,
}
sendOpts := extractOptions(options)
sendOpts := extractOptions(opts)
b.embedSendOptions(params, sendOpts)
_, err := b.Raw("pinChatMessage", params)
@ -1324,8 +1323,7 @@ func (b *Bot) Pin(msg Editable, options ...interface{}) error {
}
// Unpin unpins a message in a supergroup or a channel.
//
// It supports tb.Silent option.
// It supports Silent option.
func (b *Bot) Unpin(chat *Chat) error {
params := map[string]string{
"chat_id": chat.Recipient(),
@ -1340,7 +1338,6 @@ func (b *Bot) Unpin(chat *Chat) error {
// Including current name of the user for one-on-one conversations,
// current username of a user, group or channel, etc.
//
// Returns a Chat object on success.
func (b *Bot) ChatByID(id string) (*Chat, error) {
params := map[string]string{
"chat_id": id,
@ -1387,8 +1384,6 @@ func (b *Bot) ProfilePhotosOf(user *User) ([]Photo, error) {
}
// ChatMemberOf returns information about a member of a chat.
//
// Returns a ChatMember object on success.
func (b *Bot) ChatMemberOf(chat *Chat, user *User) (*ChatMember, error) {
params := map[string]string{
"chat_id": chat.Recipient(),
@ -1409,18 +1404,8 @@ func (b *Bot) ChatMemberOf(chat *Chat, user *User) (*ChatMember, error) {
return resp.Result, nil
}
// FileURLByID returns direct url for files using FileId which you can get from File object
func (b *Bot) FileURLByID(fileID string) (string, error) {
f, err := b.FileByID(fileID)
if err != nil {
return "", err
}
return b.URL + "/file/bot" + b.Token + "/" + f.FilePath, nil
}
// GetCommands returns the current list of the bot's commands.
func (b *Bot) GetCommands() ([]Command, error) {
// Commands returns the current list of the bot's commands.
func (b *Bot) Commands() ([]Command, error) {
data, err := b.Raw("getMyCommands", nil)
if err != nil {
return nil, err

@ -472,7 +472,7 @@ func TestBot(t *testing.T) {
}}
assert.NoError(t, b.SetCommands(orig))
cmds, err := b.GetCommands()
cmds, err := b.Commands()
assert.NoError(t, err)
assert.Equal(t, orig, cmds)
})

@ -35,8 +35,6 @@ func (c *Callback) IsInline() bool {
}
// CallbackResponse builds a response to a Callback query.
//
// See also: https://core.telegram.org/bots/api#answerCallbackQuery
type CallbackResponse struct {
// The ID of the callback to which this is a response.
//

@ -55,12 +55,12 @@ type Chat struct {
// ChatPhoto object represents a chat photo.
type ChatPhoto struct {
// File identifiers of small (160x160) chat photo
SmallFileID string `json:"small_file_id"`
SmallFileUniqueID string `json:"small_file_unique_id"`
SmallFileID string `json:"small_file_id"`
SmallUniqueID string `json:"small_file_unique_id"`
// File identifiers of big (640x640) chat photo
BigFileID string `json:"big_file_id"`
BigFileUniqueID string `json:"big_file_unique_id"`
BigFileID string `json:"big_file_id"`
BigUniqueID string `json:"big_file_unique_id"`
}
// Recipient returns chat ID (see Recipient interface).

@ -85,15 +85,15 @@ func (c *nativeContext) Sender() Recipient {
case c.Callback != nil:
return c.Callback.Sender
case c.Query != nil:
return &c.Query.From
return c.Query.Sender
case c.ChosenInlineResult != nil:
return &c.ChosenInlineResult.From
return c.ChosenInlineResult.Sender
case c.ShippingQuery != nil:
return c.ShippingQuery.Sender
case c.PreCheckoutQuery != nil:
return c.PreCheckoutQuery.Sender
case c.PollAnswer != nil:
return &c.PollAnswer.User
return c.PollAnswer.Sender
default:
return nil
}

@ -31,16 +31,17 @@ type GameHighScore struct {
NoEdit bool `json:"disable_edit_message"`
}
// GetGameScores returns the score of the specified user
// GameScores returns the score of the specified user
// and several of their neighbors in a game.
//
// This method will currently return scores for the target user,
// This function will panic upon nil Editable.
//
// Currently, it returns scores for the target user,
// plus two of their closest neighbors on each side.
// Will also return the top three users
// if the user and his neighbors are not among them.
//
// This function will panic upon nil Editable.
func (b *Bot) GetGameScores(user Recipient, msg Editable) ([]GameHighScore, error) {
func (b *Bot) GameScores(user Recipient, msg Editable) ([]GameHighScore, error) {
msgID, chatID := msg.MessageSig()
params := map[string]string{

@ -3,12 +3,14 @@ package telebot
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
)
// ChosenInlineResult represents a result of an inline query that was chosen
// by the user and sent to their chat partner.
type ChosenInlineResult struct {
From User `json:"from"`
Sender *User `json:"from"`
Location *Location `json:"location,omitempty"`
ResultID string `json:"result_id"`
Query string `json:"query"`
@ -23,7 +25,7 @@ type Query struct {
ID string `json:"id"`
// Sender.
From User `json:"from"`
Sender *User `json:"from"`
// Sender location, only for bots that request user location.
Location *Location `json:"location"`
@ -36,7 +38,6 @@ type Query struct {
}
// QueryResponse builds a response to an inline Query.
// See also: https://core.telegram.org/bots/api#answerinlinequery
type QueryResponse struct {
// The ID of the query to which this is a response.
//
@ -124,7 +125,7 @@ func inferIQR(result Result) error {
case *StickerResult:
r.Type = "sticker"
default:
return fmt.Errorf("result %v is not supported", result)
return errors.Errorf("telebot: result %v is not supported", result)
}
return nil

@ -43,7 +43,6 @@ func (r *ResultBase) Process() {
}
// ArticleResult represents a link to an article or web page.
// See also: https://core.telegram.org/bots/api#inlinequeryresultarticle
type ArticleResult struct {
ResultBase
@ -101,7 +100,6 @@ type AudioResult struct {
}
// ContentResult represents a contact with a phone number.
// See also: https://core.telegram.org/bots/api#inlinequeryresultcontact
type ContactResult struct {
ResultBase
@ -128,7 +126,6 @@ type ContactResult struct {
}
// DocumentResult represents a link to a file.
// See also: https://core.telegram.org/bots/api#inlinequeryresultdocument
type DocumentResult struct {
ResultBase
@ -166,7 +163,6 @@ type DocumentResult struct {
}
// GifResult represents a link to an animated GIF file.
// See also: https://core.telegram.org/bots/api#inlinequeryresultgif
type GifResult struct {
ResultBase
@ -204,7 +200,6 @@ type GifResult struct {
}
// LocationResult represents a location on a map.
// See also: https://core.telegram.org/bots/api#inlinequeryresultlocation
type LocationResult struct {
ResultBase
@ -219,7 +214,6 @@ type LocationResult struct {
// ResultMpeg4Gif represents a link to a video animation
// (H.264/MPEG-4 AVC video without sound).
// See also: https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif
type Mpeg4GifResult struct {
ResultBase
@ -257,7 +251,6 @@ type Mpeg4GifResult struct {
}
// ResultResult represents a link to a photo.
// See also: https://core.telegram.org/bots/api#inlinequeryresultphoto
type PhotoResult struct {
ResultBase
@ -292,7 +285,6 @@ type PhotoResult struct {
}
// VenueResult represents a venue.
// See also: https://core.telegram.org/bots/api#inlinequeryresultvenue
type VenueResult struct {
ResultBase
@ -319,7 +311,6 @@ type VenueResult struct {
// VideoResult represents a link to a page containing an embedded
// video player or a video file.
// See also: https://core.telegram.org/bots/api#inlinequeryresultvideo
type VideoResult struct {
ResultBase
@ -360,8 +351,6 @@ type VideoResult struct {
// VoiceResult represents a link to a voice recording in an .ogg
// container encoded with OPUS.
//
// See also: https://core.telegram.org/bots/api#inlinequeryresultvoice
type VoiceResult struct {
ResultBase

@ -2,14 +2,12 @@ package telebot
// InputMessageContent objects represent the content of a message to be sent
// as a result of an inline query.
// See also: https://core.telegram.org/bots/api#inputmessagecontent
type InputMessageContent interface {
IsInputMessageContent() bool
}
// InputTextMessageContent represents the content of a text message to be
// sent as the result of an inline query.
// See also: https://core.telegram.org/bots/api#inputtextmessagecontent
type InputTextMessageContent struct {
// Text of the message to be sent, 1-4096 characters.
Text string `json:"message_text"`
@ -28,7 +26,6 @@ func (input *InputTextMessageContent) IsInputMessageContent() bool {
// InputLocationMessageContent represents the content of a location message
// to be sent as the result of an inline query.
// See also: https://core.telegram.org/bots/api#inputlocationmessagecontent
type InputLocationMessageContent struct {
Lat float32 `json:"latitude"`
Lng float32 `json:"longitude"`
@ -40,7 +37,6 @@ func (input *InputLocationMessageContent) IsInputMessageContent() bool {
// InputVenueMessageContent represents the content of a venue message to
// be sent as the result of an inline query.
// See also: https://core.telegram.org/bots/api#inputvenuemessagecontent
type InputVenueMessageContent struct {
Lat float32 `json:"latitude"`
Lng float32 `json:"longitude"`
@ -61,7 +57,6 @@ func (input *InputVenueMessageContent) IsInputMessageContent() bool {
// InputContactMessageContent represents the content of a contact
// message to be sent as the result of an inline query.
// See also: https://core.telegram.org/bots/api#inputcontactmessagecontent
type InputContactMessageContent struct {
// Contact's phone number.
PhoneNumber string `json:"phone_number"`

@ -6,8 +6,6 @@ import (
// Album lets you group multiple media (so-called InputMedia)
// into a single message.
//
// On older clients albums look like N regular messages.
type Album []InputMedia
// InputMedia is a generic type for all kinds of media you
@ -32,6 +30,7 @@ type Photo struct {
type photoSize struct {
File
Width int `json:"width"`
Height int `json:"height"`
Caption string `json:"caption,omitempty"`
@ -44,8 +43,7 @@ func (p *Photo) MediaFile() *File {
// UnmarshalJSON is custom unmarshaller required to abstract
// away the hassle of treating different thumbnail sizes.
// Instead, Telebot chooses the hi-res one and just sticks to
// it.
// Instead, Telebot chooses the hi-res one and just sticks to it.
//
// I really do find it a beautiful solution.
func (p *Photo) UnmarshalJSON(jsonStr []byte) error {
@ -76,7 +74,6 @@ func (p *Photo) UnmarshalJSON(jsonStr []byte) error {
type Audio struct {
File
// Duration of the recording in seconds as defined by sender.
Duration int `json:"duration,omitempty"`
// (Optional)
@ -114,9 +111,8 @@ func (d *Document) MediaFile() *File {
type Video struct {
File
Width int `json:"width"`
Height int `json:"height"`
Width int `json:"width"`
Height int `json:"height"`
Duration int `json:"duration,omitempty"`
// (Optional)
@ -136,9 +132,8 @@ func (v *Video) MediaFile() *File {
type Animation struct {
File
Width int `json:"width"`
Height int `json:"height"`
Width int `json:"width"`
Height int `json:"height"`
Duration int `json:"duration,omitempty"`
// (Optional)
@ -157,7 +152,6 @@ func (a *Animation) MediaFile() *File {
type Voice struct {
File
// Duration of the recording in seconds as defined by sender.
Duration int `json:"duration"`
// (Optional)
@ -168,8 +162,6 @@ type Voice struct {
// as of v.4.0).
type VideoNote struct {
File
// Duration of the recording in seconds as defined by sender.
Duration int `json:"duration"`
// (Optional)
@ -189,13 +181,11 @@ type Contact struct {
// Location object represents geographic position.
type Location struct {
// Latitude
Lat float32 `json:"latitude"`
// Longitude
Lng float32 `json:"longitude"`
// Period in seconds for which the location will be updated
// (see Live Locations, should be between 60 and 86400.)
// Period in seconds for which the location will be updated,
// should be between 60 and 86400.
LivePeriod int `json:"live_period,omitempty"`
}

@ -293,6 +293,7 @@ func (m *Message) FromChannel() bool {
// Service messages are automatically sent messages, which
// typically occur on some global action. For instance, when
// anyone leaves the chat or chat title changes.
//
func (m *Message) IsService() bool {
fact := false

@ -12,6 +12,7 @@ import (
// flags instead.
//
// Supported options are defined as iota-constants.
//
type Option int
const (
@ -35,6 +36,7 @@ const (
// Despite its power, SendOptions is rather inconvenient to use all
// the way through bot logic, so you might want to consider storing
// and re-using it somewhere or be using Option flags instead.
//
type SendOptions struct {
// If the message is a reply, original message.
ReplyTo *Message
@ -132,7 +134,7 @@ func (r *ReplyMarkup) copy() *ReplyMarkup {
//
// Set either Contact or Location to true in order to request
// sensitive info, such as user's phone number or current location.
// (Available in private chats only.)
//
type ReplyButton struct {
Text string `json:"text"`

@ -119,7 +119,7 @@ func (c Currency) ToTotal(total float64) int {
return int(total) * int(math.Pow(10, float64(c.Exp)))
}
var SupportedCurrencies = map[string]Currency{}
var SupportedCurrencies = make(map[string]Currency)
func init() {
err := json.Unmarshal([]byte(dataCurrencies), &SupportedCurrencies)

@ -9,6 +9,7 @@ import (
// All pollers must implement Poll(), which accepts bot
// pointer and subscription channel and start polling
// synchronously straight away.
//
type Poller interface {
// Poll is supposed to take the bot object
// subscription channel and start polling

@ -35,7 +35,7 @@ type PollOption struct {
// PollAnswer represents an answer of a user in a non-anonymous poll.
type PollAnswer struct {
PollID string `json:"poll_id"`
User User `json:"user"`
Sender *User `json:"user"`
Options []int `json:"option_ids"`
}

@ -19,6 +19,7 @@ type Recipient interface {
// This is pretty cool, since it lets bots implement
// custom Sendables for complex kind of media or
// chat objects spanning across multiple messages.
//
type Sendable interface {
Send(*Bot, Recipient, *SendOptions) (*Message, error)
}

@ -40,8 +40,8 @@ type MaskPosition struct {
Scale float32 `json:"scale"`
}
// UploadStickerFile uploads a .PNG file with a sticker for later use.
func (b *Bot) UploadStickerFile(to Recipient, png *File) (*File, error) {
// UploadSticker uploads a PNG file with a sticker for later use.
func (b *Bot) UploadSticker(to Recipient, png *File) (*File, error) {
files := map[string]File{
"png_sticker": *png,
}
@ -63,8 +63,8 @@ func (b *Bot) UploadStickerFile(to Recipient, png *File) (*File, error) {
return &resp.Result, nil
}
// GetStickerSet returns a StickerSet on success.
func (b *Bot) GetStickerSet(name string) (*StickerSet, error) {
// StickerSet returns a sticker set on success.
func (b *Bot) StickerSet(name string) (*StickerSet, error) {
data, err := b.Raw("getStickerSet", map[string]string{"name": name})
if err != nil {
return nil, err
@ -79,8 +79,8 @@ func (b *Bot) GetStickerSet(name string) (*StickerSet, error) {
return resp.Result, nil
}
// CreateNewStickerSet creates a new sticker set.
func (b *Bot) CreateNewStickerSet(to Recipient, s StickerSet) error {
// CreateStickerSet creates a new sticker set.
func (b *Bot) CreateStickerSet(to Recipient, s StickerSet) error {
files := make(map[string]File)
if s.PNG != nil {
files["png_sticker"] = *s.PNG
@ -98,10 +98,7 @@ func (b *Bot) CreateNewStickerSet(to Recipient, s StickerSet) error {
}
if s.MaskPosition != nil {
data, err := json.Marshal(&s.MaskPosition)
if err != nil {
return err
}
data, _ := json.Marshal(&s.MaskPosition)
params["mask_position"] = string(data)
}
@ -109,8 +106,8 @@ func (b *Bot) CreateNewStickerSet(to Recipient, s StickerSet) error {
return err
}
// AddStickerToSet adds new sticker to existing sticker set.
func (b *Bot) AddStickerToSet(to Recipient, s StickerSet) error {
// AddSticker adds a new sticker to the existing sticker set.
func (b *Bot) AddSticker(to Recipient, s StickerSet) error {
files := make(map[string]File)
if s.PNG != nil {
files["png_sticker"] = *s.PNG
@ -125,10 +122,7 @@ func (b *Bot) AddStickerToSet(to Recipient, s StickerSet) error {
}
if s.MaskPosition != nil {
data, err := json.Marshal(&s.MaskPosition)
if err != nil {
return err
}
data, _ := json.Marshal(&s.MaskPosition)
params["mask_position"] = string(data)
}
@ -136,8 +130,8 @@ func (b *Bot) AddStickerToSet(to Recipient, s StickerSet) error {
return err
}
// SetStickerPositionInSet moves a sticker in set to a specific position.
func (b *Bot) SetStickerPositionInSet(sticker string, position int) error {
// SetStickerPosition moves a sticker in set to a specific position.
func (b *Bot) SetStickerPosition(sticker string, position int) error {
params := map[string]string{
"sticker": sticker,
"position": strconv.Itoa(position),
@ -147,14 +141,14 @@ func (b *Bot) SetStickerPositionInSet(sticker string, position int) error {
return err
}
// DeleteStickerFromSet deletes sticker from set created by the bot.
func (b *Bot) DeleteStickerFromSet(sticker string) error {
// DeleteSticker deletes a sticker from a set created by the bot.
func (b *Bot) DeleteSticker(sticker string) error {
_, err := b.Raw("deleteStickerFromSet", map[string]string{"sticker": sticker})
return err
}
// SetStickerSetThumb sets the thumbnail of a sticker set.
// SetStickerSetThumb sets a thumbnail of the sticker set.
// Animated thumbnails can be set for animated sticker sets only.
//
// Thumbnail must be a PNG image, up to 128 kilobytes in size
@ -164,7 +158,7 @@ func (b *Bot) DeleteStickerFromSet(sticker string) error {
// Animated sticker set thumbnail can't be uploaded via HTTP URL.
//
func (b *Bot) SetStickerSetThumb(to Recipient, s StickerSet) error {
files := map[string]File{}
files := make(map[string]File)
if s.PNG != nil {
files["thumb"] = *s.PNG
} else if s.TGS != nil {

@ -44,6 +44,7 @@ const DefaultApiURL = "https://api.telegram.org"
//
// For convenience, all Telebot-provided endpoints start with
// an "alert" character \a.
//
const (
// Basic message handlers.
//

@ -2,7 +2,6 @@ package telebot
import (
"encoding/json"
"fmt"
"log"
"strconv"
@ -58,7 +57,7 @@ func extractOk(data []byte) error {
err := ErrByDescription(desc)
if err == nil {
code, _ := strconv.Atoi(match[1])
err = fmt.Errorf("telegram unknown: %s (%d)", desc, code)
err = errors.Errorf("telegram unknown: %s (%d)", desc, code)
}
return err
}

@ -146,16 +146,15 @@ func (h *Webhook) waitForStop(stop chan struct{}) {
// and writes them to the update channel.
func (h *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var update Update
err := json.NewDecoder(r.Body).Decode(&update)
if err != nil {
if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
h.bot.debug(fmt.Errorf("cannot decode update: %v", err))
return
}
h.dest <- update
}
// GetWebhook returns current webhook status.
func (b *Bot) GetWebhook() (*Webhook, error) {
// Webhook returns the current webhook status.
func (b *Bot) Webhook() (*Webhook, error) {
data, err := b.Raw("getWebhookInfo", nil)
if err != nil {
return nil, err
@ -165,7 +164,7 @@ func (b *Bot) GetWebhook() (*Webhook, error) {
Result Webhook
}
if err := json.Unmarshal(data, &resp); err != nil {
return nil, err
return nil, wrapError(err)
}
return &resp.Result, nil
}

Loading…
Cancel
Save