telebot

package module
v0.0.0-...-29bd370 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2017 License: MIT Imports: 17 Imported by: 0

README

Telebot

Telebot is a Telegram bot framework in Go.

GoDoc Travis

NOTE: We are currently working on completing both v1 and v2 of our API. You can track the progress here and here.

Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or via group chats / channels. These accounts serve as an interface to your code.

Telebot offers a pretty convenient interface to Bots API and uses default HTTP client. Ideally, you wouldn't need to worry about actual networking at all.

go get github.com/tucnak/telebot

(after setting up your GOPATH properly).

We highly recommend you to keep your bot access token outside the code base, preferably in an environmental variable:

export BOT_TOKEN=<your token here>

Take a look at a minimal functional bot setup:

package main

import (
	"log"
	"os"
	"time"

	tb "gopkg.in/tucnak/telebot.v1"
)

func main() {
	bot, err := tb.NewBot(os.Getenv("BOT_TOKEN"))
	if err != nil {
		log.Fatalln(err)
	}

	messages := make(chan tb.Message, 100)
	bot.Listen(messages, 10 * time.Second)

	for message := range messages {
		if message.Text == "/hi" {
			bot.SendMessage(message.Chat,
				"Hello, "+message.Sender.FirstName+"!", nil)
		}
	}
}

Inline mode

As of January 4, 2016, Telegram added inline mode support for bots. Here's a nice way to handle both incoming messages and inline queries in the meantime:

package main

import (
	"log"
	"time"
	"os"

	tb "gopkg.in/tucnak/telebot.v1"
)

func main() {
	bot, err := tb.NewBot(os.Getenv("BOT_TOKEN"))
	if err != nil {
		log.Fatalln(err)
	}

	bot.Messages = make(chan tb.Message, 100)
	bot.Queries = make(chan tb.Query, 1000)

	go messages(bot)
	go queries(bot)

	bot.Start(10 * time.Second)
}

func messages(bot *tb.Bot) {
	for message := range bot.Messages {
		log.Printf("Received a message from %s with the text: %s\n",
			message.Sender.Username, message.Text)
	}
}

func queries(bot *tb.Bot) {
	for query := range bot.Queries {
		log.Println("--- new query ---")
		log.Println("from:", query.From.Username)
		log.Println("text:", query.Text)

		// Create an article (a link) object to show in results.
		article := &tb.InlineQueryResultArticle{
			Title: "Telebot",
			URL:   "https://github.com/tucnak/telebot",
			InputMessageContent: &tb.InputTextMessageContent{
				Text:		   "Telebot is a Telegram bot framework.",
				DisablePreview: false,
			},
		}

		// Build the list of results (make sure to pass pointers!).
		results := []tb.InlineQueryResult{article}

		// Build a response object to answer the query.
		response := tb.QueryResponse{
			Results:	results,
			IsPersonal: true,
		}

		// Send it.
		if err := bot.AnswerInlineQuery(&query, &response); err != nil {
			log.Println("Failed to respond to query:", err)
		}
	}
}

Files

Telebot lets you upload files from the file system:

boom, err := tb.NewFile("boom.ogg")
if err != nil {
	return err
}

audio := tb.Audio{File: boom}

// Next time you send &audio, telebot won't issue
// an upload, but would re-use existing file.
err = bot.SendAudio(recipient, &audio, nil)

Reply markup

Sometimes you wanna send a little complicated messages with some optional parameters. The third argument of all Send* methods accepts telebot.SendOptions, capable of defining an advanced reply markup:

// Send a selective force reply message.
bot.SendMessage(user, "pong", &tb.SendOptions{
		ReplyMarkup: tb.ReplyMarkup{
			ForceReply: true,
			Selective: true,
			CustomKeyboard: [][]string{
				[]string{"1", "2", "3"},
				[]string{"4", "5", "6"},
				[]string{"7", "8", "9"},
				[]string{"*", "0", "#"},
			},
		},
	},
)

Documentation

Overview

Package telebot provides a handy wrapper for interactions with Telegram bots.

Here is an example of helloworld bot implementation:

import (
	"time"
	"github.com/tucnak/telebot"
)

func main() {
	bot, err := telebot.NewBot("SECRET_TOKEN")
	if err != nil {
		return
	}

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	for message := range messages {
		if message.Text == "/hi" {
			bot.SendMessage(message.Chat,
				"Hello, "+message.Sender.FirstName+"!", nil)
		}
	}
}

Index

Constants

View Source
const Default string = ""

Default handler prefix.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArticleResult

type ArticleResult struct {
	// [Required!] Title of the result.
	Title string

	// [Required!] Text of the message to be sent, 1-512 characters.
	Text string

	// Short description of the result.
	Description string

	// Markdown, HTML?
	Mode ParseMode

	// Disables link previews for links in the sent message.
	DisableWebPagePreview bool

	// Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.
	DisableNotification bool

	// URL of the result
	URL string

	// If true, the URL won't be shown in the message.
	HideURL bool

	// Result's thumbnail URL.
	ThumbURL string
}

ArticleResult represents a link to an article or web page. Deprecated, use InlineQueryResultArticle instead.

func (ArticleResult) MarshalJSON

func (r ArticleResult) MarshalJSON() ([]byte, error)

MarshalJSON is a serializer.

type Audio

