telegram

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 20, 2018 License: MIT Imports: 15 Imported by: 2

README

telegram

telegram is a simple Telegram Bot API client.

Principles

Good design is honest. Dieter Rams

Types must be clear about its fields' type and optionality. Because of this some ids are int64. And some fields are pointers to bool, int, or string.

Types in the package explicitly mirror types of Telegram Bot API.

Installation

go get -u github.com/koorgoo/telegram

Examples

Documentation

Index

Constants

View Source
const (
	ModeDefault  ParseMode = 0
	ModeMarkdown           = 1
	ModeHTML               = 2
)

Parse modes.

Variables

View Source
var (
	ErrNotDeleted  = errors.New("telegram: message not deleted")
	ErrNotEdited   = errors.New("telegram: message not edited")
	ErrNotAnswered = errors.New("telegram: query not answered")
)
View Source
var ErrEmptyToken = errors.New("telegram: empty token")

Functions

This section is empty.

Types

type Audio

type Audio struct {
	FileID    string  `json:"file_id"`
	Duration  int     `json:"duration"`
	Performer *string `json:"performer"`
	Title     *string `json:"title"`
	MimeType  *string `json:"mime_type"`
	FileSize  *int    `json:"file_size"`
}

https://core.telegram.org/bots/api#audio

type AudioMessage

