tgbotapi

package module
v3.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2016 License: MIT Imports: 14 Imported by: 0

README

Golang bindings for the Telegram Bot API

GoDoc Travis

All methods have been added, and all features should be available. If you want a feature that hasn't been added yet or something is broken, open an issue and I'll see what I can do.

All methods are fairly self explanatory, and reading the godoc page should explain everything. If something isn't clear, open an issue or submit a pull request.

The scope of this project is just to provide a wrapper around the API without any additional features. There are other projects for creating something with plugins and command handlers without having to design all that yourself.

Use github.com/go-telegram-bot-api/telegram-bot-api for the latest version, or use gopkg.in/telegram-bot-api.v3 for the stable build.

Example

This is a very simple bot that just displays any gotten updates, then replies it to that chat.

package main

import (
	"log"
	"gopkg.in/telegram-bot-api.v3"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)

	for update := range updates {
		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

		msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
		msg.ReplyToMessageID = update.Message.MessageID

		bot.Send(msg)
	}
}

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

package main

import (
	"gopkg.in/telegram-bot-api.v3"
	"log"
	"net/http"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
	if err != nil {
		log.Fatal(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
	if err != nil {
		log.Fatal(err)
	}

	updates := bot.ListenForWebhook("/" + bot.Token)
	go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

	for update := range updates {
		log.Printf("%+v\n", update)
	}
}

If you need, you may generate a self signed certficate, as this requires HTTPS / TLS. The above example tells Telegram that this is your certificate and that it should be trusted, even though it is not properly signed.

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3560 -subj "//O=Org\CN=Test" -nodes

Now that Let's Encrypt has entered public beta, you may wish to generate your free TLS certificate there.

Documentation

Overview

Package tgbotapi has functions and types used for interacting with the Telegram Bot API.

Index

Examples

Constants

View Source
const (
	// APIEndpoint is the endpoint for all API methods,
	// with formatting for Sprintf.
	APIEndpoint = "https://api.telegram.org/bot%s/%s"
	// FileEndpoint is the endpoint for downloading a file from Telegram.
	FileEndpoint = "https://api.telegram.org/file/bot%s/%s"
)

Telegram constants

View Source
const (
	ChatTyping         = "typing"
	ChatUploadPhoto    = "upload_photo"
	ChatRecordVideo    = "record_video"
	ChatUploadVideo    = "upload_video"
	ChatRecordAudio    = "record_audio"
	ChatUploadAudio    = "upload_audio"
	ChatUploadDocument = "upload_document"
	ChatFindLocation   = "find_location"
)

Constant values for ChatActions

View Source
const (
	ModeMarkdown = "Markdown"
	ModeHTML     = "HTML"
)

Constant values for ParseMode in MessageConfig

View Source
const (
	// ErrAPIForbidden happens when a token is bad
	ErrAPIForbidden = "forbidden"
)

API errors

View Source
const (
	// ErrBadFileType happens when you pass an unknown type
	ErrBadFileType = "bad file type"
)

Library errors

Variables

This section is empty.

Functions

This section is empty.

Types

type APIResponse

type APIResponse struct {
	Ok          bool            `json:"ok"`
	Result      json.RawMessage `json:"result"`
	ErrorCode   int             `json:"error_code"`
	Description string          `json:"description"`
}

APIResponse is a response from the Telegram API with the result stored raw.

type Audio

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

Audio contains information about audio.

type AudioConfig

type AudioConfig struct {
	BaseFile
	Duration  int
	Performer string
	Title     string
}

AudioConfig contains information about a SendAudio request.

func NewAudioShare

func NewAudioShare(chatID int64, fileID string) AudioConfig

NewAudioShare shares an existing audio file. You may use this to reshare an existing audio file without reuploading it.

chatID is where to send it, fileID is the ID of the audio already uploaded.

func NewAudioUpload

func NewAudioUpload(chatID int64, file interface{}) AudioConfig

NewAudioUpload creates a new audio uploader.

chatID is where to send it, file is a string path to the file, FileReader, or FileBytes.

type BaseChat

type BaseChat struct {
	ChatID              int64 // required
	ChannelUsername     string
	ReplyToMessageID    int
	ReplyMarkup         interface{}
	DisableNotification bool
}

BaseChat is base type for all chat config types.

type BaseFile

type BaseFile struct {
	BaseChat
	File        interface{}
	FileID      string
	UseExisting bool
	MimeType    string
	FileSize    int
}

BaseFile is a base type for all file config types.

type BotAPI

type BotAPI struct {
	Token  string       `json:"token"`
	Debug  bool         `json:"debug"`
	Self   User         `json:"-"`
	Client *http.Client `json:"-"`
}

BotAPI allows you to interact with the Telegram Bot API.

func NewBotAPI

func NewBotAPI(token string) (*BotAPI, error)

NewBotAPI creates a new BotAPI instance.

It requires a token, provided by @BotFather on Telegram.

Example
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
if err != nil {
	log.Panic(err)
}

bot.Debug = true

log.Printf("Authorized on account %s", bot.Self.UserName)

u := tgbotapi.NewUpdate(0)
u.Timeout = 60

updates, err := bot.GetUpdatesChan(u)

for update := range updates {
	log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

	msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
	msg.ReplyToMessageID = update.Message.MessageID

	bot.Send(msg)
}
Output:

func NewBotAPIWithClient

func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error)

NewBotAPIWithClient creates a new BotAPI instance and allows you to pass a http.Client.

It requires a token, provided by @BotFather on Telegram.

func (*BotAPI) AnswerInlineQuery

func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error)