type Audio struct {
	File

	// Duration of the recording in seconds as defined by sender.
	Duration int `json:"duration"`

	// FileSize (optional) of the audio file.
	FileSize int `json:"file_size"`

	// Title (optional) as defined by sender or by audio tags.
	Title string `json:"title"`

	// Performer (optional) is defined by sender or by audio tags.
	Performer string `json:"performer"`

	// MIME type (optional) of the file as defined by sender.
	Mime string `json:"mime_type"`
}

Audio object represents an audio file (voice note).

type Bot

type Bot struct {
	Token     string
	Identity  User
	Messages  chan Message
	Queries   chan Query
	Callbacks chan Callback

	// Telebot debugging channel. If present, Telebot
	// will use it to report all occuring errors.
	Errors chan error
	// contains filtered or unexported fields
}

Bot represents a separate Telegram bot instance.

func NewBot

func NewBot(token string) (*Bot, error)

NewBot does try to build a Bot with token `token`, which is a secret API key assigned to particular bot.

func (*Bot) AnswerCallbackQuery

func (b *Bot) AnswerCallbackQuery(callback *Callback, response *CallbackResponse) error

AnswerCallbackQuery sends a response for a given callback query. A callback can only be responded to once, subsequent attempts to respond to the same callback will result in an error.

func (*Bot) AnswerInlineQuery

func (b *Bot) AnswerInlineQuery(query *Query, response *QueryResponse) error

AnswerInlineQuery sends a response for a given inline query. A query can only be responded to once, subsequent attempts to respond to the same query will result in an error.

func (*Bot) ForwardMessage

func (b *Bot) ForwardMessage(recipient Recipient, message Message) error

ForwardMessage forwards a message to recipient.

func (*Bot) GetChat

func (b *Bot) GetChat(recipient Recipient) (Chat, error)

GetChat get up to date information about the chat.

Including current name of the user for one-on-one conversations, current username of a user, group or channel, etc.

Returns a Chat object on success.

func (*Bot) GetChatAdministrators

func (b *Bot) GetChatAdministrators(recipient Recipient) ([]ChatMember, error)

GetChatAdministrators return list of administrators in a chat.

On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.

If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

func (*Bot) GetChatMember

func (b *Bot) GetChatMember(recipient Recipient, user User) (ChatMember, error)

GetChatMember return information about a member of a chat.

Returns a ChatMember object on success.

func (*Bot) GetChatMembersCount

func (b *Bot) GetChatMembersCount(recipient Recipient) (int, error)

GetChatMembersCount return the number of members in a chat.

Returns Int on success.

func (*Bot) GetFile

func (b *Bot) GetFile(fileID string) (File, error)

GetFile returns full file object including File.FilePath, which allow you to load file from Telegram

Usually File objects does not contain any FilePath so you need to perform additional request

func (*Bot) GetFileDirectURL

func (b *Bot) GetFileDirectURL(fileID string) (string, error)

GetFileDirectURL returns direct url for files using FileId which you can get from File object

func (*Bot) GetUserProfilePhotos

func (b *Bot) GetUserProfilePhotos(recipient Recipient) (UserProfilePhotos, error)

GetUserProfilePhotos return list of profile pictures for a user.

Returns a UserProfilePhotos object.

func (*Bot) Handle

func (b *Bot) Handle(prefix string, handler Handler)

func (*Bot) LeaveChat

func (b *Bot) LeaveChat(recipient Recipient) error

LeaveChat makes bot leave a group, supergroup or channel.

func (*Bot) Listen

func (b *Bot) Listen(subscription chan Message, timeout time.Duration)

Listen starts a new polling goroutine, one that periodically looks for updates and delivers new messages to the subscription channel.

func (*Bot) Respond

func (b *Bot) Respond(query Query, results []Result) error

Respond publishes a set of responses for an inline query. This function is deprecated in favor of AnswerInlineQuery.

func (*Bot) SendAudio

func (b *Bot) SendAudio(recipient Recipient, audio *Audio, options *SendOptions) error

SendAudio sends an audio object to recipient.

On success, audio object would be aliased to its copy on the Telegram servers, so sending the same audio object again, won't issue a new upload, but would make a use of existing file on Telegram servers.

func (*Bot) SendChatAction

func (b *Bot) SendChatAction(recipient Recipient, action ChatAction) error

SendChatAction updates a chat action for recipient.

Chat action is a status message that recipient would see where you typically see "Harry is typing" status message. The only difference is that bots' chat actions live only for 5 seconds and die just once the client recieves a message from the bot.

Currently, Telegram supports only a narrow range of possible actions, these are aligned as constants of this package.

func (*Bot) SendDocument

func (b *Bot) SendDocument(recipient Recipient, doc *Document, options *SendOptions) error

SendDocument sends a general document object to recipient.

On success, document object would be aliased to its copy on the Telegram servers, so sending the same document object again, won't issue a new upload, but would make a use of existing file on Telegram servers.

func (*Bot) SendLocation

func (b *Bot) SendLocation(recipient Recipient, geo *Location, options *SendOptions) error

SendLocation sends a general document object to recipient.

On success, video object would be aliased to its copy on the Telegram servers, so sending the same video object again, won't issue a new upload, but would make a use of existing file on Telegram servers.

func (*Bot) SendMessage

func (b *Bot) SendMessage(recipient Recipient, message string, options *SendOptions) error

SendMessage sends a text message to recipient.