type AudioMessage struct {
	ChatID              int64     `json:"chat_id"`
	Audio               InputFile `json:"-"`
	AudioID             string    `json:"audio"`
	Caption             string    `json:"caption,omitempty"`
	Duration            int       `json:"duration,omitempty"`
	Performer           string    `json:"performer,omitempty"`
	Title               string    `json:"title,omitempty"`
	DisableNotification bool      `json:"disable_notification,omitempty"`
	ReplyToMessageID    int       `json:"reply_to_message_id,omitempty"`
	ReplyMarkup         Markup    `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#sendaudio

func (*AudioMessage) Multipart

func (m *AudioMessage) Multipart() *Multipart

Multipart implements Multiparter interface.

type Bot

type Bot interface {
	Username() string
	Updates() <-chan *Update
	Errors() <-chan error

	GetMe(context.Context) (*User, error)
	GetUpdates(context.Context, ...UpdatesOption) ([]*Update, error)

	SendMessage(context.Context, *TextMessage) (*Message, error)
	ForwardMessage(context.Context, *ForwardedMessage) (*Message, error)

	EditMessageText(context.Context, *MessageText) (*Message, error)
	EditMessageCaption(context.Context, *MessageCaption) (*Message, error)
	EditMessageReplyMarkup(context.Context, *MessageReplyMarkup) (*Message, error)
	DeleteMessage(context.Context, *DeletedMessage) error
}

func NewBot

func NewBot(ctx context.Context, token string, opts ...BotOption) (Bot, error)

type BotOption

type BotOption func(*botOptions)

func WithErrTimeout

func WithErrTimeout(t time.Duration) BotOption

func WithPollTimeout

func WithPollTimeout(t time.Duration) BotOption

func WithSOCKS5 added in v0.2.0

func WithSOCKS5(v SOCKS5) BotOption

func WithUsername

func WithUsername(s string) BotOption

func WithoutUpdates

func WithoutUpdates() BotOption

type CallbackQuery

type CallbackQuery struct {
	ID              string   `json:"id"`
	From            User     `json:"from"`
	Message         *Message `json:"message"`
	InlineMessageID *string  `json:"inline_message_id"`
	ChatInstance    string   `json:"chat_instance"`
	Data            *string  `json:"data"`
}

https://core.telegram.org/bots/api#callbackquery

type CallbackQueryAnswer

type CallbackQueryAnswer struct {
	CallbackQueryID string `json:"callback_query_id"`
	Text            string `json:"text,omitempty"`
	ShowAlert       bool   `json:"show_alert,omitempty"`
	URL             string `json:"url,omitempty"`
	CacheTime       int    `json:"cache_time,omitempty"`
}

https://core.telegram.org/bots/api#answercallbackquery

type Chat

type Chat struct {
	ID                          int64      `json:"id"`
	Type                        string     `json:"type"`
	Title                       *string    `json:"title"`
	Username                    *string    `json:"username"`
	FirstName                   *string    `json:"first_name"`
	LastName                    *string    `json:"last_name"`
	AllMembersAreAdministrators *bool      `json:"all_members_are_administrators"`
	ChatPhoto                   *ChatPhoto `json:"chat_photo"`
	Description                 *string    `json:"description"`
	InviteLink                  *string    `json:"invite_link"`
}

https://core.telegram.org/bots/api#chat

func (*Chat) IsChannel

func (c *Chat) IsChannel() bool

func (*Chat) IsGroup

func (c *Chat) IsGroup() bool

func (*Chat) IsPrivate

func (c *Chat) IsPrivate() bool

func (*Chat) IsSupergroup

func (c *Chat) IsSupergroup() bool

type ChatID

type ChatID int64

TODO: Replace

type ChatMember

type ChatMember struct {
	User      User   `json:"user"`
	Status    string `json:"status"`
	UntilDate *int   `json:"until_date"`
	// Administrators only.
	CanBeEdited           *bool `json:"can_be_edited"`
	CanChangeInfo         *bool `json:"can_change_info"`
	CanPostMessages       *bool `json:"can_post_messages"`
	CanEditMessages       *bool `json:"can_edit_messages"`
	CanDeleteMessages     *bool `json:"can_delete_messages"`
	CanInviteUsers        *bool `json:"can_invite_users"`
	CanRestrictMembers    *bool `json:"can_restrict_members"`
	CanPinMessages        *bool `json:"can_pin_messages"`
	CanPromoteMembers     *bool `json:"can_promote_members"`
	CanSendMessages       *bool `json:"can_send_messages"`
	CanSendMediaMessages  *bool `json:"can_send_media_messages"`
	CanSendOtherMessages  *bool `json:"can_send_other_messages"`
	CanAddWebPagePreviews *bool `json:"can_add_web_page_previews"`
}

https://core.telegram.org/bots/api#chatmember

type ChatPhoto

type ChatPhoto struct {
	SmallFileID string `json:"small_file_id"`
	BigFileID   string `json:"big_file_id"`
}

https://core.telegram.org/bots/api#chatphoto

type Command

type Command struct {
	Name string
	Args []string
	From User
	Chat Chat
	Date int
}

Command represents a command parsed from update's message. Args is a list of words right after the command in the message.

type CommandFunc

type CommandFunc func(*Command, *Update) error

CommandFunc represents a function ran on every command. The function is ran in a separate goroutine.

type Commands

type Commands interface {
	Add(name string, fn CommandFunc)
	Run(*Update) (error, bool)
}

Commands is the interface of a generic commands register/runner.

func NewCommands

func NewCommands(username string) Commands

type Contact

type Contact struct {
	PhoneNumber string
	FirstName   string
	LastName    *string
	UserID      *int
}

https://core.telegram.org/bots/api#contact

type DeletedMessage

type DeletedMessage struct {
	ChatID    int64 `json:"chat_id"`
	MessageID int   `json:"message_id"`
}

https://core.telegram.org/bots/api#deletemessage

type Document

type Document struct {
	FileID   string     `json:"file_id"`
	Thumb    *PhotoSize `json:"thumb"`
	FileName *string    `json:"file_name"`
	MimeType *string    `json:"mime_type"`
	FileSize *int       `json:"file_size"`
}

https://core.telegram.org/bots/api#document

type DocumentMessage

type DocumentMessage struct {
	ChatID              int64     `json:"chat_id"`
	Document            InputFile `json:"document"`
	Caption             string    `json:"caption,omitempty"`
	DisableNotification bool      `json:"disable_notification,omitempty"`
	ReplyToMessageID    int       `json:"reply_to_message_id,omitempty"`
	ReplyMarkup         Markup    `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#senddocument

func (*DocumentMessage) Multipart

func (m *DocumentMessage) Multipart() *Multipart

Multipart implements Multiparter interface.

type Error

type Error struct {
	ErrorCode   int
	Description string
	Parameters  *ResponseParameters
}

Error represents an error returned by API. It satisfies error interface.

func (*Error) Error

func (e *Error) Error() string

Error returns an error string.

type File

type File struct {
	FileID   string  `json:"file_id"`
	FileSize *int    `json:"file_size"`
	FilePath *string `json:"file_path"`
}

https://core.telegram.org/bots/api#file

type ForceReply

type ForceReply struct {
	ForeceReply bool `json:"force_reply"`
	Selective   bool `json:"selective"`
}

https://core.telegram.org/bots/api#forcereply

func (*ForceReply) MarshalJSON

func (m *ForceReply) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*ForceReply) UnmarshalJSON

func (m *ForceReply) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type ForwardedMessage

type ForwardedMessage struct {
	ChatID              int64 `json:"chat_id"`
	FromChatID          int64 `json:"from_chat_id"`
	DisableNotification bool  `json:"disable_notification,omitempty"`
	MessageID           int   `json:"message_id"`
}

https://core.telegram.org/bots/api#forwardmessage

type InlineKeyboardButton

