Keeping PR up-to-date with recent master changes.

pull/76/head
Ian Byrd 8 years ago
commit 196512b59e
No known key found for this signature in database
GPG Key ID: 598F598CA3B8055F

@ -1,34 +1,34 @@
# Telebot # Telebot
>Telebot is a convenient wrapper to Telegram Bots API, written in Golang. >Telebot is a Telegram bot framework in Go.
[![GoDoc](https://godoc.org/github.com/tucnak/telebot?status.svg)](https://godoc.org/github.com/tucnak/telebot) [![GoDoc](https://godoc.org/github.com/tucnak/telebot?status.svg)](https://godoc.org/github.com/tucnak/telebot)
[![Travis](https://travis-ci.org/tucnak/telebot.svg?branch=master)](https://travis-ci.org/tucnak/telebot) [![Travis](https://travis-ci.org/tucnak/telebot.svg?branch=master)](https://travis-ci.org/tucnak/telebot)
Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server. Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots
by sending them command messages in private or group chats. These accounts serve as an interface for
code running somewhere on your server.
Telebot offers a convenient wrapper to Bots API, so you shouldn't even Telebot offers a convenient wrapper to Bots API, so you shouldn't even
care about networking at all. You may install it with bother about networking at all. You may install it with
go get github.com/tucnak/telebot go get github.com/tucnak/telebot
(after setting up your `GOPATH` properly). (after setting up your `GOPATH` properly).
Since you are probably We highly recommend you to keep your bot access token outside the code base,
hosting your bot in a public repository, we'll add an environment preferably as an environmental variable:
variable for the token in this example. Please set it with
export BOT_TOKEN=<your token here> export BOT_TOKEN=<your token here>
Take a look at a minimal functional bot setup:
Here is an example "helloworld" bot, written with telebot:
```go ```go
package main package main
import ( import (
"log" "log"
"time"
"os" "os"
"time"
"github.com/tucnak/telebot" "github.com/tucnak/telebot"
) )
@ -38,7 +38,7 @@ func main() {
log.Fatalln(err) log.Fatalln(err)
} }
messages := make(chan telebot.Message) messages := make(chan telebot.Message, 100)
bot.Listen(messages, 1*time.Second) bot.Listen(messages, 1*time.Second)
for message := range messages { for message := range messages {
@ -51,9 +51,8 @@ func main() {
``` ```
## Inline mode ## Inline mode
As of January 4, 2016, Telegram added inline mode support for bots. Here's
As of January 4, 2016, Telegram added inline mode support for bots. a nice way to handle both incoming messages and inline queries in the meantime:
Telebot support inline mode in a fancy manner. Here's a nice way to handle both incoming messages and inline queries:
```go ```go
package main package main
@ -65,47 +64,45 @@ import (
"github.com/tucnak/telebot" "github.com/tucnak/telebot"
) )
var bot *telebot.Bot
func main() { func main() {
var err error bot, err := telebot.NewBot(os.Getenv("BOT_TOKEN"))
bot, err = telebot.NewBot(os.Getenv("BOT_TOKEN"))
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
bot.Messages = make(chan telebot.Message, 1000) bot.Messages = make(chan telebot.Message, 100)
bot.Queries = make(chan telebot.Query, 1000) bot.Queries = make(chan telebot.Query, 1000)
go messages() go messages(bot)
go queries() go queries(bot)
bot.Start(1 * time.Second) bot.Start(1 * time.Second)
} }
func messages() { func messages(bot *telebot.Bot) {
for message := range bot.Messages { for message := range bot.Messages {
log.Printf("Received a message from %s with the text: %s\n", message.Sender.Username, message.Text) log.Printf("Received a message from %s with the text: %s\n",
message.Sender.Username, message.Text)
} }
} }
func queries() { func queries(bot *telebot.Bot) {
for query := range bot.Queries { for query := range bot.Queries {
log.Println("--- new query ---") log.Println("--- new query ---")
log.Println("from:", query.From.Username) log.Println("from:", query.From.Username)
log.Println("text:", query.Text) log.Println("text:", query.Text)
// Create an article (a link) object to show in our results. // Create an article (a link) object to show in results.
article := &telebot.InlineQueryResultArticle{ article := &telebot.InlineQueryResultArticle{
Title: "Telegram bot framework written in Go", Title: "Telebot",
URL: "https://github.com/tucnak/telebot", URL: "https://github.com/tucnak/telebot",
InputMessageContent: &telebot.InputTextMessageContent{ InputMessageContent: &telebot.InputTextMessageContent{
Text: "Telebot is a convenient wrapper to Telegram Bots API, written in Golang.", Text: "Telebot is a Telegram bot framework.",
DisablePreview: false, DisablePreview: false,
}, },
} }
// Build the list of results. In this instance, just our 1 article from above. // Build the list of results (make sure to pass pointers!).
results := []telebot.InlineQueryResult{article} results := []telebot.InlineQueryResult{article}
// Build a response object to answer the query. // Build a response object to answer the query.
@ -114,7 +111,7 @@ func queries() {
IsPersonal: true, IsPersonal: true,
} }
// And finally send the response. // Send it.
if err := bot.AnswerInlineQuery(&query, &response); err != nil { if err := bot.AnswerInlineQuery(&query, &response); err != nil {
log.Println("Failed to respond to query:", err) log.Println("Failed to respond to query:", err)
} }
@ -123,8 +120,8 @@ func queries() {
``` ```
## Files ## Files
Telebot lets you upload files from the file system: Telebot lets you upload files from the file system:
```go ```go
boom, err := telebot.NewFile("boom.ogg") boom, err := telebot.NewFile("boom.ogg")
if err != nil { if err != nil {
@ -139,16 +136,16 @@ err = bot.SendAudio(recipient, &audio, nil)
``` ```
## Reply markup ## 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: 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:
```go ```go
// Send a selective force reply message. // Send a selective force reply message.
bot.SendMessage(user, "pong", &telebot.SendOptions{ bot.SendMessage(user, "pong", &telebot.SendOptions{
ReplyMarkup: telebot.ReplyMarkup{ ReplyMarkup: telebot.ReplyMarkup{
ForceReply: true, ForceReply: true,
Selective: true, Selective: true,
CustomKeyboard: [][]string{ CustomKeyboard: [][]string{
[]string{"1", "2", "3"}, []string{"1", "2", "3"},
[]string{"4", "5", "6"}, []string{"4", "5", "6"},
[]string{"7", "8", "9"}, []string{"7", "8", "9"},

@ -49,7 +49,7 @@ func (b *Bot) poll(
callbacks chan Callback, callbacks chan Callback,
timeout time.Duration, timeout time.Duration,
) { ) {
var latestUpdate int64 = 0 var latestUpdate int64
for { for {
updates, err := getUpdates(b.Token, updates, err := getUpdates(b.Token,
@ -462,8 +462,8 @@ func (b *Bot) SendVenue(recipient Recipient, venue *Venue, options *SendOptions)
"longitude": fmt.Sprintf("%f", venue.Location.Longitude), "longitude": fmt.Sprintf("%f", venue.Location.Longitude),
"title": venue.Title, "title": venue.Title,
"address": venue.Address} "address": venue.Address}
if venue.Foursquare_id != "" { if venue.FoursquareID != "" {
params["foursquare_id"] = venue.Foursquare_id params["foursquare_id"] = venue.FoursquareID
} }
if options != nil { if options != nil {
@ -502,10 +502,10 @@ func (b *Bot) SendVenue(recipient Recipient, venue *Venue, options *SendOptions)
// //
// Currently, Telegram supports only a narrow range of possible // Currently, Telegram supports only a narrow range of possible
// actions, these are aligned as constants of this package. // actions, these are aligned as constants of this package.
func (b *Bot) SendChatAction(recipient Recipient, action string) error { func (b *Bot) SendChatAction(recipient Recipient, action ChatAction) error {
params := map[string]string{ params := map[string]string{
"chat_id": recipient.Destination(), "chat_id": recipient.Destination(),
"action": action, "action": string(action),
} }
responseJSON, err := sendCommand("sendChatAction", b.Token, params) responseJSON, err := sendCommand("sendChatAction", b.Token, params)
@ -733,7 +733,7 @@ func (b *Bot) GetChatAdministrators(recipient Recipient) ([]ChatMember, error) {
var responseRecieved struct { var responseRecieved struct {
Ok bool Ok bool
Result []ChatMember Result []ChatMember
Description string `json:"description",omitempty` Description string `json:"description"`
} }
err = json.Unmarshal(responseJSON, &responseRecieved) err = json.Unmarshal(responseJSON, &responseRecieved)
@ -763,7 +763,7 @@ func (b *Bot) GetChatMembersCount(recipient Recipient) (int, error) {
var responseRecieved struct { var responseRecieved struct {
Ok bool Ok bool
Result int Result int
Description string `json:"description",omitempty` Description string `json:"description"`
} }
err = json.Unmarshal(responseJSON, &responseRecieved) err = json.Unmarshal(responseJSON, &responseRecieved)
@ -793,7 +793,7 @@ func (b *Bot) GetUserProfilePhotos(recipient Recipient) (UserProfilePhotos, erro
var responseRecieved struct { var responseRecieved struct {
Ok bool Ok bool
Result UserProfilePhotos Result UserProfilePhotos
Description string `json:"description",omitempty` Description string `json:"description"`
} }
err = json.Unmarshal(responseJSON, &responseRecieved) err = json.Unmarshal(responseJSON, &responseRecieved)
@ -824,7 +824,7 @@ func (b *Bot) GetChatMember(recipient Recipient, user User) (ChatMember, error)
var responseRecieved struct { var responseRecieved struct {
Ok bool Ok bool
Result ChatMember Result ChatMember
Description string `json:"description",omitempty` Description string `json:"description"`
} }
err = json.Unmarshal(responseJSON, &responseRecieved) err = json.Unmarshal(responseJSON, &responseRecieved)

@ -19,7 +19,7 @@ type InputTextMessageContent struct {
ParseMode string `json:"parse_mode,omitempty"` ParseMode string `json:"parse_mode,omitempty"`
// Optional. Disables link previews for links in the sent message. // Optional. Disables link previews for links in the sent message.
DisablePreview bool `json:"disable_web_page_preview` DisablePreview bool `json:"disable_web_page_preview"`
} }
func (input *InputTextMessageContent) IsInputMessageContent() bool { func (input *InputTextMessageContent) IsInputMessageContent() bool {

@ -129,9 +129,9 @@ type Message struct {
// Sender would lead to creator of the migration. // Sender would lead to creator of the migration.
MigrateFrom int64 `json:"migrate_from_chat_id"` MigrateFrom int64 `json:"migrate_from_chat_id"`
Entities []MessageEntity `json:"entities",omitempty` Entities []MessageEntity `json:"entities,omitempty"`
Caption string `json:"caption",omitempty` Caption string `json:"caption,omitempty"`
} }
// Origin returns an origin of message: group chat / personal. // Origin returns an origin of message: group chat / personal.

@ -1,15 +1,5 @@
package telebot package telebot
// ParseMode determines the way client applications treat the text of the message
type ParseMode string
// Supported ParseMode
const (
ModeDefault ParseMode = ""
ModeMarkdown ParseMode = "Markdown"
ModeHTML ParseMode = "HTML"
)
// SendOptions represents a set of custom options that could // SendOptions represents a set of custom options that could
// be appled to messages sent. // be appled to messages sent.
type SendOptions struct { type SendOptions struct {

@ -27,14 +27,52 @@
// //
package telebot package telebot
// A bunch of available chat actions. // ChatAction is a client-side status indicating bot activity.
type ChatAction string
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"
)
// ParseMode determines the way client applications treat the text of the message
type ParseMode string
const (
ModeDefault ParseMode = ""
ModeMarkdown ParseMode = "Markdown"
ModeHTML ParseMode = "HTML"
)
// EntityType is a MessageEntity type.
type EntityType string
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"
)
// ChatType represents one of the possible chat types.
type ChatType string
const ( const (
Typing = "typing" ChatPrivate ChatType = "private"
UploadingPhoto = "upload_photo" ChatGroup ChatType = "group"
UploadingVideo = "upload_video" ChatSuperGroup ChatType = "supergroup"
UploadingAudio = "upload_audio" ChatChannel ChatType = "channel"
UploadingDocument = "upload_document"
RecordingVideo = "record_video"
RecordingAudio = "record_audio"
FindingLocation = "find_location"
) )

@ -26,13 +26,17 @@ func (u User) Destination() string {
} }
// Chat object represents a Telegram user, bot or group chat. // Chat object represents a Telegram user, bot or group chat.
// Title for channels and group chats //
// Type of chat, can be either “private”, “group”, "supergroup" or “channel” // Type of chat, can be either “private”, “group”, "supergroup" or “channel”
type Chat struct { type Chat struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Type string `json:"type"`
// See telebot.ChatType and consts.
Type ChatType `json:"type"`
// Won't be there for ChatPrivate.
Title string `json:"title"` Title string `json:"title"`
FirstName string `json:"first_name"` FirstName string `json:"first_name"`
LastName string `json:"last_name"` LastName string `json:"last_name"`
Username string `json:"username"` Username string `json:"username"`
@ -147,10 +151,11 @@ type KeyboardButton struct {
InlineQuery string `json:"switch_inline_query,omitempty"` InlineQuery string `json:"switch_inline_query,omitempty"`
} }
// InlineKeyboardMarkup represents an inline keyboard that appears right next // InlineKeyboardMarkup represents an inline keyboard that appears
// to the message it belongs to. // right next to the message it belongs to.
type InlineKeyboardMarkup struct { type InlineKeyboardMarkup struct {
// Array of button rows, each represented by an Array of KeyboardButton objects. // Array of button rows, each represented by
// an Array of KeyboardButton objects.
InlineKeyboard [][]KeyboardButton `json:"inline_keyboard,omitempty"` InlineKeyboard [][]KeyboardButton `json:"inline_keyboard,omitempty"`
} }
@ -183,10 +188,14 @@ type Callback struct {
// MessageID will be set if the button was attached to a message // MessageID will be set if the button was attached to a message
// sent via the bot in inline mode. // sent via the bot in inline mode.
MessageID string `json:"inline_message_id"` 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"` Data string `json:"data"`
} }
// CallbackResponse builds a response to an Callback query. // CallbackResponse builds a response to a Callback query.
//
// See also: https://core.telegram.org/bots/api#answerCallbackQuery // See also: https://core.telegram.org/bots/api#answerCallbackQuery
type CallbackResponse struct { type CallbackResponse struct {
// The ID of the callback to which this is a response. // The ID of the callback to which this is a response.
@ -208,52 +217,47 @@ type CallbackResponse struct {
URL string `json:"url,omitempty"` URL string `json:"url,omitempty"`
} }
// Venue object represents a venue location with name, address and optional foursquare id. // Venue object represents a venue location with name, address and
// optional foursquare ID.
type Venue struct { type Venue struct {
Location Location `json:"location"` Location Location `json:"location"`
Title string `json:"title"` Title string `json:"title"`
Address string `json:"address"` Address string `json:"address"`
Foursquare_id string `json:"foursquare_id",omitempty` FoursquareID string `json:"foursquare_id,omitempty"`
} }
// MessageEntity // MessageEntity object represents "special" parts of text messages,
// This object represents one special entity in a text message. // including hashtags, usernames, URLs, etc.
// For example, hashtags, usernames, URLs, etc
type MessageEntity struct { type MessageEntity struct {
// Specifies entity type.
Type EntityType `json:"type"`
// type Type of the entity. Can be mention (@username), hashtag, // Offset in UTF-16 code units to the start of the entity.
// bot_command, url, email, bold (bold text), italic (italic text),
// code (monowidth string), pre (monowidth block), text_link (for clickable text URLs),
// text_mention (for users without usernames)
Type string `json:"type"`
// offset Offset in UTF-16 code units to the start of the entity
Offset int `json:"offset"` Offset int `json:"offset"`
//length Length of the entity in UTF-16 code units // Length of the entity in UTF-16 code units.
Length int `json:"length"` Length int `json:"length"`
//url Optional. For “text_link” only, url that will be opened after user taps on the text // (Optional) For EntityTextLink entity type only.
Url string `json:"url",omitempty` //
// URL will be opened after user taps on the text.
URL string `json:"url,omitempty"`
//user Optional. For “text_mention” only, the mentioned user // (Optional) For EntityTMention entity type only.
User User `json:"user",omitempty` User User `json:"user,omitempty"`
} }
// ChatMember , // ChatMember object represents information about a single chat member.
// This struct contains information about one member of the chat.
type ChatMember struct { type ChatMember struct {
User User `json:"user"` User User `json:"user"`
Status string `json:"status"` Status string `json:"status"`
} }
// UserProfilePhotos , // UserProfilePhotos object represent a user's profile pictures.
// This struct represent a user's profile pictures.
//
// Count : Total number of profile pictures the target user has
//
// Photos : Array of Array of PhotoSize , Requested profile pictures (in up to 4 sizes each)
type UserProfilePhotos struct { type UserProfilePhotos struct {
// Total number of profile pictures the target user has.
Count int `json:"total_count"` Count int `json:"total_count"`
// Requested profile pictures (in up to 4 sizes each).
Photos [][]Photo `json:"photos"` Photos [][]Photo `json:"photos"`
} }

Loading…
Cancel
Save