AnswerInlineQuery sends a response to an inline query.

Note that you must respond to an inline query within 30 seconds.

func (*BotAPI) GetFile

func (bot *BotAPI) GetFile(config FileConfig) (File, error)

GetFile returns a File which can download a file from Telegram.

Requires FileID.

func (*BotAPI) GetFileDirectURL

func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error)

GetFileDirectURL returns direct URL to file

It requires the FileID.

func (*BotAPI) GetMe

func (bot *BotAPI) GetMe() (User, error)

GetMe fetches the currently authenticated bot.

This method is called upon creation to validate the token, and so you may get this data from BotAPI.Self without the need for another request.

func (*BotAPI) GetUpdates

func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error)

GetUpdates fetches updates. If a WebHook is set, this will not return any data!

Offset, Limit, and Timeout are optional. To avoid stale items, set Offset to one higher than the previous item. Set Timeout to a large number to reduce requests so you can get updates instantly instead of having to wait between requests.

func (*BotAPI) GetUpdatesChan

func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (<-chan Update, error)

GetUpdatesChan starts and returns a channel for getting updates.

func (*BotAPI) GetUserProfilePhotos

func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error)

GetUserProfilePhotos gets a user's profile photos.

It requires UserID. Offset and Limit are optional.

func (*BotAPI) IsMessageToMe

func (bot *BotAPI) IsMessageToMe(message Message) bool

IsMessageToMe returns true if message directed to this bot.

It requires the Message.

func (*BotAPI) ListenForWebhook

func (bot *BotAPI) ListenForWebhook(pattern string) <-chan Update

ListenForWebhook registers a http handler for a webhook.

func (*BotAPI) MakeRequest

func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error)

MakeRequest makes a request to a specific endpoint with our token.

func (*BotAPI) RemoveWebhook

func (bot *BotAPI) RemoveWebhook() (APIResponse, error)

RemoveWebhook unsets the webhook.

func (*BotAPI) Send

func (bot *BotAPI) Send(c Chattable) (Message, error)

Send will send a Chattable item to Telegram.

It requires the Chattable to send.

func (*BotAPI) SetWebhook

func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error)

SetWebhook sets a webhook.

If this is set, GetUpdates will not get any data!

If you do not have a legitmate TLS certificate, you need to include your self signed certificate with the config.

func (*BotAPI) UploadFile

func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error)

UploadFile makes a request to the API with a file.

Requires the parameter to hold the file not be in the params. File should be a string to a file path, a FileBytes struct, or a FileReader struct.

Note that if your FileReader has a size set to -1, it will read the file into memory to calculate a size.

type Chat

type Chat struct {
	ID        int64  `json:"id"`
	Type      string `json:"type"`
	Title     string `json:"title"`      // optional
	UserName  string `json:"username"`   // optional
	FirstName string `json:"first_name"` // optional
	LastName  string `json:"last_name"`  // optional
}

Chat contains information about the place a message was sent.

func (*Chat) IsChannel

func (c *Chat) IsChannel() bool

IsChannel returns if the Chat is a channel.

func (*Chat) IsGroup

func (c *Chat) IsGroup() bool

IsGroup returns if the Chat is a group.

func (*Chat) IsPrivate

func (c *Chat) IsPrivate() bool