func (*Bot) SendPhoto

func (b *Bot) SendPhoto(recipient Recipient, photo *Photo, options *SendOptions) error

SendPhoto sends a photo object to recipient.

On success, photo object would be aliased to its copy on the Telegram servers, so sending the same photo object again, won't issue a new upload, but would make a use of existing file on Telegram servers.

func (*Bot) SendSticker

func (b *Bot) SendSticker(recipient Recipient, sticker *Sticker, options *SendOptions) error

SendSticker sends a general document object to recipient.

On success, sticker object would be aliased to its copy on the Telegram servers, so sending the same sticker object again, won't issue a new upload, but would make a use of existing file on Telegram servers.

func (*Bot) SendVenue

func (b *Bot) SendVenue(recipient Recipient, venue *Venue, options *SendOptions) error

SendVenue sends a venue object to recipient.

func (*Bot) SendVideo

func (b *Bot) SendVideo(recipient Recipient, video *Video, options *SendOptions) error

SendVideo sends a general document object to recipient.

On success, video object would be aliased to its copy on the Telegram servers, so sending the same video object again, won't issue a new upload, but would make a use of existing file on Telegram servers.

func (*Bot) Serve

func (b *Bot) Serve(msg Message) (ok bool)

func (*Bot) Start

func (b *Bot) Start(timeout time.Duration)

Start periodically polls messages, updates and callbacks into their corresponding channels of the bot object.

NOTE: It's a blocking method!

type Callback

type Callback struct {
	ID string `json:"id"`

	// For message sent to channels, Sender may be empty
	Sender User `json:"from"`

	// Message will be set if the button that originated the query
	// was attached to a message sent by a bot.
	Message Message `json:"message"`

	// MessageID will be set if the button was attached to a message
	// sent via the bot in inline mode.
	MessageID string `json:"inline_message_id"`

	// Data associated with the callback button. Be aware that
	// a bad client can send arbitrary data in this field.
	Data string `json:"data"`
}

Callback object represents a query from a callback button in an inline keyboard.

type CallbackResponse

type CallbackResponse struct {
	// The ID of the callback to which this is a response.
	// It is not necessary to specify this field manually.
	CallbackID string `json:"callback_query_id"`

	// Text of the notification. If not specified, nothing will be shown to the user.
	Text string `json:"text,omitempty"`

	// (Optional) If true, an alert will be shown by the client instead
	// of a notification at the top of the chat screen. Defaults to false.
	ShowAlert bool `json:"show_alert,omitempty"`

	// (Optional) URL that will be opened by the user's client.
	// If you have created a Game and accepted the conditions via @Botfather
	// specify the URL that opens your game
	// note that this will only work if the query comes from a callback_game button.
	// Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
	URL string `json:"url,omitempty"`
}

CallbackResponse builds a response to a Callback query.

See also: https://core.telegram.org/bots/api#answerCallbackQuery

type Chat

type Chat struct {
	ID int64 `json:"id"`

	// Won't be there for ChatPrivate.
	Title string `json:"title"`

	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Username  string `json:"username"`

	// Group/channel-specific values (see telebot.ChatType):
	Type          ChatType  `json:"type"`
	Photo         ChatPhoto `json:"photo"`
	Description   string    `json:"description"`
	InviteLink    string    `json:"invite_link"`
	AllAdminGroup bool      `json:"all_members_are_administrators"`
	PinnedMessage *Message  `json:"pinned_message"`
}

Chat object represents a Telegram user, bot or group chat.

Type of chat, can be either “private”, “group”, "supergroup" or “channel”

func (Chat) Destination

func (c Chat) Destination() string

Destination is internal chat ID.

func (Chat) IsGroupChat

func (c Chat) IsGroupChat() bool

IsGroupChat returns true if chat object represents a group chat.

type ChatAction

type ChatAction string

ChatAction is a client-side status indicating bot activity.

const (
	Typing            ChatAction = "typing"
	UploadingPhoto    ChatAction = "upload_photo"
	UploadingVideo    ChatAction = "upload_video"
	UploadingAudio    ChatAction = "upload_audio"
	UploadingDocument ChatAction = "upload_document"
	RecordingVideo    ChatAction = "record_video"
	RecordingAudio    ChatAction = "record_audio"
	FindingLocation   ChatAction = "find_location"
)

type ChatMember

type ChatMember struct {
	User   User   `json:"user"`
	Status string `json:"status"`
}

ChatMember object represents information about a single chat member.

type ChatPhoto

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

ChatPhoto object represents small/big file IDs for the group pic.

Both are download-only.

type ChatType

type ChatType string

ChatType represents one of the possible chat types.

const (
	ChatPrivate    ChatType = "private"
	ChatGroup      ChatType = "group"
	ChatSuperGroup ChatType = "supergroup"
	ChatChannel    ChatType = "channel"
)

type Contact

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

Contact object represents a contact to Telegram user

type Context

type Context struct {
	Bot     *Bot
	Message Message
}

type Document

type Document struct {
	File

	// Document thumbnail as defined by sender.
	Preview Thumbnail `json:"thumb"`

	// Original filename as defined by sender.
	FileName string `json:"file_name"`

	// MIME type of the file as defined by sender.
	Mime string `json:"mime_type"`
}

Document object represents a general file (as opposed to Photo or Audio). Telegram users can send files of any type of up to 1.5 GB in size.

