telegram

package module
v0.0.0-...-9717319 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2020 License: MIT Imports: 11 Imported by: 7

README

telegram

telegram is a Go package to help writing Telegram bots

installation

go get -u github.com/igungor/telegram

usage

Documentation

Also look at echobot

license

MIT. See LICENSE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Audio

type Audio struct {
	File

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

	// Performer of the audio as defined by sender or by audio tags
	Performer string `json:"performer,omitempty"`

	// Title of the audio as defined by sender or by audio tags
	Title string `json:"title,omitempty"`

	// MIME type of the file as defined by sender
	MimeType string `json:"mime_type,omitempty"`
	Caption  string `json:"-"`
}

Audio represents an audio file to be treated as music by Telegram clients.

type Bot

type Bot struct {
	// contains filtered or unexported fields
}

Bot represent a Telegram bot.

func New

func New(token string) *Bot

New creates a new Telegram bot with the given token, which is given by Botfather. See https://core.telegram.org/bots#botfather

func (*Bot) GetFile

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

GetFile retrieves basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.

func (*Bot) Handler

func (b *Bot) Handler() http.HandlerFunc

func (*Bot) Messages

func (b *Bot) Messages() <-chan *Message

func (*Bot) SendAudio

func (b *Bot) SendAudio(recipient int64, audio Audio, opts ...SendOption) (Message, error)

SendAudio sends audio files, if you want Telegram clients to display them in the music player. audio must be in the .mp3 format and must not exceed 50 MB in size.

func (*Bot) SendChatAction

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

SendChatAction broadcasts type of action to recipient, such as `typing`, `uploading a photo` etc.

Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).

Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use SendChatAction with action = UploadingPhoto. The user will see a “sending photo” status for the bot.

func (*Bot) SendLocation

func (b *Bot) SendLocation(recipient int64, location Location, opts ...SendOption) (Message, error)

SendLocation sends location point on the map.

func (*Bot) SendMessage

func (b *Bot) SendMessage(recipient int64, message string, opts ...SendOption) (Message, error)

SendMessage sends text message to the recipient.

func (*Bot) SendPhoto

func (b *Bot) SendPhoto(recipient int64, photo Photo, opts ...SendOption) (Message, error)

SendPhoto sends given photo to recipient. Only remote URLs are supported for now. A trivial example is:

b := bot.New("your-token-here")
photo := bot.Photo{URL: "http://i.imgur.com/6S9naG6.png"}
b.SendPhoto(recipient, photo, "sample image")

func (*Bot) SendVenue

func (b *Bot) SendVenue(recipient int64, venue Venue, opts ...SendOption) (Message, error)

SendVenue sends information about a venue.

func (*Bot) SetWebhook

func (b *Bot) SetWebhook(webhook string) error

SetWebhook assigns bot's webhook URL with the given URL.

type Chat

type Chat struct {
	// Unique identifier for this chat. This number may be greater than 32 bits and
	// some programming languages may have difficulty/silent defects in
	// interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer
	// or double-precision float type are safe for storing this identifier.
	ID int64 `json:"id"`

	// Type of chat, can be either “private”, “group”, “supergroup” or “channel”
	Type string `json:"type"`

	// Title, for supergroups, channels and group chats
	Title string `json:"title"`

	// Username, for private chats, supergroups and channels if available
	Username string `json:"username"`

	// First name of the other party in a private chat
	FirstName string `json:"first_name"`

	// Last name of the other party in a private chat
	LastName string `json:"last_name"`
}

Chat represents a Telegram chat.

func (Chat) IsGroupChat

func (c Chat) IsGroupChat() bool

IsGroupChat reports whether the message is originally sent from a chat group.

type ChatAction

type ChatAction string

ChatAction represents bot activity.

const (
	Typing             ChatAction = "typing"
	UploadingPhoto     ChatAction = "upload_photo"
	UploadingVideo     ChatAction = "upload_video"
	UploadingAudio     ChatAction = "upload_audio"
	UploadingDocument  ChatAction = "upload_document"
	FindingLocation    ChatAction = "find_location"
	UploadingVideoNote ChatAction = "upload_video_note"
)

Types of actions to broadcast

type Contact

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

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

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

	// Contact's user identifier in Telegram
	UserID int64 `json:"user_id,omitempty"`
}

Contact represents a phone contact.

type Document

type Document struct {
	File

	// Document thumbnail as defined by sender
	Thumbnail Photo `json:"thumb,omitempty"`

	// Original filename as defined by sender
	Filename string `json:"file_name,omitempty"`

	// MIME type of the file as defined by sender
	MimeType string `json:"mime_type,omitempty"`
}