IsPrivate returns if the Chat is a private conversation.

func (*Chat) IsSuperGroup

func (c *Chat) IsSuperGroup() bool

IsSuperGroup returns if the Chat is a supergroup.

type ChatActionConfig

type ChatActionConfig struct {
	BaseChat
	Action string // required
}

ChatActionConfig contains information about a SendChatAction request.

func NewChatAction

func NewChatAction(chatID int64, action string) ChatActionConfig

NewChatAction sets a chat action. Actions last for 5 seconds, or until your next action.

chatID is where to send it, action should be set via Chat constants.

type Chattable

type Chattable interface {
	// contains filtered or unexported methods
}

Chattable is any config type that can be sent.

type ChosenInlineResult

type ChosenInlineResult struct {
	ResultID string `json:"result_id"`
	From     User   `json:"from"`
	Query    string `json:"query"`
}

ChosenInlineResult is an inline query result chosen by a User

type Contact

type Contact struct {
	PhoneNumber string `json:"phone_number"`
	FirstName   string `json:"first_name"`
	LastName    string `json:"last_name"` // optional
	UserID      int    `json:"user_id"`   // optional
}

Contact contains information about a contact.

Note that LastName and UserID may be empty.

type Document

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

Document contains information about a document.

type DocumentConfig

type DocumentConfig struct {
	BaseFile
}

DocumentConfig contains information about a SendDocument request.

func NewDocumentShare

func NewDocumentShare(chatID int64, fileID string) DocumentConfig

NewDocumentShare shares an existing document. You may use this to reshare an existing document without reuploading it.

chatID is where to send it, fileID is the ID of the document already uploaded.

func NewDocumentUpload

func NewDocumentUpload(chatID int64, file interface{}) DocumentConfig

NewDocumentUpload creates a new document uploader.

chatID is where to send it, file is a string path to the file, FileReader, or FileBytes.

type File

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

File contains information about a file to download from Telegram.

func (f *File) Link(token string) string

Link returns a full path to the download URL for a File.

It requires the Bot Token to create the link.

type FileBytes

type FileBytes struct {
	Name  string
	Bytes []byte
}

FileBytes contains information about a set of bytes to upload as a File.

type FileConfig

type FileConfig struct {
	FileID string
}

FileConfig has information about a file hosted on Telegram.

type FileReader

type FileReader struct {
	Name   string
	Reader io.Reader
	Size   int64
}

FileReader contains information about a reader to upload as a File. If Size is -1, it will read the entire Reader into memory to calculate a Size.

type Fileable

type Fileable interface {
	Chattable
	// contains filtered or unexported methods
}

Fileable is any config type that can be sent that includes a file.

type ForceReply

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

ForceReply allows the Bot to have users directly reply to it without additional interaction.

type ForwardConfig

type ForwardConfig struct {
	BaseChat
	FromChatID          int64 // required
	FromChannelUsername string
	MessageID           int // required
}

ForwardConfig contains information about a ForwardMessage request.

func NewForward

func NewForward(chatID int64, fromChatID int64, messageID int) ForwardConfig

NewForward creates a new forward.

chatID is where to send it, fromChatID is the source chat, and messageID is the ID of the original message.

type GroupChat

type GroupChat struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

GroupChat is a group chat.

type InlineConfig

type InlineConfig struct {
	InlineQueryID string        `json:"inline_query_id"`
	Results       []interface{} `json:"results"`
	CacheTime     int           `json:"cache_time"`
	IsPersonal    bool          `json:"is_personal"`
	NextOffset    string        `json:"next_offset"`
}

InlineConfig contains information on making an InlineQuery response.

type InlineQuery

type InlineQuery struct {
	ID     string `json:"id"`
	From   User   `json:"from"`
	Query  string `json:"query"`
	Offset string `json:"offset"`
}

InlineQuery is a Query from Telegram for an inline request.

type InlineQueryResultArticle

type InlineQueryResultArticle struct {
	Type                  string `json:"type"`         // required
	ID                    string `json:"id"`           // required
	Title                 string `json:"title"`        // required
	MessageText           string `json:"message_text"` // required
	ParseMode             string `json:"parse_mode"`
	DisableWebPagePreview bool   `json:"disable_web_page_preview"`
	URL                   string `json:"url"`
	HideURL               bool   `json:"hide_url"`
	Description           string `json:"description"`
	ThumbURL              string `json:"thumb_url"`
	ThumbWidth            int    `json:"thumb_width"`
	ThumbHeight           int    `json:"thumb_height"`
}