type EntityType

type EntityType string

EntityType is a MessageEntity type.

const (
	EntityMention   EntityType = "mention"
	EntityTMention  EntityType = "text_mention"
	EntityHashtag   EntityType = "hashtag"
	EntityCommand   EntityType = "bot_command"
	EntityURL       EntityType = "url"
	EntityEmail     EntityType = "email"
	EntityBold      EntityType = "bold"
	EntityItalic    EntityType = "italic"
	EntityCode      EntityType = "code"
	EntityCodeBlock EntityType = "pre"
	EntityTextLink  EntityType = "text_link"
)

type File

type File struct {
	FileID   string `json:"file_id"`
	FileSize int    `json:"file_size"`
	FilePath string `json:"file_path"`
	// contains filtered or unexported fields
}

File object represents any sort of file.

func NewFile

func NewFile(path string) (File, error)

NewFile attempts to create a File object, leading to a real file on the file system, that could be uploaded later.

Notice that NewFile doesn't upload file, but only creates a descriptor for it.

func (File) Exists

func (f File) Exists() bool

Exists says whether the file presents on Telegram servers or not.

func (File) Local

func (f File) Local() string

Local returns location of file on local file system, if it's actually there, otherwise returns empty string.

type Handler

type Handler func(Context)

type InlineKeyboardMarkup

type InlineKeyboardMarkup struct {
	// Array of button rows, each represented by
	// an Array of KeyboardButton objects.
	InlineKeyboard [][]KeyboardButton `json:"inline_keyboard,omitempty"`
}

InlineKeyboardMarkup represents an inline keyboard that appears right next to the message it belongs to.

type InlineQueryResult

type InlineQueryResult interface {
	GetID() string
	SetID(string)
}

InlineQueryResult represents one result of an inline query.

type InlineQueryResultArticle