Document represents a general file (as opposed to photos and audio files).

type File

type File struct {
	// Unique identifier for this file
	FileID string `json:"file_id"`

	// File size, if known
	FileSize int `json:"file_size,omitempty"`

	// File path.
	FilePath string `json:"file_path,omitempty"`

	Name string    `json:"-"`
	Body io.Reader `json:"-"`
	URL  string    `json:"-"`
}

File represents a file ready to be downloaded. The file can be downloaded via the GetFile method. The URL of the file is available from URL field of the File. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling GetFile.

func (File) Exists

func (f File) Exists() bool

Exists reports whether the file is already at Telegram servers.

type Location

type Location struct {
	// Longitude as defined by sender
	Long float64 `json:"longitude"`

	// Latitude as defined by sender
	Lat float64 `json:"latitude"`
}

Location represents a point on the map.

type Message

type Message struct {
	// Unique message identifier
	ID int64 `json:"message_id"`

	// Sender (optional. can be empty for messages sent to channel)
	From User `json:"from,omitempty"`

	// Date is when the message was sent in Unix time
	Unixtime int64 `json:"date"`

	// Conversation the message belongs to — user in case of a private chat,
	// group in case of a group chat
	Chat Chat `json:"chat"`

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

	// For messages forwarded from a channel, information about the original channel
	ForwardFromChat Chat `json:"forward_from_chat,omitempty"`

	// For forwarded messages, date the original message was sent in
	// Unix time
	ForwardDate int64 `json:"forward_date,omitempty"`

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

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

	// For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
	Entities []MessageEntity `json:"entities,omitempty"`

	// Message is an audio file, information about the file
	Audio Audio `json:"audio,omitempty"`

	// Message is a general file, information about the file
	Document Document `json:"document,omitempty"`

	// Message is a photo, available sizes of the photo
	Photos []Photo `json:"photo,omitempty"`

	// Message is a sticker, information about the sticker
	Sticker Sticker `json:"sticker,omitempty"`

	// Message is a video, information about the video
	Video Video `json:"video,omitempty"`

	// Message is a voice message, information about the file
	Voice Voice `json:"voice,omitempty"`

	// Message is a video note, information about the video message
	VideoNote VideoNote `json:"video_note,omitempty"`

	// New members that were added to the group or supergroup and information about
	// them (the bot itself may be one of these members)
	NewChatMembers []User `json:"new_chat_members,omitempty"`

	// Caption for the document, photo or video, 0-200 characters
	Caption string `json:"caption,omitempty"`

	// Message is a shared contact, information about the contact
	Contact Contact `json:"contact,omitempty"`

	// Message is a shared location, information about the location
	Location Location `json:"location,omitempty"`

	// Message is a venue, information about the venue
	Venue Venue `json:"venue,omitempty"`

	// A new member was added to the group, information about them
	// (this member may be bot itself)
	JoinedUser User `json:"new_chat_member,omitempty"`

	// A member was removed from the group, information about them
	// (this member may be bot itself)
	LeftUser User `json:"left_chat_member,omitempty"`

	// A group title was changed to this value
	NewChatTitle string `json:"new_chat_title,omitempty"`

	// A group photo was change to this value
	NewChatPhoto []Photo `json:"new_chat_photo,omitempty"`

	// Informs that the group photo was deleted
	ChatPhotoDeleted bool `json:"delete_chat_photo,omitempty"`

	// Informs that the group has been created
	GroupChatCreated bool `json:"group_chat_created,omitempty"`
}

Message represents a message to be sent.

func (Message) Args

func (m Message) Args() []string

Args returns all words after the first word in the message text. First word is meant to be the command name and can be accessed with Command method.

func (Message) Command

func (m Message) Command() string

Command returns the command's name: the first word in the message text. If message text starts with a `/`, function returns the command name, or else empty string.

func (Message) IsReply

func (m Message) IsReply() bool

IsReply reports whether the message is a reply to another message.

func (Message) IsService

func (m Message) IsService() bool

IsService reports whether the message is a Telegram service message, not a user sent message.

func (Message) String

func (m Message) String() string

String returns a human-readable representation of Message.

func (Message) Time

func (m Message) Time() time.Time

Time returns the moment of message in UTC time.

type MessageEntity

type MessageEntity struct {
	// Type of the entity. Can be mention (@username), hashtag, 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 in UTF-16 code units to the start of the entity
	// TODO(ig):
	Offset int `json:"offset"`

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

	// For “text_link” only, url that will be opened after user taps on the text
	URL string `json:"url,omitempty"`

	// For “text_mention” only, the mentioned user
	User User `json:"user,omitempty"`
}

