1
0
Fork 0

♻️ Methods refactor

This commit is contained in:
Maxim Lebedev 2018-08-21 16:05:04 +05:00
parent d0fcc09b71
commit 3265acc0fc
No known key found for this signature in database
GPG Key ID: F8978F46FF0FFA4F
66 changed files with 422 additions and 464 deletions

View File

@ -44,18 +44,17 @@ func NewAnswerCallbackQuery(callbackQueryID string) *AnswerCallbackQueryParamete
// option to work, you must first create a game for your bot via @Botfather and
// accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX
// that open your bot with a parameter.
func (bot *Bot) AnswerCallbackQuery(params *AnswerCallbackQueryParameters) (bool, error) {
func (bot *Bot) AnswerCallbackQuery(params *AnswerCallbackQueryParameters) (ok bool, err error) {
dst, err := json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodAnswerCallbackQuery)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -48,18 +48,17 @@ func NewAnswerInlineQuery(inlineQueryID string, results ...interface{}) *AnswerI
// AnswerInlineQuery send answers to an inline query. On success, True is returned.
//
// No more than 50 results per query are allowed.
func (bot *Bot) AnswerInlineQuery(params *AnswerInlineQueryParameters) (bool, error) {
func (bot *Bot) AnswerInlineQuery(params *AnswerInlineQueryParameters) (ok bool, err error) {
dst, err := json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodAnswerInlineQuery)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -39,18 +39,17 @@ func NewAnswerPreCheckoutQuery(preCheckoutQueryID string, ok bool) *AnswerPreChe
//
// Note: The Bot API must receive an answer within 10 seconds after the
// pre-checkout query was sent.
func (bot *Bot) AnswerPreCheckoutQuery(params *AnswerShippingQueryParameters) (bool, error) {
func (bot *Bot) AnswerPreCheckoutQuery(params *AnswerShippingQueryParameters) (ok bool, err error) {
dst, err := json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodAnswerPreCheckoutQuery)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -37,18 +37,17 @@ func NewAnswerShippingQuery(shippingQueryID string, ok bool) *AnswerShippingQuer
// If you sent an invoice requesting a shipping address and the parameter
// is_flexible was specified, the Bot API will send an Update with a
// shipping_query field to the bot. On success, True is returned.
func (bot *Bot) AnswerShippingQuery(params *AnswerShippingQueryParameters) (bool, error) {
func (bot *Bot) AnswerShippingQuery(params *AnswerShippingQueryParameters) (ok bool, err error) {
dst, err := json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodAnswerShippingQuery)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -14,18 +14,17 @@ type DeleteChatPhotoParameters struct {
//
// Note: In regular groups (non-supergroups), this method will only work if the
// 'All Members Are Admins' setting is off in the target group.
func (bot *Bot) DeleteChatPhoto(chatID int64) (bool, error) {
func (bot *Bot) DeleteChatPhoto(chatID int64) (ok bool, err error) {
dst, err := json.Marshal(&DeleteChatPhotoParameters{ChatID: chatID})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodDeleteChatPhoto)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -12,18 +12,17 @@ type DeleteChatStickerSetParameters struct {
// in the chat for this to work and must have the appropriate admin rights. Use the field
// can_set_sticker_set optionally returned in getChat requests to check if the bot can use this
// method. Returns True on success.
func (bot *Bot) DeleteChatStickerSet(chatID int64) (bool, error) {
func (bot *Bot) DeleteChatStickerSet(chatID int64) (ok bool, err error) {
dst, err := json.Marshal(&DeleteChatStickerSetParameters{ChatID: chatID})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodDeleteChatStickerSet)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -17,21 +17,20 @@ type DeleteMessageParameters struct {
// 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. Returns True on success.
func (bot *Bot) DeleteMessage(chatID int64, messageID int) (bool, error) {
func (bot *Bot) DeleteMessage(chatID int64, messageID int) (ok bool, err error) {
dst, err := json.Marshal(&DeleteMessageParameters{
ChatID: chatID,
MessageID: messageID,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodDeleteMessage)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -9,18 +9,17 @@ type DeleteStickerFromSetParameters struct {
// DeleteStickerFromSet delete a sticker from a set created by the bot. Returns
// True on success.
func (bot *Bot) DeleteStickerFromSet(sticker string) (bool, error) {
func (bot *Bot) DeleteStickerFromSet(sticker string) (ok bool, err error) {
dst, err := json.Marshal(&DeleteStickerFromSetParameters{Sticker: sticker})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodDeleteStickerFromSet)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -4,13 +4,12 @@ import json "github.com/pquerna/ffjson/ffjson"
// DeleteWebhook remove webhook integration if you decide to switch back to
// getUpdates. Returns True on success. Requires no parameters.
func (bot *Bot) DeleteWebhook() (bool, error) {
func (bot *Bot) DeleteWebhook() (ok bool, err error) {
resp, err := bot.request(nil, MethodDeleteWebhook)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -31,18 +31,18 @@ type EditMessageCaptionParameters struct {
// EditMessageCaption edit captions of messages sent by the bot or via the bot
// (for inline bots). On success, if edited message is sent by the bot, the
// edited Message is returned, otherwise True is returned.
func (bot *Bot) EditMessageCaption(params *EditMessageCaptionParameters) (*Message, error) {
func (bot *Bot) EditMessageCaption(params *EditMessageCaptionParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodEditMessageCaption)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -42,18 +42,18 @@ func NewLiveLocation(latitude, longitude float32) *EditMessageLiveLocationParame
// or editing is explicitly disabled by a call to stopMessageLiveLocation. On
// success, if the edited message was sent by the bot, the edited Message is
// returned, otherwise True is returned.
func (bot *Bot) EditMessageLiveLocation(params *EditMessageLiveLocationParameters) (*Message, error) {
func (bot *Bot) EditMessageLiveLocation(params *EditMessageLiveLocationParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodEditMessageLiveLocation)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -25,18 +25,19 @@ type EditMessageMediaParameters struct {
// edited, new file can't be uploaded. Use previously uploaded file via its
// file_id or specify a URL. On success, if the edited message was sent by the
// bot, the edited Message is returned, otherwise True is returned.
func (b *Bot) EditMessageMedia(emmp *EditMessageMediaParameters) (m *Message, err error) {
func (b *Bot) EditMessageMedia(emmp *EditMessageMediaParameters) (msg *Message, err error) {
var src []byte
src, err = json.Marshal(emmp)
if err != nil {
return nil, err
return
}
resp, err := b.request(src, MethodEditMessageMedia)
if err != nil {
return nil, err
return
}
err = json.Unmarshal(*resp.Result, m)
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -24,18 +24,18 @@ type EditMessageReplyMarkupParameters struct {
// EditMessageReplyMarkup edit only the reply markup of messages sent by the bot
// or via the bot (for inline bots). On success, if edited message is sent by the
// bot, the edited Message is returned, otherwise True is returned.
func (bot *Bot) EditMessageReplyMarkup(params *EditMessageReplyMarkupParameters) (*Message, error) {
func (bot *Bot) EditMessageReplyMarkup(params *EditMessageReplyMarkupParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodEditMessageReplyMarkup)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -41,18 +41,18 @@ func NewMessageText(text string) *EditMessageTextParameters {
// EditMessageText edit text and game messages sent by the bot or via the bot
// (for inline bots). On success, if edited message is sent by the bot, the
// edited Message is returned, otherwise True is returned.
func (bot *Bot) EditMessageText(params *EditMessageTextParameters) (*Message, error) {
func (bot *Bot) EditMessageText(params *EditMessageTextParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodEditMessageText)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -11,18 +11,17 @@ type ExportChatInviteLinkParameters struct {
// ExportChatInviteLink export an invite link to a supergroup or a channel. The
// bot must be an administrator in the chat for this to work and must have the
// appropriate admin rights. Returns exported invite link as String on success.
func (bot *Bot) ExportChatInviteLink(chatID int64) (string, error) {
func (bot *Bot) ExportChatInviteLink(chatID int64) (inviteLink string, err error) {
dst, err := json.Marshal(&ExportChatInviteLinkParameters{ChatID: chatID})
if err != nil {
return "", err
return
}
resp, err := bot.request(dst, MethodExportChatInviteLink)
if err != nil {
return "", err
return
}
var data string
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &inviteLink)
return
}

View File

@ -27,18 +27,18 @@ func NewForwardMessage(from, to int64, messageID int) *ForwardMessageParameters
}
// ForwardMessage forward messages of any kind. On success, the sent Message is returned.
func (bot *Bot) ForwardMessage(params *ForwardMessageParameters) (*Message, error) {
func (bot *Bot) ForwardMessage(params *ForwardMessageParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodForwardMessage)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -11,18 +11,18 @@ type GetChatParameters struct {
// GetChat get up to date information about the chat (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 (bot *Bot) GetChat(chatID int64) (*Chat, error) {
func (bot *Bot) GetChat(chatID int64) (chat *Chat, err error) {
dst, err := json.Marshal(&GetChatParameters{ChatID: chatID})
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetChat)
if err != nil {
return nil, err
return
}
var data Chat
err = json.Unmarshal(*resp.Result, &data)
return &data, err
chat = new(Chat)
err = json.Unmarshal(*resp.Result, chat)
return
}

View File

@ -13,18 +13,17 @@ type GetChatAdministratorsParameters struct {
// 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 (bot *Bot) GetChatAdministrators(chatID int64) ([]ChatMember, error) {
func (bot *Bot) GetChatAdministrators(chatID int64) (members []ChatMember, err error) {
dst, err := json.Marshal(&GetChatAdministratorsParameters{ChatID: chatID})
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetChatAdministrators)
if err != nil {
return nil, err
return
}
var data []ChatMember
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &members)
return
}

View File

@ -12,21 +12,21 @@ type GetChatMemberParameters struct {
// GetChatMember get information about a member of a chat. Returns a ChatMember
// object on success.
func (bot *Bot) GetChatMember(chatID int64, userID int) (*ChatMember, error) {
func (bot *Bot) GetChatMember(chatID int64, userID int) (member *ChatMember, err error) {
dst, err := json.Marshal(&GetChatMemberParameters{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetChatMember)
if err != nil {
return nil, err
return
}
var data ChatMember
err = json.Unmarshal(*resp.Result, &data)
return &data, err
member = new(ChatMember)
err = json.Unmarshal(*resp.Result, member)
return
}

View File

@ -10,18 +10,17 @@ type GetChatMembersCountParameters struct {
// GetChatMembersCount get the number of members in a chat. Returns Int on
// success.
func (bot *Bot) GetChatMembersCount(chatID int64) (int, error) {
func (bot *Bot) GetChatMembersCount(chatID int64) (count int, err error) {
dst, err := json.Marshal(&GetChatMembersCountParameters{ChatID: chatID})
if err != nil {
return 0, err
return
}
resp, err := bot.request(dst, MethodGetChatMembersCount)
if err != nil {
return 0, err
return
}
var data int
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &count)
return
}

View File

@ -18,18 +18,18 @@ type GetFileParameters struct {
// Note: This function may not preserve the original file name and MIME type. You
// should save the file's MIME type and name (if available) when the File object
// is received.
func (bot *Bot) GetFile(fileID string) (*File, error) {
func (bot *Bot) GetFile(fileID string) (file *File, err error) {
dst, err := json.Marshal(&GetFileParameters{FileID: fileID})
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetFile)
if err != nil {
return nil, err
return
}
var data File
err = json.Unmarshal(*resp.Result, &data)
return &data, err
file = new(File)
err = json.Unmarshal(*resp.Result, file)
return
}

View File

@ -30,18 +30,17 @@ func NewGameHighScores(userID int) *GetGameHighScoresParameters {
// GetGameHighScores get data for high score tables. Will return the score of the
// specified user and several of his neighbors in a game. On success, returns an
// Array of GameHighScore objects.
func (bot *Bot) GetGameHighScores(params *GetGameHighScoresParameters) ([]GameHighScore, error) {
func (bot *Bot) GetGameHighScores(params *GetGameHighScoresParameters) (scores []GameHighScore, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetGameHighScores)
if err != nil {
return nil, err
return
}
var data []GameHighScore
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &scores)
return
}

View File

@ -4,13 +4,13 @@ import json "github.com/pquerna/ffjson/ffjson"
// GetMe testing your bot's auth token. Requires no parameters. Returns basic
// information about the bot in form of a User object.
func (bot *Bot) GetMe() (*User, error) {
func (bot *Bot) GetMe() (me *User, err error) {
resp, err := bot.request(nil, MethodGetMe)
if err != nil {
return nil, err
return
}
var data User
err = json.Unmarshal(*resp.Result, &data)
return &data, err
me = new(User)
err = json.Unmarshal(*resp.Result, me)
return
}

View File

@ -8,18 +8,18 @@ type GetStickerSetParameters struct {
}
// GetStickerSet get a sticker set. On success, a StickerSet object is returned.
func (bot *Bot) GetStickerSet(name string) (*StickerSet, error) {
func (bot *Bot) GetStickerSet(name string) (set *StickerSet, err error) {
dst, err := json.Marshal(&GetStickerSetParameters{Name: name})
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetStickerSet)
if err != nil {
return nil, err
return
}
var data StickerSet
err = json.Unmarshal(*resp.Result, &data)
return &data, err
set = new(StickerSet)
err = json.Unmarshal(*resp.Result, set)
return
}

View File

@ -37,18 +37,23 @@ type GetUpdatesParameters struct {
// GetUpdates receive incoming updates using long polling. An Array of
// Update objects is returned.
func (bot *Bot) GetUpdates(params *GetUpdatesParameters) ([]Update, error) {
func (bot *Bot) GetUpdates(params *GetUpdatesParameters) (updates []Update, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetUpdates)
if err != nil {
return nil, err
return
}
data := make([]Update, 100)
err = json.Unmarshal(*resp.Result, &data)
return data, err
if params == nil {
params = new(GetUpdatesParameters)
params.Limit = 100
}
updates = make([]Update, params.Limit)
err = json.Unmarshal(*resp.Result, &updates)
return
}

View File

@ -10,18 +10,18 @@ type GetUserProfilePhotosParameters struct {
}
// GetUserProfilePhotos get a list of profile pictures for a user. Returns a UserProfilePhotos object.
func (bot *Bot) GetUserProfilePhotos(params *GetUserProfilePhotosParameters) (*UserProfilePhotos, error) {
func (bot *Bot) GetUserProfilePhotos(params *GetUserProfilePhotosParameters) (photos *UserProfilePhotos, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodGetUserProfilePhotos)
if err != nil {
return nil, err
return
}
var data UserProfilePhotos
err = json.Unmarshal(*resp.Result, &data)
return &data, err
photos = new(UserProfilePhotos)
err = json.Unmarshal(*resp.Result, photos)
return
}

View File

@ -5,13 +5,13 @@ import json "github.com/pquerna/ffjson/ffjson"
// GetWebhookInfo get current webhook status. Requires no parameters. On success,
// returns a WebhookInfo object. If the bot is using getUpdates, will return an
// object with the url field empty.
func (bot *Bot) GetWebhookInfo() (*WebhookInfo, error) {
func (bot *Bot) GetWebhookInfo() (info *WebhookInfo, err error) {
resp, err := bot.request(nil, MethodGetWebhookInfo)
if err != nil {
return nil, err
return
}
var data WebhookInfo
err = json.Unmarshal(*resp.Result, &data)
return &data, err
info = new(WebhookInfo)
err = json.Unmarshal(*resp.Result, info)
return
}

View File

@ -19,18 +19,17 @@ type KickChatMemberParameters struct {
// Note: In regular groups (non-supergroups), this method will only work if the 'All Members Are
// Admins' setting is off in the target group. Otherwise members may only be removed by the group's
// creator or by the member that added them.
func (bot *Bot) KickChatMember(params *KickChatMemberParameters) (bool, error) {
func (bot *Bot) KickChatMember(params *KickChatMemberParameters) (ok bool, err error) {
dst, err := json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodKickChatMember)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -9,18 +9,17 @@ type LeaveChatParameters struct {
}
// LeaveChat leave a group, supergroup or channel. Returns True on success.
func (bot *Bot) LeaveChat(chatID int64) (bool, error) {
func (bot *Bot) LeaveChat(chatID int64) (ok bool, err error) {
dst, err := json.Marshal(&LeaveChatParameters{ChatID: chatID})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodLeaveChat)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -16,9 +16,10 @@ var ErrUserNotDefined = errors.New("user is not defined")
// received by comparing the received hash parameter with the hexadecimal
// representation of the HMAC-SHA-256 signature of the data-check-string with the
// SHA256 hash of the bot's token used as a secret key.
func (app *App) CheckAuthorization(user *User) (bool, error) {
func (a *App) CheckAuthorization(user *User) (ok bool, err error) {
if user == nil {
return false, ErrUserNotDefined
err = ErrUserNotDefined
return
}
dataCheck := make(url.Values)
@ -37,8 +38,12 @@ func (app *App) CheckAuthorization(user *User) (bool, error) {
dataCheck.Add(KeyUsername, user.Username)
}
secretKey := sha256.Sum256([]byte(app.SecretKey))
secretKey := sha256.Sum256([]byte(a.SecretKey))
hash := hmac.New(sha256.New, secretKey[0:])
_, err := hash.Write([]byte(dataCheck.Encode()))
return hex.EncodeToString(hash.Sum(nil)) == user.Hash, err
if _, err = hash.Write([]byte(dataCheck.Encode())); err != nil {
return
}
ok = hex.EncodeToString(hash.Sum(nil)) == user.Hash
return
}

View File

@ -1,11 +1,9 @@
package login
// App represents a widget which get and validate users authorizations.
type App struct {
SecretKey string
}
type App struct{ SecretKey string }
// New create new app widget for validate authorizations with bot token as secret key.
func New(botToken string) *App {
return &App{SecretKey: botToken}
func New(accessToken string) *App {
return &App{SecretKey: accessToken}
}

View File

@ -17,24 +17,26 @@ type User struct {
}
// ParseUser create User structure from input url.Values.
func ParseUser(src url.Values) (*User, error) {
authDate, err := strconv.Atoi(src.Get(KeyAuthDate))
func ParseUser(src url.Values) (u *User, err error) {
u = new(User)
var ad int
ad, err = strconv.Atoi(src.Get(KeyAuthDate))
if err != nil {
return nil, err
return
}
id, err := strconv.Atoi(src.Get(KeyID))
u.ID, err = strconv.Atoi(src.Get(KeyID))
if err != nil {
return nil, err
return
}
return &User{
AuthDate: int64(authDate),
FirstName: src.Get(KeyFirstName),
Hash: src.Get(KeyHash),
ID: id,
LastName: src.Get(KeyLastName),
PhotoURL: src.Get(KeyPhotoURL),
Username: src.Get(KeyUsername),
}, nil
u.AuthDate = int64(ad)
u.FirstName = src.Get(KeyFirstName)
u.Hash = src.Get(KeyHash)
u.LastName = src.Get(KeyLastName)
u.PhotoURL = src.Get(KeyPhotoURL)
u.Username = src.Get(KeyUsername)
return
}

View File

@ -1,9 +1,6 @@
package login
import (
"fmt"
"time"
)
import "time"
// FullName return user first name only or full name if last name is present.
func (user *User) FullName() string {
@ -11,18 +8,29 @@ func (user *User) FullName() string {
return ""
}
if user.LastName != "" {
return fmt.Sprintln(user.FirstName, user.LastName)
if user.HasLastName() {
return user.FirstName + " " + user.LastName
}
return user.FirstName
}
// AuthTime convert AuthDate field into time.Time.
func (user *User) AuthTime() time.Time {
func (user *User) AuthTime() *time.Time {
if user == nil {
return time.Time{}
return nil
}
return time.Unix(user.AuthDate, 0)
t := time.Unix(user.AuthDate, 0)
return &t
}
// HaveLastName checks what the current user has a LastName.
func (u *User) HasLastName() bool {
return u != nil && u.LastName != ""
}
// HaveUsername checks what the current user has a username.
func (u *User) HasUsername() bool {
return u != nil && u.Username != ""
}

View File

@ -14,18 +14,17 @@ type PinChatMessageParameters struct {
// PinChatMessage pin a message in a supergroup or a channel. The bot must be an administrator in the
// chat for this to work and must have the 'can_pin_messages' admin right in the supergroup or
// 'can_edit_messages' admin right in the channel. Returns True on success.
func (bot *Bot) PinChatMessage(params *PinChatMessageParameters) (bool, error) {
func (bot *Bot) PinChatMessage(params *PinChatMessageParameters) (ok bool, err error) {
dst, err := json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodPinChatMessage)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -2,20 +2,21 @@ package telegram
import (
"errors"
"fmt"
"path"
"strconv"
log "github.com/kirillDanshin/dlog"
json "github.com/pquerna/ffjson/ffjson"
http "github.com/valyala/fasthttp"
)
func (bot *Bot) request(dst []byte, method string) (*Response, error) {
func (bot *Bot) request(dst []byte, method string) (response *Response, err error) {
if bot.Client == nil {
bot.SetClient(defaultClient)
}
requestURI := defaultURI
requestURI.Path = fmt.Sprint("/bot", bot.AccessToken, "/", method)
requestURI.Path = path.Join("bot"+bot.AccessToken, method)
req := http.AcquireRequest()
defer http.ReleaseRequest(req)
@ -25,30 +26,30 @@ func (bot *Bot) request(dst []byte, method string) (*Response, error) {
req.Header.SetMethod("GET")
}
req.Header.SetRequestURI(requestURI.String())
req.Header.SetUserAgent(fmt.Sprint("telegram/", Version))
req.Header.SetUserAgent(path.Join("telegram", strconv.FormatInt(Version, 10)))
req.Header.SetHost(requestURI.Hostname())
req.SetBody(dst)
resp := http.AcquireResponse()
defer http.ReleaseResponse(resp)
err := bot.Client.Do(req, resp)
err = bot.Client.Do(req, resp)
log.Ln("Request:")
log.D(req)
log.Ln("Response:")
log.D(resp)
if err != nil {
return nil, err
return
}
var data Response
if err = json.Unmarshal(resp.Body(), &data); err != nil {
return nil, err
response = new(Response)
if err = json.Unmarshal(resp.Body(), response); err != nil {
return
}
if !data.Ok {
return &data, errors.New(data.Description)
if !response.Ok {
err = errors.New(response.Description)
}
return &data, nil
return
}

View File

@ -55,7 +55,7 @@ func NewAnimation(chatID int64, animation interface{}) *SendAnimationParameters
// sound). On success, the sent Message is returned. Bots can currently send
// animation files of up to 50 MB in size, this limit may be changed in the
// future.
func (bot *Bot) SendAnimation(params *SendAnimationParameters) (*Message, error) {
func (bot *Bot) SendAnimation(params *SendAnimationParameters) (msg *Message, err error) {
args := http.AcquireArgs()
defer http.ReleaseArgs(args)
args.Add("chat_id", strconv.FormatInt(params.ChatID, 10))
@ -80,10 +80,10 @@ func (bot *Bot) SendAnimation(params *SendAnimationParameters) (*Message, error)
resp, err := bot.Upload(MethodSendAnimation, "animation", "", params.Animation, args)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -16,21 +16,20 @@ type SendChatActionParameters struct {
//
// We only recommend using this method when a response from the bot will take a
// noticeable amount of time to arrive.
func (bot *Bot) SendChatAction(chatID int64, action string) (bool, error) {
func (bot *Bot) SendChatAction(chatID int64, action string) (ok bool, err error) {
dst, err := json.Marshal(&SendChatActionParameters{
ChatID: chatID,
Action: action,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodSendChatAction)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -42,18 +42,18 @@ func NewContact(chatID int64, phoneNumber, firstName string) *SendContactParamet
}
// SendContact send phone contacts. On success, the sent Message is returned.
func (bot *Bot) SendContact(params *SendContactParameters) (*Message, error) {
func (bot *Bot) SendContact(params *SendContactParameters) (msg *Message, err error) {
dst, err := json.Marshal(*params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendContact)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -45,7 +45,7 @@ func NewDocument(chatID int64, document interface{}) *SendDocumentParameters {
// SendDocument send general files. On success, the sent Message is returned. Bots can currently send
// files of any type of up to 50 MB in size, this limit may be changed in the future.
func (bot *Bot) SendDocument(params *SendDocumentParameters) (*Message, error) {
func (bot *Bot) SendDocument(params *SendDocumentParameters) (msg *Message, err error) {
args := http.AcquireArgs()
defer http.ReleaseArgs(args)
args.Add("chat_id", strconv.FormatInt(params.ChatID, 10))
@ -70,10 +70,10 @@ func (bot *Bot) SendDocument(params *SendDocumentParameters) (*Message, error) {
resp, err := bot.Upload(MethodSendDocument, "document", "", params.Document, args)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -33,18 +33,18 @@ func NewGame(chatID int64, gameShortName string) *SendGameParameters {
}
// SendGame send a game. On success, the sent Message is returned.
func (bot *Bot) SendGame(params *SendGameParameters) (*Message, error) {
func (bot *Bot) SendGame(params *SendGameParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendGame)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -94,18 +94,18 @@ func NewInvoice(chatID int64, title, description, payload, providerToken, startP
}
// SendInvoice send invoices. On success, the sent Message is returned.
func (bot *Bot) SendInvoice(params *SendInvoiceParameters) (*Message, error) {
func (bot *Bot) SendInvoice(params *SendInvoiceParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendInvoice)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -40,18 +40,18 @@ func NewLocation(chatID int64, latitude, longitude float32) *SendLocationParamet
}
// SendLocation send point on the map. On success, the sent Message is returned.
func (bot *Bot) SendLocation(params *SendLocationParameters) (*Message, error) {
func (bot *Bot) SendLocation(params *SendLocationParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendLocation)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -29,18 +29,17 @@ func NewMediaGroup(chatID int64, media ...interface{}) *SendMediaGroupParameters
// SendMediaGroup send a group of photos or videos as an album. On success, an array of the sent
// Messages is returned.
func (bot *Bot) SendMediaGroup(params *SendMediaGroupParameters) ([]Message, error) {
func (bot *Bot) SendMediaGroup(params *SendMediaGroupParameters) (album []Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendMediaGroup)
if err != nil {
return nil, err
return
}
var data []Message
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &album)
return
}

View File

@ -40,18 +40,18 @@ func NewMessage(chatID int64, text string) *SendMessageParameters {
}
// SendMessage send text messages. On success, the sent Message is returned.
func (bot *Bot) SendMessage(params *SendMessageParameters) (*Message, error) {
func (bot *Bot) SendMessage(params *SendMessageParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendMessage)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -51,7 +51,7 @@ func NewPhoto(chatID int64, photo interface{}) *SendPhotoParameters {
}
// SendPhoto send photos. On success, the sent Message is returned.
func (bot *Bot) SendPhoto(params *SendPhotoParameters) (*Message, error) {
func (bot *Bot) SendPhoto(params *SendPhotoParameters) (msg *Message, err error) {
args := http.AcquireArgs()
defer http.ReleaseArgs(args)
args.Add("chat_id", strconv.FormatInt(params.ChatID, 10))
@ -76,10 +76,10 @@ func (bot *Bot) SendPhoto(params *SendPhotoParameters) (*Message, error) {
resp, err := bot.Upload(MethodSendPhoto, "photo", "", params.Photo, args)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -52,18 +52,18 @@ func NewVenue(chatID int64, latitude, longitude float32, title, address string)
}
// SendVenue send information about a venue. On success, the sent Message is returned.
func (bot *Bot) SendVenue(params *SendVenueParameters) (*Message, error) {
func (bot *Bot) SendVenue(params *SendVenueParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSendVenue)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -13,21 +13,20 @@ type SetChatDescriptionParameters struct {
// SetChatDescription change the description of a supergroup or a channel. The
// bot must be an administrator in the chat for this to work and must have the
// appropriate admin rights. Returns True on success.
func (bot *Bot) SetChatDescription(chatID int64, description string) (bool, error) {
func (bot *Bot) SetChatDescription(chatID int64, description string) (ok bool, err error) {
dst, err := json.Marshal(&SetChatDescriptionParameters{
ChatID: chatID,
Description: description,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodSetChatDescription)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -21,17 +21,16 @@ type SetChatPhotoParameters struct {
//
// Note: In regular groups (non-supergroups), this method will only work if the 'All Members Are
// Admins' setting is off in the target group.
func (bot *Bot) SetChatPhoto(chatID int64, chatPhoto interface{}) (bool, error) {
func (bot *Bot) SetChatPhoto(chatID int64, chatPhoto interface{}) (ok bool, err error) {
args := http.AcquireArgs()
defer http.ReleaseArgs(args)
args.Add("chat_id", strconv.FormatInt(chatID, 10))
resp, err := bot.Upload(MethodSetChatPhoto, TypePhoto, "chat_photo", chatPhoto, args)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -14,21 +14,20 @@ type SetChatStickerSetParameters struct {
// in the chat for this to work and must have the appropriate admin rights. Use the field
// can_set_sticker_set optionally returned in getChat requests to check if the bot can use this
// method. Returns True on success.
func (bot *Bot) SetChatStickerSet(chatID int64, stickerSetName string) (bool, error) {
func (bot *Bot) SetChatStickerSet(chatID int64, stickerSetName string) (ok bool, err error) {
dst, err := json.Marshal(&SetChatStickerSetParameters{
ChatID: chatID,
StickerSetName: stickerSetName,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodSetChatStickerSet)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -16,21 +16,20 @@ type SetChatTitleParameters struct {
//
// Note: In regular groups (non-supergroups), this method will only work if the
// 'All Members Are Admins' setting is off in the target group.
func (bot *Bot) SetChatTitle(chatID int64, title string) (bool, error) {
func (bot *Bot) SetChatTitle(chatID int64, title string) (ok bool, err error) {
dst, err := json.Marshal(&SetChatTitleParameters{
ChatID: chatID,
Title: title,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodSetChatTitle)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -43,18 +43,18 @@ func NewGameScore(userID, score int) *SetGameScoreParameters {
// message was sent by the bot, returns the edited Message, otherwise returns
// True. Returns an error, if the new score is not greater than the user's
// current score in the chat and force is False.
func (bot *Bot) SetGameScore(params *SetGameScoreParameters) (*Message, error) {
func (bot *Bot) SetGameScore(params *SetGameScoreParameters) (msg *Message, err error) {
dst, err := json.Marshal(params)
if err != nil {
return nil, err
return
}
resp, err := bot.request(dst, MethodSetGameScore)
if err != nil {
return nil, err
return
}
var data Message
err = json.Unmarshal(*resp.Result, &data)
return &data, err
msg = new(Message)
err = json.Unmarshal(*resp.Result, msg)
return
}

View File

@ -26,12 +26,12 @@ func (b *Bot) SetPassportDataErrors(userId int, errors []PassportElementError) (
Errors: errors,
})
if err != nil {
return false, err
return
}
resp, err := b.request(dst, MethodSetPassportDataErrors)
if err != nil {
return false, err
return
}
err = json.Unmarshal(*resp.Result, &ok)

View File

@ -11,21 +11,20 @@ type SetStickerPositionInSetParameters struct {
// SetStickerPositionInSet move a sticker in a set created by the bot to a
// specific position. Returns True on success.
func (bot *Bot) SetStickerPositionInSet(sticker string, position int) (bool, error) {
func (bot *Bot) SetStickerPositionInSet(sticker string, position int) (ok bool, err error) {
dst, err := json.Marshal(&SetStickerPositionInSetParameters{
Sticker: sticker,
Position: position,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodSetStickerPositionInSet)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -54,7 +54,7 @@ func NewWebhook(url string, file interface{}) *SetWebhookParameters {
// If you'd like to make sure that the Webhook request comes from Telegram, we
// recommend using a secret path in the URL, e.g. https://www.example.com/<token>.
// Since nobody else knows your bots token, you can be pretty sure its us.
func (bot *Bot) SetWebhook(params *SetWebhookParameters) (bool, error) {
func (bot *Bot) SetWebhook(params *SetWebhookParameters) (ok bool, err error) {
args := http.AcquireArgs()
defer http.ReleaseArgs(args)
args.Add("url", params.URL)
@ -67,26 +67,22 @@ func (bot *Bot) SetWebhook(params *SetWebhookParameters) (bool, error) {
args.Add("max_connections", strconv.Itoa(params.MaxConnections))
}
var (
err error
resp *Response
)
var resp *Response
if params.Certificate != nil {
resp, err = bot.Upload(MethodSetWebhook, "certificate", "cert.pem", params.Certificate, args)
} else {
var dst []byte
dst, err = json.Marshal(params)
if err != nil {
return false, err
return
}
resp, err = bot.request(dst, MethodSetWebhook)
}
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -14,21 +14,20 @@ type UnbanChatMemberParameters struct {
// user will not return to the group or channel automatically, but will be able
// to join via link, etc. The bot must be an administrator for this to work.
// Returns True on success.
func (bot *Bot) UnbanChatMember(chatID int64, userID int) (bool, error) {
func (bot *Bot) UnbanChatMember(chatID int64, userID int) (ok bool, err error) {
dst, err := json.Marshal(&UnbanChatMemberParameters{
ChatID: chatID,
UserID: userID,
})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodUnbanChatMember)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -11,18 +11,17 @@ type UnpinChatMessageParameters struct {
// UnpinChatMessage unpin a message in a supergroup chat. The bot must be an
// administrator in the chat for this to work and must have the appropriate admin
// rights. Returns True on success.
func (bot *Bot) UnpinChatMessage(chatID int64) (bool, error) {
func (bot *Bot) UnpinChatMessage(chatID int64) (ok bool, err error) {
dst, err := json.Marshal(&UnpinChatMessageParameters{ChatID: chatID})
if err != nil {
return false, err
return
}
resp, err := bot.request(dst, MethodUnpinChatMessage)
if err != nil {
return false, err
return
}
var data bool
err = json.Unmarshal(*resp.Result, &data)
return data, err
err = json.Unmarshal(*resp.Result, &ok)
return
}

View File

@ -8,6 +8,8 @@ import (
"mime/multipart"
"net/url"
"os"
"path"
"strconv"
log "github.com/kirillDanshin/dlog"
json "github.com/pquerna/ffjson/ffjson"
@ -54,16 +56,16 @@ voice notes will be sent as files.
* Other configurations may work but we can't guarantee that they will.
*/
func (bot *Bot) Upload(method, key, name string, file InputFile, args fmt.Stringer) (*Response, error) {
func (bot *Bot) Upload(method, key, name string, file InputFile, args fmt.Stringer) (response *Response, err error) {
buffer := bytes.NewBuffer(nil)
multi := multipart.NewWriter(buffer)
requestURI := defaultURI
requestURI.Path = fmt.Sprint("/bot", bot.AccessToken, "/", method)
requestURI.Path = path.Join("bot"+bot.AccessToken, method)
query, err := url.ParseQuery(args.String())
if err != nil {
return nil, err
return
}
for key, val := range query {
@ -73,11 +75,11 @@ func (bot *Bot) Upload(method, key, name string, file InputFile, args fmt.String
}
if err = createFileField(multi, file, key, name); err != nil {
return nil, err
return
}
if err = multi.Close(); err != nil {
return nil, err
return
}
req := http.AcquireRequest()
@ -86,7 +88,7 @@ func (bot *Bot) Upload(method, key, name string, file InputFile, args fmt.String
req.Header.SetContentType(multi.FormDataContentType())
req.Header.SetMethod("POST")
req.Header.SetRequestURI(requestURI.String())
req.Header.SetUserAgent(fmt.Sprint("telegram/", Version))
req.Header.SetUserAgent(path.Join("telegram", strconv.FormatInt(Version, 10)))
req.Header.SetHost(requestURI.Hostname())
log.Ln("Request:")
@ -99,19 +101,19 @@ func (bot *Bot) Upload(method, key, name string, file InputFile, args fmt.String
log.Ln("Resp:")
log.D(resp)
if err != nil {
return nil, err
return
}
var data Response
if err = json.Unmarshal(resp.Body(), &data); err != nil {
return nil, err
response = new(Response)
if err = json.Unmarshal(resp.Body(), response); err != nil {
return
}
if !data.Ok {
return nil, errors.New(data.Description)
if !response.Ok {
err = errors.New(response.Description)
}
return &data, nil
return
}
func createFileField(w *multipart.Writer, file interface{}, key, val string) error {

View File

@ -1,7 +1,6 @@
package telegram
import (
"fmt"
"net/url"
"strconv"
)
@ -26,15 +25,15 @@ func NewInlineMentionURL(userID int) *url.URL {
}
func NewMarkdownBold(text string) string {
return fmt.Sprint("*", text, "*")
return "*" + text + "*"
}
func NewMarkdownItalic(text string) string {
return fmt.Sprint("_", text, "_")
return "_" + text + "_"
}
func NewMarkdownURL(text string, link *url.URL) string {
return fmt.Sprint("[", text, "](", link.String(), ")")
return "[" + text + "](" + link.String() + ")"
}
func NewMarkdownMention(text string, id int) string {
@ -43,23 +42,23 @@ func NewMarkdownMention(text string, id int) string {
}
func NewMarkdownCode(text string) string {
return fmt.Sprint("`", text, "`")
return "`" + text + "`"
}
func NewMarkdownCodeBlock(text string) string {
return fmt.Sprint("```", text, "```")
return "```" + text + "```"
}
func NewHtmlBold(text string) string {
return fmt.Sprint("<b>", text, "</b>")
return "<b>" + text + "</b>"
}
func NewHtmlItalic(text string) string {
return fmt.Sprint("<i>", text, "</i>")
return "<i>" + text + "</i>"
}
func NewHtmlURL(text string, link *url.URL) string {
return fmt.Sprint(`<a href="`, link.String(), `">`, text, `</a>`)
return `<a href="` + link.String() + `">` + text + `</a>`
}
func NewHtmlMention(text string, id int) string {
@ -68,9 +67,9 @@ func NewHtmlMention(text string, id int) string {
}
func NewHtmlCode(text string) string {
return fmt.Sprint("<code>", text, "</code>")
return "<code>" + text + "</code>"
}
func NewHtmlCodeBlock(text string) string {
return fmt.Sprint("<pre>", text, "</pre>")
return "<pre>" + text + "</pre>"
}

View File

@ -1,9 +1,5 @@
package telegram
import (
"strings"
)
func (a *Audio) FullName(sep string) (name string) {
if !a.HasTitle() {
return
@ -18,11 +14,11 @@ func (a *Audio) FullName(sep string) (name string) {
}
func (a *Audio) HasPerformer() bool {
return a != nil && !strings.EqualFold(a.Performer, "")
return a != nil && a.Performer != ""
}
func (a *Audio) HasTitle() bool {
return a != nil && !strings.EqualFold(a.Title, "")
return a != nil && a.Title != ""
}
func (a *Audio) HasThumb() bool {

View File

@ -1,7 +1,6 @@
package telegram
import (
"fmt"
"net/url"
"path"
"strings"
@ -36,20 +35,15 @@ func New(accessToken string) (*Bot, error) {
// IsMessageFromMe checks that the input message is a message from the current
// bot.
func (b *Bot) IsMessageFromMe(m *Message) bool {
return m != nil &&
b != nil &&
m.From != nil &&
b.User != nil &&
m.From.ID == b.ID
return b != nil && b.User != nil &&
m != nil && m.From != nil && m.From.ID == b.ID
}
// IsForwardFromMe checks that the input message is a forwarded message from the
// current bot.
func (b *Bot) IsForwardFromMe(m *Message) bool {
return m.IsForward() &&
b != nil &&
b.User != nil &&
m.ForwardFrom.ID == b.ID
return b != nil && b.User != nil &&
m.IsForward() && m.ForwardFrom.ID == b.ID
}
// IsReplyToMe checks that the input message is a reply to the current bot.
@ -78,9 +72,8 @@ func (b *Bot) IsCommandToMe(m *Message) bool {
// IsMessageMentionsMe checks that the input message mentions the current bot.
func (b *Bot) IsMessageMentionsMe(m *Message) bool {
if m == nil ||
b == nil ||
b.User == nil {
if b == nil || b.User == nil ||
m == nil {
return false
}
@ -97,10 +90,8 @@ func (b *Bot) IsMessageMentionsMe(m *Message) bool {
}
for _, entity := range entities {
if entity.IsMention() {
if b.ID == entity.User.ID {
return true
}
if entity.IsMention() && entity.User.ID == b.ID {
return true
}
}
@ -136,23 +127,20 @@ func (b *Bot) IsMessageToMe(m *Message) bool {
// NewFileURL creates a url.URL to file with path getted from GetFile method.
func (b *Bot) NewFileURL(filePath string) *url.URL {
if b == nil ||
strings.EqualFold(b.AccessToken, "") ||
strings.EqualFold(filePath, "") {
if b == nil || b.AccessToken == "" ||
filePath == "" {
return nil
}
result := defaultURI
result.Path = path.Join("file", fmt.Sprint("bot", b.AccessToken), filePath)
result.Path = path.Join("file", "bot"+b.AccessToken, filePath)
return result
}
// NewRedirectURL creates new url.URL for redirecting from one chat to another.
func (b *Bot) NewRedirectURL(param string, group bool) *url.URL {
if b == nil ||
b.User == nil ||
b.User.Username == "" {
if b == nil || b.User == nil || b.User.Username == "" {
return nil
}

View File

@ -1,9 +1,6 @@
package telegram
import (
"fmt"
"strings"
)
import "strings"
// IsPrivate checks that the current chat is a private chat with single user.
func (c *Chat) IsPrivate() bool {
@ -32,7 +29,7 @@ func (c *Chat) HasPinnedMessage() bool {
// HasStickerSet checks that the current chat has a sticker set.
func (c *Chat) HasStickerSet() bool {
return c != nil && !strings.EqualFold(c.StickerSetName, "")
return c != nil && c.StickerSetName != ""
}
// StickerSet return StickerSet structure if StickerSetName is available.
@ -56,7 +53,7 @@ func (c *Chat) FullName() string {
}
if c.HasLastName() {
return fmt.Sprintln(c.FirstName, c.LastName)
return c.FirstName + " " + c.LastName
}
return c.FirstName
@ -64,18 +61,18 @@ func (c *Chat) FullName() string {
// HaveLastName checks what the current user has a LastName.
func (c *Chat) HasLastName() bool {
return c != nil && !strings.EqualFold(c.LastName, "")
return c != nil && c.LastName != ""
}
// HaveUsername checks what the current user has a username.
func (c *Chat) HasUsername() bool {
return c != nil && !strings.EqualFold(c.Username, "")
return c != nil && c.Username != ""
}
func (c *Chat) HasDescription() bool {
return c != nil && !strings.EqualFold(c.Description, "")
return c != nil && c.Description != ""
}
func (c *Chat) HasInviteLink() bool {
return c != nil && !strings.EqualFold(c.InviteLink, "")
return c != nil && c.InviteLink != ""
}

View File

@ -1,10 +1,5 @@
package telegram
import (
"fmt"
"strings"
)
// FullName returns the full name of contact or FirstName if LastName is not
// available.
func (c *Contact) FullName() string {
@ -13,7 +8,7 @@ func (c *Contact) FullName() string {
}
if c.HasLastName() {
return fmt.Sprint(c.FirstName, " ", c.LastName)
return c.FirstName + " " + c.LastName
}
return c.FirstName
@ -21,7 +16,7 @@ func (c *Contact) FullName() string {
// HaveLastName checks what the current contact has a LastName.
func (c *Contact) HasLastName() bool {
return c != nil && !strings.EqualFold(c.LastName, "")
return c != nil && c.LastName != ""
}
func (c *Contact) HasTelegram() bool {
@ -29,5 +24,5 @@ func (c *Contact) HasTelegram() bool {
}
func (c *Contact) HasVCard() bool {
return c != nil && !strings.EqualFold(c.VCard, "")
return c != nil && c.VCard != ""
}

View File

@ -1,16 +1,13 @@
package telegram
import (
"fmt"
"net/url"
"strings"
)
// ParseURL selects URL from entered text of message and parse it as url.URL.
func (e *MessageEntity) ParseURL(messageText string) *url.URL {
if e == nil ||
!e.IsURL() ||
strings.EqualFold(messageText, "") {
if e == nil || !e.IsURL() || messageText == "" {
return nil
}
@ -22,8 +19,8 @@ func (e *MessageEntity) ParseURL(messageText string) *url.URL {
}
link, err := url.Parse(string(text[from:to]))
if err == nil && strings.EqualFold(link.Scheme, "") {
link, err = url.Parse(fmt.Sprint("http://", link))
if err == nil && link.Scheme == "" {
link, err = url.Parse("http://" + link.String())
}
if err != nil {
return nil

View File

@ -95,13 +95,13 @@ func (m *Message) ForwardTime() *time.Time {
}
// EditTime parse current message EditDate and returns time.Time.
func (m *Message) EditTime() time.Time {
var t time.Time
func (m *Message) EditTime() *time.Time {
if m == nil || !m.HasBeenEdited() {
return t
return nil
}
return time.Unix(m.EditDate, 0)
et := time.Unix(m.EditDate, 0)
return &et
}
// HasBeenEdited checks that the current message has been edited.
@ -111,142 +111,142 @@ func (m *Message) HasBeenEdited() bool {
// IsText checks that the current message is just a text message.
func (m *Message) IsText() bool {
return m != nil && !strings.EqualFold(m.Text, "")
return m != nil && m.Text != ""
}
// IsAudio checks that the current message is a audio.
func (m *Message) IsAudio() bool {
return !m.IsText() && m.Audio != nil
return m != nil && m.Audio != nil
}
// IsDocument checks that the current message is a document.
func (m *Message) IsDocument() bool {
return !m.IsText() && m.Document != nil
return m != nil && m.Document != nil
}
// IsGame checks that the current message is a game.
func (m *Message) IsGame() bool {
return !m.IsText() && m.Game != nil
return m != nil && m.Game != nil
}
// IsPhoto checks that the current message is a photo.
func (m *Message) IsPhoto() bool {
return !m.IsText() && len(m.Photo) > 0
return m != nil && len(m.Photo) > 0
}
// IsSticker checks that the current message is a sticker.
func (m *Message) IsSticker() bool {
return !m.IsText() && m.Sticker != nil
return m != nil && m.Sticker != nil
}
// IsVideo checks that the current message is a video.
func (m *Message) IsVideo() bool {
return !m.IsText() && m.Video != nil
return m != nil && m.Video != nil
}
// IsVoice checks that the current message is a voice.
func (m *Message) IsVoice() bool {
return !m.IsText() && m.Voice != nil
return m != nil && m.Voice != nil
}
// IsVideoNote checks that the current message is a video note.
func (m *Message) IsVideoNote() bool {
return !m.IsText() && m.VideoNote != nil
return m != nil && m.VideoNote != nil
}
// IsContact checks that the current message is a contact.
func (m *Message) IsContact() bool {
return !m.IsText() && m.Contact != nil
return m != nil && m.Contact != nil
}
// IsLocation checks that the current message is a location.
func (m *Message) IsLocation() bool {
return !m.IsText() && m.Location != nil
return m != nil && m.Location != nil
}
// IsVenue checks that the current message is a venue.
func (m *Message) IsVenue() bool {
return !m.IsText() && m.Venue != nil
return m != nil && m.Venue != nil
}
// IsAnimation checks that the current message is a animation.
func (m *Message) IsAnimation() bool {
return !m.IsText() && m.Animation != nil
return m != nil && m.Animation != nil
}
// IsNewChatMembersEvent checks that the current message is a event of entry of
// new members.
func (m *Message) IsNewChatMembersEvent() bool {
return !m.IsText() && len(m.NewChatMembers) > 0
return m != nil && len(m.NewChatMembers) > 0
}
// IsLeftChatMemberEvent checks that the current message is a event of members
// exit.
func (m *Message) IsLeftChatMemberEvent() bool {
return !m.IsText() && m.LeftChatMember != nil
return m != nil && m.LeftChatMember != nil
}
// IsNewChatTitleEvent checks that the current message is a event of setting a
// new chat title.
func (m *Message) IsNewChatTitleEvent() bool {
return !m.IsText() && !strings.EqualFold(m.NewChatTitle, "")
return m != nil && !strings.EqualFold(m.NewChatTitle, "")
}
// IsNewChatPhotoEvent checks that the current message is a event of setting a
// new chat avatar.
func (m *Message) IsNewChatPhotoEvent() bool {
return !m.IsText() && len(m.NewChatPhoto) > 0
return m != nil && len(m.NewChatPhoto) > 0
}
// IsDeleteChatPhotoEvent checks that the current message is a event of deleting
// a chat avatar.
func (m *Message) IsDeleteChatPhotoEvent() bool {
return !m.IsText() && m.DeleteChatPhoto
return m != nil && m.DeleteChatPhoto
}
// IsGroupChatCreatedEvent checks that the current message is a event of creating
// a new group.
func (m *Message) IsGroupChatCreatedEvent() bool {
return !m.IsText() && m.GroupChatCreated
return m != nil && m.GroupChatCreated
}
// IsSupergroupChatCreatedEvent checks that the current message is a event of
// creating a new supergroup.
func (m *Message) IsSupergroupChatCreatedEvent() bool {
return !m.IsText() && m.SupergroupChatCreated
return m != nil && m.SupergroupChatCreated
}
// IsChannelChatCreatedEvent checks that the current message is a event of
// creating a new channel.
func (m *Message) IsChannelChatCreatedEvent() bool {
return !m.IsText() && m.ChannelChatCreated
return m != nil && m.ChannelChatCreated
}
// IsPinnedMessage checks that the current message is a event of pinning another
// message.
func (m *Message) IsPinnedMessage() bool {
return !m.IsText() && m.PinnedMessage != nil
return m != nil && m.PinnedMessage != nil
}
// IsInvoice checks that the current message is a invoice.
func (m *Message) IsInvoice() bool {
return !m.IsText() && m.Invoice != nil
return m != nil && m.Invoice != nil
}
// IsSuccessfulPayment checks that the current message is a event of successful
// payment.
func (m *Message) IsSuccessfulPayment() bool {
return !m.IsText() && m.SuccessfulPayment != nil
return m != nil && m.SuccessfulPayment != nil
}
// HasEntities checks that the current message contains entities.
func (m *Message) HasEntities() bool {
return m.IsText() && len(m.Entities) > 0
return m != nil && len(m.Entities) > 0
}
// HasCaptionEntities checks that the current media contains entities in caption.
func (m *Message) HasCaptionEntities() bool {
return !m.IsText() && len(m.CaptionEntities) > 0
return m != nil && len(m.CaptionEntities) > 0
}
// HasMentions checks that the current message contains mentions.
@ -281,12 +281,12 @@ func (m *Message) HasCaptionMentions() bool {
// HasCaption checks that the current media has caption.
func (m *Message) HasCaption() bool {
return !m.IsText() && !strings.EqualFold(m.Caption, "")
return m != nil && m.Caption != ""
}
// HasAuthorSignature checks that the current channel post has author signature.
func (m *Message) HasAuthorSignature() bool {
return m != nil && !strings.EqualFold(m.AuthorSignature, "")
return m != nil && m.AuthorSignature != ""
}
// IsEvent checks what current message is a any chat event.

View File

@ -1,12 +1,10 @@
package telegram
import "strings"
// InSet checks that the current sticker in the stickers set.
//
// For uploaded WebP files this return false.
func (s *Sticker) InSet() bool {
return s != nil && !strings.EqualFold(s.SetName, "")
return s != nil && s.SetName != ""
}
// Set use bot for getting parent StickerSet if SetName is present.

View File

@ -1,11 +1,6 @@
package telegram
import (
"fmt"
"strings"
"golang.org/x/text/language"
)
import "golang.org/x/text/language"
// Language parse LanguageCode of current user and returns language.Tag.
func (u *User) Language() *language.Tag {
@ -29,7 +24,7 @@ func (u *User) FullName() string {
}
if u.HasLastName() {
return fmt.Sprint(u.FirstName, " ", u.LastName)
return u.FirstName + " " + u.LastName
}
return u.FirstName
@ -37,10 +32,10 @@ func (u *User) FullName() string {
// HaveLastName checks what the current user has a LastName.
func (u *User) HasLastName() bool {
return u != nil && !strings.EqualFold(u.LastName, "")
return u != nil && u.LastName != ""
}
// HaveUsername checks what the current user has a username.
func (u *User) HasUsername() bool {
return u != nil && !strings.EqualFold(u.Username, "")
return u != nil && u.Username != ""
}