InlineQueryResultArticle is an inline query response article.

func NewInlineQueryResultArticle

func NewInlineQueryResultArticle(id, title, messageText string) InlineQueryResultArticle

NewInlineQueryResultArticle creates a new inline query article.

type InlineQueryResultGIF

type InlineQueryResultGIF struct {
	Type                  string `json:"type"`    // required
	ID                    string `json:"id"`      // required
	URL                   string `json:"gif_url"` // required
	Width                 int    `json:"gif_width"`
	Height                int    `json:"gif_height"`
	ThumbURL              string `json:"thumb_url"`
	Title                 string `json:"title"`
	Caption               string `json:"caption"`
	MessageText           string `json:"message_text"`
	ParseMode             string `json:"parse_mode"`
	DisableWebPagePreview bool   `json:"disable_web_page_preview"`
}

InlineQueryResultGIF is an inline query response GIF.

func NewInlineQueryResultGIF

func NewInlineQueryResultGIF(id, url string) InlineQueryResultGIF

NewInlineQueryResultGIF creates a new inline query GIF.

type InlineQueryResultMPEG4GIF

type InlineQueryResultMPEG4GIF struct {
	Type                  string `json:"type"`      // required
	ID                    string `json:"id"`        // required
	URL                   string `json:"mpeg4_url"` // required
	Width                 int    `json:"mpeg4_width"`
	Height                int    `json:"mpeg4_height"`
	ThumbURL              string `json:"thumb_url"`
	Title                 string `json:"title"`
	Caption               string `json:"caption"`
	MessageText           string `json:"message_text"`
	ParseMode             string `json:"parse_mode"`
	DisableWebPagePreview bool   `json:"disable_web_page_preview"`
}

InlineQueryResultMPEG4GIF is an inline query response MPEG4 GIF.

func NewInlineQueryResultMPEG4GIF

func NewInlineQueryResultMPEG4GIF(id, url string) InlineQueryResultMPEG4GIF

NewInlineQueryResultMPEG4GIF creates a new inline query MPEG4 GIF.

type InlineQueryResultPhoto

type InlineQueryResultPhoto struct {
	Type                  string `json:"type"`      // required
	ID                    string `json:"id"`        // required
	URL                   string `json:"photo_url"` // required
	MimeType              string `json:"mime_type"`
	Width                 int    `json:"photo_width"`
	Height                int    `json:"photo_height"`
	ThumbURL              string `json:"thumb_url"`
	Title                 string `json:"title"`
	Description           string `json:"description"`
	Caption               string `json:"caption"`
	MessageText           string `json:"message_text"`
	ParseMode             string `json:"parse_mode"`
	DisableWebPagePreview bool   `json:"disable_web_page_preview"`
}

InlineQueryResultPhoto is an inline query response photo.

func NewInlineQueryResultPhoto

func NewInlineQueryResultPhoto(id, url string) InlineQueryResultPhoto

NewInlineQueryResultPhoto creates a new inline query photo.

type InlineQueryResultVideo

type InlineQueryResultVideo struct {
	Type                  string `json:"type"`         // required
	ID                    string `json:"id"`           // required
	URL                   string `json:"video_url"`    // required
	MimeType              string `json:"mime_type"`    // required
	MessageText           string `json:"message_text"` // required
	ParseMode             string `json:"parse_mode"`
	DisableWebPagePreview bool   `json:"disable_web_page_preview"`
	Width                 int    `json:"video_width"`
	Height                int    `json:"video_height"`
	ThumbURL              string `json:"thumb_url"`
	Title                 string `json:"title"`
	Description           string `json:"description"`
}

InlineQueryResultVideo is an inline query response video.

func NewInlineQueryResultVideo

func NewInlineQueryResultVideo(id, url string) InlineQueryResultVideo

NewInlineQueryResultVideo creates a new inline query video.

type Location

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

Location contains information about a place.

type LocationConfig

type LocationConfig struct {
	BaseChat
	Latitude  float64 // required
	Longitude float64 // required
}

LocationConfig contains information about a SendLocation request.

func NewLocation

func NewLocation(chatID int64, latitude float64, longitude float64) LocationConfig

NewLocation shares your location.

chatID is where to send it, latitude and longitude are coordinates.

type Message

