telebot

package
v0.0.0-...-31a6de3 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2015 License: MIT, Apache-2.0 Imports: 12 Imported by: 0

README

Telebot

Telebot is a convenient wrapper to Telegram Bots API, written in Golang.

GoDoc

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 care about networking at all. Here is an example "helloworld" bot, written with telebot:

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)
        }
    }
}

You can also send any kind of resources from file system easily:

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

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

Sometimes you might want to send a little bit complicated messages, with some optional parameters:

// Send a selective force reply message.
bot.SendMessage(user, "pong", &telebot.SendOptions{
        ForceReply: telebot.ForceReply{
            Require: true,
            Selective: true,
        },
    },
)

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 (
	Typing            = "typing"
	UploadingPhoto    = "upload_photo"
	UploadingVideo    = "upload_video"
	UploadingAudio    = "upload_audio"
	UploadingDocument = "upload_document"
	RecordingVideo    = "record_video"
	RecordingAudio    = "record_audio"
	FindingLocation   = "find_location"
)

A bunch of available chat actions.

Variables

This section is empty.

Functions

This section is empty.

Types

type Audio

type Audio struct {
	File

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

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

Audio object represents an audio file (voice note).

type AuthError

type AuthError struct {
	Payload string
}

AuthError occurs if the token appears to be invalid.

func (AuthError) Error

func (e AuthError) Error() string

type Bot

type Bot struct {
	Token string

	// Bot as `User` on API level.
	Identity User
}

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) ForwardMessage

func (b Bot) ForwardMessage(recipient User, message Message) error

ForwardMessage forwards a message to recipient.

func (Bot) Listen

func (b Bot) Listen(subscription chan<- Message, interval time.Duration)

Listen periodically looks for updates and delivers new messages to subscription channel.

func (Bot) SendAudio

func (b Bot) SendAudio(recipient User, 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 User, action string) 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 User, 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 User, 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 User, message string, options *SendOptions) error

SendMessage sends a text message to recipient.

func (Bot) SendPhoto

func (b Bot) SendPhoto(recipient User, 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 User, 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) SendVideo

func (b Bot) SendVideo(recipient User, 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.

type Contact

type Contact struct {
	PhoneNumber string `json:"phone_number"`
	FirstName   string `json:"first_name"`
	LastName    string `json:"last_name"`

	// Contact's username in Telegram (might be empty).
	Username string `json:"user_id"`
}

Contact object represents a contact to Telegram user

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 FetchError

type FetchError struct {
	Payload string
}

FetchError occurs when something goes wrong while fetching updates.

func (FetchError) Error

func (e FetchError) Error() string

type File

type File struct {
	FileID   string `json:"file_id"`
	FileSize int    `json:"file_size"`
	// 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 FileError

type FileError struct {
	Payload string
}

FileError occurs when local file can't be read.

func (FileError) Error

func (e FileError) Error() string

type ForceReply

type ForceReply struct {
	// Enable if intended.
	Require bool `json:"force_reply"`

	// 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"`
}

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").

type Location

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

Location object represents geographic position.

type Message

type Message struct {
	ID       int  `json:"message_id"`
	Sender   User `json:"from"`
	Unixtime int  `json:"date"`

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

	// 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 User `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_participant"`

	// 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_participant"`

	// 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"`
}

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 Photo

type Photo struct {
	Thumbnail

	Caption string
}

Photo object represents a photo with caption.

type SendError

type SendError struct {
	Payload string
}

SendError occurs when something goes wrong while posting images, documents, etc.

func (SendError) Error

func (e SendError) Error() string

type SendOptions

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

	// See ForceReply struct definition.
	ForceReply ForceReply

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

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 a image/sticker of particular size.

type Update

type Update struct {
	ID      int     `json:"update_id"`
	Payload Message `json:"message"`
}

Update object represents an incoming update.

type User

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

	Title string `json:"title"`
}

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

Title field differs a group chat apart from users and bots: object represents a group chat if Title is empty.

func (User) IsGroupChat

func (u User) IsGroupChat() bool

IsGroupChat returns true if user object represents a group chat.

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