MessageEntity represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

type ParseMode

type ParseMode string

ParseMode determines the markup of the text of the message.

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

Parse modes

type Photo

type Photo struct {
	File

	// Photo width
	Width int `json:"width"`

	// Photo height
	Height int `json:"height"`

	Caption string `json:"-"`
}

Photo represents one size of a photo or a file/sticker thumbnail.

type ReplyMarkup

type ReplyMarkup struct {
	// Array of button rows, each represented by an strings
	Keyboard [][]string `json:"keyboard"`

	// Optional. Requests clients to resize the keyboard vertically for optimal
	// fit (e.g., make the keyboard smaller if there are just two rows of
	// buttons).
	Resize bool `json:"resize_keyboard,omitempty"`

	// Optional. Requests clients to hide the keyboard as soon as it's been used.
	// The keyboard will still be available, but clients will automatically display
	// the usual letter-keyboard in the chat – the user can press a special button
	// in the input field to see the custom keyboard again.
	OneTime bool `json:"one_time_keyboard,omitempty"`

	// Optional. Use this parameter if you want to show the keyboard to 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, sender of the original message.
	Selective bool `json:"selective,omitempty"`
}

ReplyMarkup represents a custom keyboard with reply options.

type SendOption

type SendOption func(*sendOptions)

SendOption configures how we configure the message to be sent.

func WithDisableNotification

func WithDisableNotification(disable bool) SendOption

WithDisableNotification sends the message silently. Users will receive a notification with no sound.

func WithDisableWebPagePreview

func WithDisableWebPagePreview(disable bool) SendOption

WithDisableWebPagePreview returns a SendOption which disables webpage previews if the message contains a link.

func WithParseMode

func WithParseMode(mode ParseMode) SendOption

WithParseMode returns a SendOption which sets the message format, such as HTML, Markdown etc.

func WithReplyMarkup

func WithReplyMarkup(markup ReplyMarkup) SendOption

WithReplyMarkup returns a SendOption which configures a custom keyboard for the sent message.

func WithReplyTo

func WithReplyTo(to int64) SendOption

WithReplyTo returns a SendOption which sets the message to be replied to.

type Sticker

type Sticker struct {
	File

	// Sticker width
	Width int `json:"width"`

	// Sticker height
	Height int `json:"height"`

	// Sticker thumbnail in .webp or .jpg format
	Thumbnail Photo `json:"thumb,omitempty"`

	// Emoji associated with the sticker
	Emoji string `json:"emoji,omitempty"`
}

Sticker represents a sticker.

type Update

type Update struct {
	// The update‘s unique identifier. Update identifiers start from a certain
	// positive number and increase sequentially. This ID becomes especially handy
	// if you’re using Webhooks, since it allows you to ignore repeated updates or
	// to restore the correct update sequence, should they get out of order.
	ID int64 `json:"update_id"`

	// New incoming message of any kind — text, photo, sticker, etc.
	Message Message `json:"message,omitempty"`

	// New version of a message that is known to the bot and was edited
	EditedMessage Message `json:"edited_message,omitempty"`
}

type User

type User struct {
	// Unique identifier for this user or bot
	ID int64 `json:"id"`

	// User‘s or bot’s first name
	Username string `json:"username"`

	// User‘s or bot’s last name
	FirstName string `json:"first_name"`

	// User‘s or bot’s username
	LastName string `json:"last_name"`

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

User represents a Telegram user or bot.

type Venue

type Venue struct {
	// Venue location
	Location Location `json:"location"`

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

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

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

Venue represents a venue

type Video

type Video struct {
	File

	// Video width as defined by sender
	Width int `json:"width"`

	// Video height as defined by sender
	Height int `json:"height"`

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

	// Video thumbnail
	Thumbnail Photo `json:"thumb,omitempty"`

	// Mime type of a file as defined by sender
	MimeType string `json:"mime_type,omitempty"`

	Caption string `json:"-"`
}

Video represents a video file.

type VideoNote

type VideoNote struct {
	File

	// Video width and height as defined by sender
	Length int `json:"length"`

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

	// Video thumbnail
	Thumbnail Photo `json:"thumb"`
}

VideoNote represents a video message.

type Voice

type Voice struct {
	File

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

	// MIME type of the file as defined by sender
	MimeType string `json:"mime_type,omitempty"`
}

Voice represents an voice note.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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