type InlineKeyboardButton struct {
	Text                         string `json:"text"`
	URL                          string `json:"url,omitempty"`
	CallbackData                 string `json:"callback_data,omitempty"`
	SwitchInlineQuery            string `json:"switch_inline_query,omitempty"`
	SwitchInlineQueryCurrentChat string `json:"switch_inline_query_current_chat,omitempty"`
}

https://core.telegram.org/bots/api#inlinekeyboardbutton

type InlineKeyboardMarkup

type InlineKeyboardMarkup struct {
	InlineKeyboard [][]*InlineKeyboardButton `json:"inline_keyboard"`
}

https://core.telegram.org/bots/api#inlinekeyboardmarkup

func (*InlineKeyboardMarkup) MarshalJSON

func (m *InlineKeyboardMarkup) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*InlineKeyboardMarkup) UnmarshalJSON

func (m *InlineKeyboardMarkup) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type InputFile

type InputFile interface {
	io.Reader
	Name() string
}

https://core.telegram.org/bots/api#inputfile

type KeyboardButton

type KeyboardButton struct {
	Text            string `json:"text"`
	RequestContact  bool   `json:"request_contact,omitempty"`
	RequestLocation bool   `json:"request_location,omitempty"`
}

https://core.telegram.org/bots/api#keyboardbutton

type Location

type Location struct {
	Longitude float32 `json:"longitude"`
	Latitude  float32 `json:"latitude"`
}

https://core.telegram.org/bots/api#location

type Markup

type Markup interface {
	json.Marshaler
	json.Unmarshaler
}

type MaskPosition

type MaskPosition struct {
	Point  string  `json:"point"`
	XShift float32 `json:"x_shift"`
	YShift float32 `json:"y_shift"`
	Scale  float32 `json:"scale"`
}

https://core.telegram.org/bots/api#maskposition

type Message

type Message struct {
	MessageID       int              `json:"message_id"`
	From            *User            `json:"from"`
	Date            int              `json:"date"`
	Chat            Chat             `json:"chat"`
	ForwardFrom     *User            `json:"forward_from"`
	ForwardFromChat *Chat            `json:"forward_from_chat"`
	ForwardDate     *int             `json:"forward_date"`
	ReplyToMessage  *Message         `json:"reply_to_message"`
	EditDate        *int             `json:"edit_date"`
	Text            *string          `json:"text"`
	Entities        []*MessageEntity `json:"entities"`
	Audio           *Audio           `json:"audio"`
	Document        *Document        `json:"document"`
	// Game
	Photo                 []*PhotoSize `json:"photo"`
	Sticker               *Sticker     `json:"sticker"`
	Video                 *Video       `json:"video"`
	Voice                 *Voice       `json:"voice"`
	VideoNote             *VideoNote   `json:"video_note"`
	NewChatMembers        []*User      `json:"new_chat_members"`
	Caption               *string      `json:"caption"`
	Contact               *Contact     `json:"contact"`
	Location              *Location    `json:"location"`
	Venue                 *Venue       `json:"venue"`
	NewChatMember         *User        `json:"new_chat_member"`
	LeftChatMember        *User        `json:"left_chat_member"`
	NewChatTitle          *string      `json:"new_chat_title"`
	NewChatPhoto          []*PhotoSize `json:"new_chat_photo"`
	DeleteChatPhoto       *bool        `json:"delete_chat_photo"`
	GroupChatCreated      *bool        `json:"group_chat_created"`
	SupergroupChatCreated *bool        `json:"supergroup_chat_created"`
	ChannelChatCreated    *bool        `json:"channel_chat_created"`
	MigrateToChatID       *int64       `json:"migrate_to_chat_id"`
	MigrateFromChatID     *int64       `json:"migrate_from_chat_id"`
	PinnedMessage         *Message     `json:"pinned_message"`
}

https://core.telegram.org/bots/api#message

type MessageCaption