type Message struct {
	MessageID             int         `json:"message_id"`
	From                  User        `json:"from"` // optional
	Date                  int         `json:"date"`
	Chat                  Chat        `json:"chat"`
	ForwardFrom           User        `json:"forward_from"`            // optional
	ForwardDate           int         `json:"forward_date"`            // optional
	ReplyToMessage        *Message    `json:"reply_to_message"`        // optional
	Text                  string      `json:"text"`                    // optional
	Audio                 Audio       `json:"audio"`                   // optional
	Document              Document    `json:"document"`                // optional
	Photo                 []PhotoSize `json:"photo"`                   // optional
	Sticker               Sticker     `json:"sticker"`                 // optional
	Video                 Video       `json:"video"`                   // optional
	Voice                 Voice       `json:"voice"`                   // optional
	Caption               string      `json:"caption"`                 // optional
	Contact               Contact     `json:"contact"`                 // optional
	Location              Location    `json:"location"`                // optional
	NewChatParticipant    User        `json:"new_chat_participant"`    // optional
	LeftChatParticipant   User        `json:"left_chat_participant"`   // optional
	NewChatTitle          string      `json:"new_chat_title"`          // optional
	NewChatPhoto          []PhotoSize `json:"new_chat_photo"`          // optional
	DeleteChatPhoto       bool        `json:"delete_chat_photo"`       // optional
	GroupChatCreated      bool        `json:"group_chat_created"`      // optional
	SuperGroupChatCreated bool        `json:"supergroup_chat_created"` // optional
	ChannelChatCreated    bool        `json:"channel_chat_created"`    // optional
	MigrateToChatID       int64       `json:"migrate_to_chat_id"`      // optional
	MigrateFromChatID     int64       `json:"migrate_from_chat_id"`    // optional
}

Message is returned by almost every request, and contains data about almost anything.

func (*Message) Command

func (m *Message) Command() string

Command checks if the message was a command and if it was, returns the command. If the Message was not a command, it returns an empty string.

If the command contains the at bot syntax, it removes the bot name.

func (*Message) CommandArguments

func (m *Message) CommandArguments() string

CommandArguments checks if the message was a command and if it was, returns all text after the command name. If the Message was not a command, it returns an empty string.

func (*Message) IsCommand

func (m *Message) IsCommand() bool

IsCommand returns true if message starts with '/'.

func (*Message) Time

func (m *Message) Time() time.Time

Time converts the message timestamp into a Time.

type MessageConfig

type MessageConfig struct {
	BaseChat
	Text                  string
	ParseMode             string
	DisableWebPagePreview bool
}

MessageConfig contains information about a SendMessage request.

func NewMessage

func NewMessage(chatID int64, text string) MessageConfig

NewMessage creates a new Message.

chatID is where to send it, text is the message text.

type PhotoConfig

type PhotoConfig struct {
	BaseFile
	Caption string
}

PhotoConfig contains information about a SendPhoto request.

func NewPhotoShare

func NewPhotoShare(chatID int64, fileID string) PhotoConfig

NewPhotoShare shares an existing photo. You may use this to reshare an existing photo without reuploading it.

chatID is where to send it, fileID is the ID of the file already uploaded.

func NewPhotoUpload

func NewPhotoUpload(chatID int64, file interface{}) PhotoConfig

NewPhotoUpload creates a new photo uploader.

chatID is where to send it, file is a string path to the file, FileReader, or FileBytes.

Note that you must send animated GIFs as a document.

type PhotoSize

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

PhotoSize contains information about photos.

type ReplyKeyboardHide

type ReplyKeyboardHide struct {
	HideKeyboard bool `json:"hide_keyboard"`
	Selective    bool `json:"selective"` // optional
}

ReplyKeyboardHide allows the Bot to hide a custom keyboard.

type ReplyKeyboardMarkup

type ReplyKeyboardMarkup struct {
	Keyboard        [][]string `json:"keyboard"`
	ResizeKeyboard  bool       `json:"resize_keyboard"`   // optional
	OneTimeKeyboard bool       `json:"one_time_keyboard"` // optional
	Selective       bool       `json:"selective"`         // optional
}

ReplyKeyboardMarkup allows the Bot to set a custom keyboard.

type Sticker

type Sticker struct {
	FileID    string    `json:"file_id"`
	Width     int       `json:"width"`
	Height    int       `json:"height"`
	Thumbnail PhotoSize `json:"thumb"`     // optional
	FileSize  int       `json:"file_size"` // optional
}