type InlineQueryResultArticle struct {
	InlineQueryResultBase

	// Title of the result.
	Title string `json:"title"`

	// Message text. Shortcut (and mutually exclusive to) specifying
	// InputMessageContent.
	Text string `json:"message_text,omitempty"`

	// Content of the message to be sent.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. URL of the result.
	URL string `json:"url,omitempty"`

	// Optional. Pass True, if you don't want the URL to be shown in the message.
	HideURL bool `json:"hide_url,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. Url of the thumbnail for the result.
	ThumbURL string `json:"thumb_url,omitempty"`

	// Optional. Thumbnail width.
	ThumbWidth int `json:"thumb_width,omitempty"`

	// Optional. Thumbnail height.
	ThumbHeight int `json:"thumb_height,omitempty"`
}

InlineQueryResultArticle represents a link to an article or web page. See also: https://core.telegram.org/bots/api#inlinequeryresultarticle

type InlineQueryResultAudio

type InlineQueryResultAudio struct {
	InlineQueryResultBase

	// A valid URL for the audio file.
	AudioURL string `json:"audio_url"`

	// Title.
	Title string `json:"title"`

	// Optional. Performer.
	Performer string `json:"performer,omitempty"`

	// Optional. Audio duration in seconds.
	Duration int `json:"audio_duration,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}

InlineQueryResultAudio represents a link to an mp3 audio file.

type InlineQueryResultBase

type InlineQueryResultBase struct {
	// Unique identifier for this result, 1-64 Bytes.
	// If left unspecified, a 64-bit FNV-1 hash will be calculated
	// from the other fields and used automatically.
	ID string `json:"id",hash:"ignore"`

	// Ignore. This field gets set automatically.
	Type string `json:"type",hash:"ignore"`
}

InlineQueryResultBase must be embedded into all IQRs.

func (*InlineQueryResultBase) GetID

func (result *InlineQueryResultBase) GetID() string

GetID is part of IQRBase's implementation of IQR interface.

func (*InlineQueryResultBase) SetID

func (result *InlineQueryResultBase) SetID(id string)

SetID is part of IQRBase's implementation of IQR interface.

type InlineQueryResultContact

type InlineQueryResultContact struct {
	InlineQueryResultBase

	// Contact's phone number.
	PhoneNumber string `json:"phone_number"`

	// Contact's first name.
	FirstName string `json:"first_name"`

	// Optional. Contact's last name.
	LastName string `json:"last_name,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`

	// Optional. Url of the thumbnail for the result.
	ThumbURL string `json:"thumb_url,omitempty"`

	// Optional. Thumbnail width.
	ThumbWidth int `json:"thumb_width,omitempty"`

	// Optional. Thumbnail height.
	ThumbHeight int `json:"thumb_height,omitempty"`
}

InlineQueryResultContact represents a contact with a phone number. See also: https://core.telegram.org/bots/api#inlinequeryresultcontact

type InlineQueryResultDocument

type InlineQueryResultDocument struct {
	InlineQueryResultBase

	// Title for the result.
	Title string `json:"title"`

	// A valid URL for the file
	DocumentURL string `json:"document_url"`

	// Mime type of the content of the file, either “application/pdf” or
	// “application/zip”.
	MimeType string `json:"mime_type"`

	// Optional. Caption of the document to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`

	// Optional. URL of the thumbnail (jpeg only) for the file.
	ThumbURL string `json:"thumb_url,omitempty"`

	// Optional. Thumbnail width.
	ThumbWidth int `json:"thumb_width,omitempty"`

	// Optional. Thumbnail height.
	ThumbHeight int `json:"thumb_height,omitempty"`
}

InlineQueryResultDocument represents a link to a file. See also: https://core.telegram.org/bots/api#inlinequeryresultdocument

type InlineQueryResultGif

type InlineQueryResultGif struct {
	InlineQueryResultBase

	// A valid URL for the GIF file. File size must not exceed 1MB.
	GifURL string `json:"gif_url"`

	// URL of the static thumbnail for the result (jpeg or gif).
	ThumbURL string `json:"thumb_url"`

	// Optional. Width of the GIF.
	GifWidth int `json:"gif_width,omitempty"`

	// Optional. Height of the GIF.
	GifHeight int `json:"gif_height,omitempty"`

	// Optional. Title for the result.
	Title string `json:"title,omitempty"`

	// Optional. Caption of the GIF file to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}

InlineQueryResultGif represents a link to an animated GIF file. See also: https://core.telegram.org/bots/api#inlinequeryresultgif

type InlineQueryResultLocation

type InlineQueryResultLocation struct {
	InlineQueryResultBase

	// Latitude of the location in degrees.
	Latitude float32 `json:"latitude"`

	// Longitude of the location in degrees.
	Longitude float32 `json:"longitude"`

	// Location title.
	Title string `json:"title"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`

	// Optional. Url of the thumbnail for the result.
	ThumbURL string `json:"thumb_url,omitempty"`

	// Optional. Thumbnail width.
	ThumbWidth int `json:"thumb_width,omitempty"`

	// Optional. Thumbnail height.
	ThumbHeight int `json:"thumb_height,omitempty"`
}

InlineQueryResultLocation represents a location on a map. See also: https://core.telegram.org/bots/api#inlinequeryresultlocation

type InlineQueryResultMpeg4Gif

type InlineQueryResultMpeg4Gif struct {
	InlineQueryResultBase

	// A valid URL for the MP4 file.
	URL string `json:"mpeg4_url"`

	// Optional. Video width.
	Width int `json:"mpeg4_width,omitempty"`

	// Optional. Video height.
	Height int `json:"mpeg4_height,omitempty"`

	// URL of the static thumbnail (jpeg or gif) for the result.
	ThumbURL string `json:"thumb_url,omitempty"`

	// Optional. Title for the result.
	Title string `json:"title,omitempty"`

	// Optional. Caption of the MPEG-4 file to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}

InlineQueryResultMpeg4Gif represents a link to a video animation (H.264/MPEG-4 AVC video without sound). See also: https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif

type InlineQueryResultPhoto

type InlineQueryResultPhoto struct {
	InlineQueryResultBase

	// A valid URL of the photo. Photo must be in jpeg format.
	// Photo size must not exceed 5MB.
	PhotoURL string `json:"photo_url"`

	// URL of the thumbnail for the photo.
	ThumbURL string `json:"thumb_url"`

	// Optional. Width of the photo.
	PhotoWidth int `json:"photo_width,omitempty"`

	// Optional. Height of the photo.
	PhotoHeight int `json:"photo_height,omitempty"`

	// Optional. Title for the result.
	Title string `json:"title,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. Caption of the photo to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}

InlineQueryResultPhoto represents a link to a photo. See also: https://core.telegram.org/bots/api#inlinequeryresultphoto

type InlineQueryResultVenue

type InlineQueryResultVenue struct {
	InlineQueryResultBase

	// Latitude of the venue location in degrees.
	Latitude float32 `json:"latitude"`

	// Longitude of the venue location in degrees.
	Longitude float32 `json:"longitude"`

	// Title of the venue.
	Title string `json:"title"`

	// Address of the venue.
	Address string `json:"address"`

	// Optional. Foursquare identifier of the venue if known.
	FoursquareID string `json:"foursquare_id,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`

	// Optional. Url of the thumbnail for the result.
	ThumbURL string `json:"thumb_url,omitempty"`

	// Optional. Thumbnail width.
	ThumbWidth int `json:"thumb_width,omitempty"`

	// Optional. Thumbnail height.
	ThumbHeight int `json:"thumb_height,omitempty"`
}

InlineQueryResultVenue represents a venue. See also: https://core.telegram.org/bots/api#inlinequeryresultvenue

type InlineQueryResultVideo

type InlineQueryResultVideo struct {
	InlineQueryResultBase

	// A valid URL for the embedded video player or video file.
	VideoURL string `json:"video_url"`

	// Mime type of the content of video url, “text/html” or “video/mp4”.
	MimeType string `json:"mime_type"`

	// URL of the thumbnail (jpeg only) for the video.
	ThumbURL string `json:"thumb_url"`

	// Title for the result.
	Title string `json:"title"`

	// Optional. Caption of the video to be sent, 0-200 characters.
	Caption string `json:"caption,omitempty"`

	// Optional. Video width.
	VideoWidth int `json:"video_width,omitempty"`

	// Optional. Video height.
	VideoHeight int `json:"video_height,omitempty"`

	// Optional. Video duration in seconds.
	VideoDuration int `json:"video_duration,omitempty"`

	// Optional. Short description of the result.
	Description string `json:"description,omitempty"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}

InlineQueryResultVideo represents a link to a page containing an embedded video player or a video file. See also: https://core.telegram.org/bots/api#inlinequeryresultvideo

type InlineQueryResultVoice

type InlineQueryResultVoice struct {
	InlineQueryResultBase

	// A valid URL for the voice recording.
	VoiceURL string `json:"voice_url"`

	// Recording title.
	Title string `json:"title"`

	// Optional. Recording duration in seconds.
	VoiceDuration int `json:"voice_duration"`

	// Optional. Inline keyboard attached to the message.
	ReplyMarkup InlineKeyboardMarkup `json:"reply_markup,omitempty"`

	// Optional. Content of the message to be sent instead of the audio.
	InputMessageContent InputMessageContent `json:"input_message_content,omitempty"`
}

InlineQueryResultVoice represents a link to a voice recording in a .ogg container encoded with OPUS. See also: https://core.telegram.org/bots/api#inlinequeryresultvoice

type InlineQueryResults

type InlineQueryResults []InlineQueryResult

InlineQueryResults is a slice wrapper for convenient marshalling.

func (*InlineQueryResults) MarshalJSON

func (results *InlineQueryResults) MarshalJSON() ([]byte, error)

MarshalJSON makes sure IQRs have proper IDs and Type variables set.

If ID of some result appears empty, it gets set to a new hash. JSON-specific Type gets infered from the actual (specific) IQR type.

type InputContactMessageContent

type InputContactMessageContent struct {
	// Contact's phone number.
	PhoneNumber string `json:"phone_number"`

	// Contact's first name.
	FirstName string `json:"first_name"`

	// Optional. Contact's last name.
	LastName string `json:"last_name,omitempty"`
}

InputContactMessageContent represents the content of a contact message to be sent as the result of an inline query. See also: https://core.telegram.org/bots/api#inputcontactmessagecontent

func (*InputContactMessageContent) IsInputMessageContent

func (input *InputContactMessageContent) IsInputMessageContent() bool

type InputLocationMessageContent

type InputLocationMessageContent struct {
	// Latitude of the location in degrees.
	Latitude float32 `json:"latitude"`

	// Longitude of the location in degrees.
	Longitude float32 `json:"longitude"`
}

InputLocationMessageContent represents the content of a location message to be sent as the result of an inline query. See also: https://core.telegram.org/bots/api#inputlocationmessagecontent

func (*InputLocationMessageContent) IsInputMessageContent

func (input *InputLocationMessageContent) IsInputMessageContent() bool

type InputMessageContent

type InputMessageContent interface {
	IsInputMessageContent() bool
}

InputMessageContent objects represent the content of a message to be sent as a result of an inline query. See also: https://core.telegram.org/bots/api#inputmessagecontent

type InputTextMessageContent

type InputTextMessageContent struct {
	// Text of the message to be sent, 1-4096 characters.
	Text string `json:"message_text"`

	// Optional. Send Markdown or HTML, if you want Telegram apps to show
	// bold, italic, fixed-width text or inline URLs in your bot's message.
	ParseMode string `json:"parse_mode,omitempty"`

	// Optional. Disables link previews for links in the sent message.
	DisablePreview bool `json:"disable_web_page_preview"`
}

InputTextMessageContent represents the content of a text message to be sent as the result of an inline query. See also: https://core.telegram.org/bots/api#inputtextmessagecontent

func (*InputTextMessageContent) IsInputMessageContent

func (input *InputTextMessageContent) IsInputMessageContent() bool

type InputVenueMessageContent

type InputVenueMessageContent struct {
	// Latitude of the location in degrees.
	Latitude float32 `json:"latitude"`

	// Longitude of the location in degrees.
	Longitude float32 `json:"longitude"`

	// Name of the venue.
	Title string `json:"title"`

	// Address of the venue.
	Address string `json:"address"`

	// Optional. Foursquare identifier of the venue, if known.
	FoursquareID string `json:"foursquare_id,omitempty"`
}

InputVenueMessageContent represents the content of a venue message to be sent as the result of an inline query. See also: https://core.telegram.org/bots/api#inputvenuemessagecontent

func (*InputVenueMessageContent) IsInputMessageContent

func (input *InputVenueMessageContent) IsInputMessageContent() bool

type KeyboardButton

type KeyboardButton struct {
	Text        string `json:"text"`
	URL         string `json:"url,omitempty"`
	Data        string `json:"callback_data,omitempty"`
	InlineQuery string `json:"switch_inline_query,omitempty"`
}

KeyboardButton represents a button displayed on in a message.

type Location

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

Location object represents geographic position.

type Message

type Message struct {
	ID int `json:"message_id"`

	// For message sent to channels, Sender may be empty
	Sender User `json:"from"`

	Unixtime int `json:"date"`

	// For forwarded messages, sender of the original message.
	OriginalSender User `json:"forward_from"`

	// For forwarded messages, chat of the original message when forwarded from a channel.
	OriginalChat Chat `json:"forward_from_chat"`

	// For forwarded messages, unixtime of the original message.
	OriginalUnixtime int `json:"forward_date"`

	// For replies, ReplyTo represents the original message.
	// Note that the Message object in this field will not
	// contain further ReplyTo fields even if it
	// itself is a reply.
	ReplyTo *Message `json:"reply_to_message"`

	// For a text message, the actual UTF-8 text of the message
	Text string `json:"text"`

	// For an audio recording, information about it.
	Audio Audio `json:"audio"`

	// For a general file, information about it.
	Document Document `json:"document"`

	// For a photo, available thumbnails.
	Photo []Thumbnail `json:"photo"`

	// For a sticker, information about it.
	Sticker Sticker `json:"sticker"`

	// For a video, information about it.
	Video Video `json:"video"`

	// For a contact, contact information itself.
	Contact Contact `json:"contact"`

	// For a location, its longitude and latitude.
	Location Location `json:"location"`

	// A group chat message belongs to, empty if personal.
	Chat Chat `json:"chat"`

	// For a service message, represents a user,
	// that just got added to chat, this message came from.
	//
	// Sender leads to User, capable of invite.
	//
	// UserJoined might be the Bot itself.
	UserJoined User `json:"new_chat_member"`

	// For a service message, represents a user,
	// that just left chat, this message came from.
	//
	// If user was kicked, Sender leads to a User,
	// capable of this kick.
	//
	// UserLeft might be the Bot itself.
	UserLeft User `json:"left_chat_member"`

	// For a service message, represents a new title
	// for chat this message came from.
	//
	// Sender would lead to a User, capable of change.
	NewChatTitle string `json:"new_chat_title"`

	// For a service message, represents all available
	// thumbnails of new chat photo.
	//
	// Sender would lead to a User, capable of change.
	NewChatPhoto []Thumbnail `json:"new_chat_photo"`

	// For a service message, true if chat photo just
	// got removed.
	//
	// Sender would lead to a User, capable of change.
	ChatPhotoDeleted bool `json:"delete_chat_photo"`

	// For a service message, true if group has been created.
	//
	// You would recieve such a message if you are one of
	// initial group chat members.
	//
	// Sender would lead to creator of the chat.
	ChatCreated bool `json:"group_chat_created"`

	// For a service message, true if super group has been created.
	//
	// You would recieve such a message if you are one of
	// initial group chat members.
	//
	// Sender would lead to creator of the chat.
	SuperGroupCreated bool `json:"supergroup_chat_created"`

	// For a service message, true if channel has been created.
	//
	// You would recieve such a message if you are one of
	// initial channel administrators.
	//
	// Sender would lead to creator of the chat.
	ChannelCreated bool `json:"channel_chat_created"`

	// For a service message, the destination (super group) you
	// migrated to.
	//
	// You would recieve such a message when your chat has migrated
	// to a super group.
	//
	// Sender would lead to creator of the migration.
	MigrateTo int64 `json:"migrate_to_chat_id"`

	// For a service message, the Origin (normal group) you migrated
	// from.
	//
	// You would recieve such a message when your chat has migrated
	// to a super group.
	//
	// Sender would lead to creator of the migration.
	MigrateFrom int64 `json:"migrate_from_chat_id"`

	Entities []MessageEntity `json:"entities,omitempty"`

	Caption string `json:"caption,omitempty"`
}

Message object represents a message.

func (*Message) IsForwarded

func (m *Message) IsForwarded() bool

IsForwarded says whether message is forwarded copy of another message or not.

func (*Message) IsPersonal

func (m *Message) IsPersonal() bool

IsPersonal returns true, if message is a personal message, returns false if sent to group chat.

func (*Message) IsReply

func (m *Message) IsReply() bool

IsReply says whether message is reply to another message or not.

func (*Message) IsService

func (m *Message) IsService() bool

IsService returns true, if message is a service message, returns false otherwise.

Service messages are automatically sent messages, which typically occur on some global action. For instance, when anyone leaves the chat or chat title changes.

func (*Message) Origin

func (m *Message) Origin() User

Origin returns an origin of message: group chat / personal.

func (*Message) Time

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

Time returns the moment of message creation in local time.

type MessageEntity

type MessageEntity struct {
	// Specifies entity type.
	Type EntityType `json:"type"`

	// Offset in UTF-16 code units to the start of the entity.
	Offset int `json:"offset"`

	// Length of the entity in UTF-16 code units.
	Length int `json:"length"`

	// (Optional) For EntityTextLink entity type only.
	//
	// URL will be opened after user taps on the text.
	URL string `json:"url,omitempty"`

	// (Optional) For EntityTMention entity type only.
	User User `json:"user,omitempty"`
}

MessageEntity object represents "special" parts of text messages, including hashtags, usernames, URLs, etc.

type ParseMode

type ParseMode string

ParseMode determines the way client applications treat the text of the message

const (
	ModeDefault  ParseMode = ""
	ModeMarkdown ParseMode = "Markdown"
	ModeHTML     ParseMode = "HTML"
)

type Photo

type Photo struct {
	File

	Thumbnail

	Caption string
}

Photo object represents a photo with caption.

type Query

type Query struct {
	// Unique identifier for this query.
	ID string `json:"id"`

	// Sender.
	From User `json:"from"`

	// (Optional) Sender location, only for bots that request user location.
	Location Location `json:"location"`

	// Text of the query (up to 512 characters).
	Text string `json:"query"`

	// Offset of the results to be returned, can be controlled by the bot.
	Offset string `json:"offset"`
}

Query is an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

type QueryResponse

type QueryResponse struct {
	// The ID of the query to which this is a response.
	// It is not necessary to specify this field manually.
	QueryID string `json:"inline_query_id"`

	// The results for the inline query.
	Results InlineQueryResults `json:"results"`

	// (Optional) The maximum amount of time in seconds that the result
	// of the inline query may be cached on the server.
	CacheTime int `json:"cache_time,omitempty"`

	// (Optional) Pass True, if results may be cached on the server side
	// only for the user that sent the query. By default, results may
	// be returned to any user who sends the same query.
	IsPersonal bool `json:"is_personal"`

	// (Optional) Pass the offset that a client should send in the next
	// query with the same text to receive more results. Pass an empty
	// string if there are no more results or if you don‘t support
	// pagination. Offset length can’t exceed 64 bytes.
	NextOffset string `json:"next_offset"`

	// (Optional) If passed, clients will display a button with specified
	// text that switches the user to a private chat with the bot and sends
	// the bot a start message with the parameter switch_pm_parameter.
	SwitchPMText string `json:"switch_pm_text,omitempty"`

	// (Optional) Parameter for the start message sent to the bot when user
	// presses the switch button.
	SwitchPMParameter string `json:"switch_pm_parameter,omitempty"`
}

QueryResponse builds a response to an inline Query. See also: https://core.telegram.org/bots/api#answerinlinequery

type Recipient

type Recipient interface {
	// ID of user or group chat, @Username for channel
	Destination() string
}

Recipient is basically any possible endpoint you can send messages to. It's usually a distinct user or a chat.

type ReplyMarkup

type ReplyMarkup struct {
	// ForceReply forces Telegram clients to display
	// a reply interface to the user (act as if the user
	// has selected the bot‘s message and tapped "Reply").
	ForceReply bool `json:"force_reply,omitempty"`

	// CustomKeyboard is Array of button rows, each represented by an Array of Strings.
	//
	// Note: you don't need to set HideCustomKeyboard field to show custom keyboard.
	CustomKeyboard [][]string `json:"keyboard,omitempty"`

	InlineKeyboard [][]KeyboardButton `json:"inline_keyboard,omitempty"`

	// Requests clients to resize the keyboard vertically for optimal fit
	// (e.g., make the keyboard smaller if there are just two rows of buttons).
	// Defaults to false, in which case the custom keyboard is always of the
	// same height as the app's standard keyboard.
	ResizeKeyboard bool `json:"resize_keyboard,omitempty"`
	// Requests clients to hide the keyboard as soon as it's been used. Defaults to false.
	OneTimeKeyboard bool `json:"one_time_keyboard,omitempty"`

	// Requests clients to hide the custom keyboard.
	//
	// Note: You dont need to set CustomKeyboard field to hide custom keyboard.
	HideCustomKeyboard bool `json:"hide_keyboard,omitempty"`

	// Use this param if you want to force reply from
	// specific users only.
	//
	// Targets:
	// 1) Users that are @mentioned in the text of the Message object;
	// 2) If the bot's message is a reply (has SendOptions.ReplyTo),
	//       sender of the original message.
	Selective bool `json:"selective,omitempty"`
}

ReplyMarkup specifies convenient options for bot-user communications.

type Result

type Result interface {
	MarshalJSON() ([]byte, error)
}

Result is a deprecated type, superseded by InlineQueryResult.

type SendOptions

type SendOptions struct {
	// If the message is a reply, original message.
	ReplyTo Message

	// See ReplyMarkup struct definition.
	ReplyMarkup ReplyMarkup

	// For text messages, disables previews for links in this message.
	DisableWebPagePreview bool

	// Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.
	DisableNotification bool

	// ParseMode controls how client apps render your message.
	ParseMode ParseMode
}

SendOptions represents a set of custom options that could be appled to messages sent.

type Sticker

type Sticker struct {
	File

	Width  int `json:"width"`
	Height int `json:"height"`

	// Sticker thumbnail in .webp or .jpg format.
	Preview Thumbnail `json:"thumb"`
}

Sticker object represents a WebP image, so-called sticker.

type Thumbnail

type Thumbnail struct {
	File

	Width  int `json:"width"`
	Height int `json:"height"`
}

Thumbnail object represents an image/sticker of a particular size.

type Update

type Update struct {
	ID      int64    `json:"update_id"`
	Payload *Message `json:"message"`

	// optional
	Callback *Callback `json:"callback_query"`
	Query    *Query    `json:"inline_query"`
}

Update object represents an incoming update.

type User

type User struct {
	ID        int    `json:"id"`
	FirstName string `json:"first_name"`

	// Optional!
	LastName string `json:"last_name"`
	Username string `json:"username"`

	// True for bots.
	IsBot bool `json:"is_bot"`

	// Optional. IETF language tag of the user's language.
	Language string `json:"language_code"`
}

User object represents a Telegram user or bot.

func (User) Destination

func (u User) Destination() string

Destination is internal user ID.

type UserProfilePhotos

type UserProfilePhotos struct {
	// Total number of profile pictures the target user has.
	Count int `json:"total_count"`

	// Requested profile pictures (in up to 4 sizes each).
	Photos [][]Photo `json:"photos"`
}

UserProfilePhotos object represent a user's profile pictures.

type Venue

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

Venue object represents a venue location with name, address and optional foursquare ID.

type Video

type Video struct {
	Audio

	Width  int `json:"width"`
	Height int `json:"height"`

	// Text description of the video as defined by sender (usually empty).
	Caption string `json:"caption"`

	// Video thumbnail.
	Preview Thumbnail `json:"thumb"`
}

Video object represents an MP4-encoded video.

Jump to

Keyboard shortcuts

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