type MessageCaption struct {
	ChatID          int64                 `json:"chat_id,omitempty"`
	MessageID       int                   `json:"message_id,omitempty"`
	InlineMessageID int                   `json:"inline_message_id,omitempty"`
	Caption         string                `json:"caption,omitempty"`
	ReplyMarkup     *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#editmessagecaption

type MessageEntity

type MessageEntity struct {
	Type   string  `json:"type"`
	Offset int     `json:"offset"`
	Length int     `json:"length"`
	URL    *string `json:"url"`
	User   *User   `json:"user"`
}

https://core.telegram.org/bots/api#messageentity

func (*MessageEntity) IsBotCommand

func (e *MessageEntity) IsBotCommand() bool

func (*MessageEntity) IsEmail

func (e *MessageEntity) IsEmail() bool

func (*MessageEntity) IsHashtag

func (e *MessageEntity) IsHashtag() bool

func (*MessageEntity) IsMention

func (e *MessageEntity) IsMention() bool

func (*MessageEntity) IsURL

func (e *MessageEntity) IsURL() bool

type MessageReplyMarkup

type MessageReplyMarkup struct {
	ChatID          int64                 `json:"chat_id,omitempty"`
	MessageID       int                   `json:"message_id,omitempty"`
	InlineMessageID int                   `json:"inline_message_id,omitempty"`
	ReplyMarkup     *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#editmessagereplymarkup

type MessageText

type MessageText struct {
	ChatID                int64                 `json:"chat_id,omitempty"`
	MessageID             int                   `json:"message_id,omitempty"`
	InlineMessageID       int                   `json:"inline_message_id,omitempty"`
	Text                  string                `json:"text"`
	ParseMode             ParseMode             `json:"parse_mode"`
	DisableWebPagePreview bool                  `json:"disable_web_page_preview"`
	ReplyMarkup           *InlineKeyboardMarkup `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#editmessagetext

type Multipart

type Multipart struct {
	Form  url.Values
	Files map[string]InputFile
}

func (*Multipart) Encode

func (m *Multipart) Encode() (io.Reader, string, error)

Encode encodes Multipart to multipart/form-data. It returns io.Reader for content, content type with boundary and error. In case of failed encoding io.Reader is nil, content type is an empty string.

type Multiparter

type Multiparter interface {
	Multipart() *Multipart
}

Multiparter is an interface for messages that may be converted to a multipart form (e.g. photo, document, video). *Multipart may be nil meaning unavailable conversion.

type ParseMode

type ParseMode int

func (ParseMode) MarshalJSON

func (m ParseMode) MarshalJSON() (b []byte, err error)

MarshalJSON implements json.Marshaler interface.

type PhotoMessage

type PhotoMessage struct {
	ChatID              int64     `json:"chat_id"`
	Photo               InputFile `json:"-"`
	PhotoID             string    `json:"photo,omitempty"`
	Caption             string    `json:"caption,omitempty"`
	DisableNotification bool      `json:"disable_notification,omitempty"`
	ReplyToMessageID    int       `json:"reply_to_message_id,omitempty"`
}

https://core.telegram.org/bots/api#sendphoto

func (*PhotoMessage) Multipart

func (m *PhotoMessage) Multipart() *Multipart

Multipart implements Multiparter interface.

type PhotoSize

type PhotoSize struct {
	FileID   string `json:"file_id"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
	FileSize *int   `json:"file_size"`
}

https://core.telegram.org/bots/api#photosize

type ReplyKeyboardMarkup

type ReplyKeyboardMarkup struct {
	Keyboard        [][]*KeyboardButton `json:"keyboard"`
	ResizeKeyboard  bool                `json:"resize_keyboard,omitempty"`
	OneTimeKeyboard bool                `json:"one_time_keyboard,omitempty"`
	Selective       bool                `json:"selective,omitempty"`
}

https://core.telegram.org/bots/api#replykeyboardmarkup

func (*ReplyKeyboardMarkup) MarshalJSON

func (m *ReplyKeyboardMarkup) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*ReplyKeyboardMarkup) UnmarshalJSON

func (m *ReplyKeyboardMarkup) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type ReplyKeyboardRemove

type ReplyKeyboardRemove struct {
	RemoveKeyboard bool `json:"remove_keyboard,omitempty"`
	Selective      bool `json:"selective,omitempty"`
}

https://core.telegram.org/bots/api#replykeyboardremove

func (*ReplyKeyboardRemove) MarshalJSON

func (m *ReplyKeyboardRemove) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*ReplyKeyboardRemove) UnmarshalJSON

func (m *ReplyKeyboardRemove) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type ResponseParameters

type ResponseParameters struct {
	MigrateToChatID *int64 `json:"migrate_to_chat_id"`
	RetryAfter      *int   `json:"retry_after"`
}

https://core.telegram.org/bots/api#responseparameters

type SOCKS5 added in v0.2.0

type SOCKS5 struct {
	Address  string // host:port
	User     string
	Password string
}

func (*SOCKS5) Auth added in v0.2.0

func (s *SOCKS5) Auth() *proxy.Auth

type Sticker

type Sticker struct {
	FileID       string        `json:"file_id"`
	Width        int           `json:"width"`
	Height       int           `json:"height"`
	Thumb        *PhotoSize    `json:"thumb"`
	Emoji        *string       `json:"emoji"`
	SetName      *string       `json:"set_name"`
	MaskPosition *MaskPosition `json:"mask_position"`
	FileSize     *int          `json:"file_size"`
}