Sticker contains information about a sticker.

type StickerConfig

type StickerConfig struct {
	BaseFile
}

StickerConfig contains information about a SendSticker request.

func NewStickerShare

func NewStickerShare(chatID int64, fileID string) StickerConfig

NewStickerShare shares an existing sticker. You may use this to reshare an existing sticker without reuploading it.

chatID is where to send it, fileID is the ID of the sticker already uploaded.

func NewStickerUpload

func NewStickerUpload(chatID int64, file interface{}) StickerConfig

NewStickerUpload creates a new sticker uploader.

chatID is where to send it, file is a string path to the file, FileReader, or FileBytes.

type Update

type Update struct {
	UpdateID           int                `json:"update_id"`
	Message            Message            `json:"message"`
	InlineQuery        InlineQuery        `json:"inline_query"`
	ChosenInlineResult ChosenInlineResult `json:"chosen_inline_result"`
}

Update is an update response, from GetUpdates.

type UpdateConfig

type UpdateConfig struct {
	Offset  int
	Limit   int
	Timeout int
}

UpdateConfig contains information about a GetUpdates request.

func NewUpdate

func NewUpdate(offset int) UpdateConfig

NewUpdate gets updates since the last Offset.

offset is the last Update ID to include. You likely want to set this to the last Update ID plus 1.

type User

type User struct {
	ID        int    `json:"id"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"` // optional
	UserName  string `json:"username"`  // optional
}

User is a user on Telegram.

func (*User) String

func (u *User) String() string

String displays a simple text version of a user.

It is normally a user's username, but falls back to a first/last name as available.

type UserProfilePhotos

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

UserProfilePhotos contains a set of user profile photos.

type UserProfilePhotosConfig

type UserProfilePhotosConfig struct {
	UserID int
	Offset int
	Limit  int
}

UserProfilePhotosConfig contains information about a GetUserProfilePhotos request.

func NewUserProfilePhotos

func NewUserProfilePhotos(userID int) UserProfilePhotosConfig

NewUserProfilePhotos gets user profile photos.

userID is the ID of the user you wish to get profile photos from.

type Video

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

Video contains information about a video.

type VideoConfig

type VideoConfig struct {
	BaseFile
	Duration int
	Caption  string
}

VideoConfig contains information about a SendVideo request.

func NewVideoShare

func NewVideoShare(chatID int64, fileID string) VideoConfig

NewVideoShare shares an existing video. You may use this to reshare an existing video without reuploading it.

chatID is where to send it, fileID is the ID of the video already uploaded.

func NewVideoUpload

func NewVideoUpload(chatID int64, file interface{}) VideoConfig

NewVideoUpload creates a new video uploader.

chatID is where to send it, file is a string path to the file, FileReader, or FileBytes.

type Voice

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

Voice contains information about a voice.

type VoiceConfig

type VoiceConfig struct {
	BaseFile
	Duration int
}

VoiceConfig contains information about a SendVoice request.

func NewVoiceShare

func NewVoiceShare(chatID int64, fileID string) VoiceConfig

NewVoiceShare shares an existing voice. You may use this to reshare an existing voice without reuploading it.

chatID is where to send it, fileID is the ID of the video already uploaded.

func NewVoiceUpload

func NewVoiceUpload(chatID int64, file interface{}) VoiceConfig

NewVoiceUpload creates a new voice uploader.

chatID is where to send it, file is a string path to the file, FileReader, or FileBytes.

type WebhookConfig

type WebhookConfig struct {
	URL         *url.URL
	Certificate interface{}
}

WebhookConfig contains information about a SetWebhook request.

func NewWebhook

func NewWebhook(link string) WebhookConfig

NewWebhook creates a new webhook.

link is the url parsable link you wish to get the updates.

Example
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
if err != nil {
	log.Fatal(err)
}

bot.Debug = true

log.Printf("Authorized on account %s", bot.Self.UserName)

_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
if err != nil {
	log.Fatal(err)
}

updates := bot.ListenForWebhook("/" + bot.Token)
go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

for update := range updates {
	log.Printf("%+v\n", update)
}
Output:

func NewWebhookWithCert

func NewWebhookWithCert(link string, file interface{}) WebhookConfig

NewWebhookWithCert creates a new webhook with a certificate.

link is the url you wish to get webhooks, file contains a string to a file, FileReader, or FileBytes.

Jump to

Keyboard shortcuts

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