https://core.telegram.org/bots/api#sticker

type StickerMessage

type StickerMessage struct {
	ChatID              int64     `json:"chat_id"`
	Sticker             InputFile `json:"-"`
	StickerID           string    `json:"sticker"`
	DisableNotification bool      `json:"disalbe_notification,omitempty"`
	ReplyToMessageID    int       `json:"reply_to_message_id,omitempty"`
	ReplyMarkup         Markup    `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#sendsticker

type StickerSet

type StickerSet struct {
	Name          string     `json:"name"`
	Title         string     `json:"title"`
	ContainsMasks bool       `json:"contains_masks"`
	Stickers      []*Sticker `json:"stickers"`
}

https://core.telegram.org/bots/api#stickerset

type TextMessage

type TextMessage struct {
	ChatID                int64     `json:"chat_id"`
	Text                  string    `json:"text"`
	ParseMode             ParseMode `json:"parse_mode,omitempty"`
	DisableWebPagePreview bool      `json:"disable_web_page_preview,omitempty"`
	DisableNotification   bool      `json:"disable_notification,omitempty"`
	ReplyToMessageID      int       `json:"reply_to_message_id,omitempty"`
	ReplyMarkup           Markup    `json:"reply_markup,omitempty"`
}

https://core.telegram.org/bots/api#sendmessage

type Update

type Update struct {
	UpdateID          int      `json:"update_id"`
	Message           *Message `json:"message"`
	EditedMessage     *Message `json:"edited_message"`
	ChannelPost       *Message `json:"channel_post"`
	EditedChannelPost *Message `json:"edited_channel_post"`
	// InlineQuery
	// ChosenInlineResult
	CallbackQuery *CallbackQuery `json:"callback_query"`
}

https://core.telegram.org/bots/api#update

type UpdatesOption

type UpdatesOption func(*updatesOptions)

func WithLimit

func WithLimit(limit int) UpdatesOption

WithLimit modifies updates request to limit the number of updates in response.

func WithOffset

func WithOffset(offset int) UpdatesOption

WithOffset sets id of the first expected update in response. Usually offset should equal last update's id + 1.

func WithTimeout

func WithTimeout(t time.Duration) UpdatesOption

WithTimeout modifies timeout of updates request. 0 duration means short polling (for testing only).

type User

type User struct {
	ID           int     `json:"id"`
	FirstName    string  `json:"first_name"`
	LastName     *string `json:"last_name"`
	Username     *string `json:"username"`
	LanguageCode *string `json:"language_code"`
}

https://core.telegram.org/bots/api#user

type UserProfilePhotos

type UserProfilePhotos struct {
	TotalCount int            `json:"total_count"`
	Photos     [][]*PhotoSize `json:"photos"`
}

https://core.telegram.org/bots/api#userprofilephotos

type Venue

type Venue struct {
	Location     Location `json:"location"`
	Title        string   `json:"title"`
	Address      string   `json:"address"`
	FoursquareID *string  `json:"foursquare_id"`
}

https://core.telegram.org/bots/api#venue

type Video

type Video struct {
	FileID   string     `json:"file_id"`
	Width    int        `json:"width"`
	Height   int        `json:"height"`
	Duration int        `json:"duration"`
	Thumb    *PhotoSize `json:"thumb"`
	MimeType *string    `json:"mime_type"`
	FileSize *int       `json:"file_size"`
}

https://core.telegram.org/bots/api#video

type VideoNote

type VideoNote struct {
	FileID   string     `json:"file_id"`
	Length   int        `json:"length"`
	Duration int        `json:"duration"`
	Thumb    *PhotoSize `json:"thumb"`
	FileSize *int       `json:"file_size"`
}

https://core.telegram.org/bots/api#videonote

type Voice

type Voice struct {
	FileID   string  `json:"file_id"`
	Duration int     `json:"duration"`
	MimeType *string `json:"mime_type"`
	FileSize *int    `json:"file_size"`
}

https://core.telegram.org/bots/api#voice

type WebhookInfo

type WebhookInfo struct {
	URL                  string   `json:"url"`
	HasCustomCertificate bool     `json:"has_custom_certificate"`
	PendingUpdateCount   int      `json:"pending_update_count"`
	LastErrorDate        int      `json:"last_error_date"`
	LastErrorMessage     string   `json:"last_error_message"`
	MaxConnections       int      `json:"max_connections"`
	AllowedUpdates       []string `json:"allowed_updates"`
}

https://core.telegram.org/bots/api#webhookinfo

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL