telegram

package module
v0.10.11 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2022 License: MIT Imports: 19 Imported by: 5

README

telegram-bot-api

telegram-bot-api is a Telegram Bot API client and bot implementation.

Disclaimer

Not all API methods, options and types are implemented at the moment. Godoc is also pretty poor, I am working on it. Test coverage is absent (haha, classic). API is more or less stable in the root package, ext subpackage is to be refactored heavily and is mainly for my personal use at the moment.

Installation

Simply install the package via go get:

go get -u github.com/jfk9w-go/telegram-bot-api

Example

package main

import (
	"context"
	"os"

	"github.com/jfk9w-go/flu"
	"github.com/jfk9w-go/flu/syncf"
	"github.com/jfk9w-go/telegram-bot-api"
)

type Handler struct{}

func (h Handler) Ping(ctx context.Context, client telegram.Client, cmd *telegram.Command) error {
	return cmd.Reply(ctx, client, "pong")
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	
	// read token from command line arguments
	token := os.Args[1]

	// instantiate Handler
	// available commands will be resolved automatically by reflection
	// you can also simply create a CommandRegistry and fill it manually
	var handler Handler
	
	bot := telegram.
		// create bot instance
		NewBot(syncf.DefaultClock, nil, token).
		// start command listener
		CommandListener(handler)

	defer flu.CloseQuietly(bot)

	// wait for signal
	syncf.AwaitSignal(ctx)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultMediaType   = Document
	MIMEType2MediaType = map[string]MediaType{
		"image/jpeg":               Photo,
		"image/png":                Photo,
		"image/bmp":                Photo,
		"image/gif":                Animation,
		"video/mp4":                Video,
		"application/pdf":          Document,
		"application/octet-stream": Document,
		"audio/mpeg":               Audio,
		"audio/ogg":                Voice,
		"image/webp":               Sticker,
	}
)
View Source
var DefaultCommandsOptions = &GetUpdatesOptions{
	TimeoutSecs:    60,
	AllowedUpdates: []string{"message", "edited_message", "callback_query"},
}
View Source
var (
	ErrUnexpectedAnswer = errors.New("unexpected answer")
)
View Source
var GatewaySendDelay = 35 * time.Millisecond

GatewaySendDelay is a delay between two consecutive /send* API calls per bot token.

View Source
var MaxSendRetries = 3
View Source
var SendDelays = map[ChatType]time.Duration{
	PrivateChat: 35 * time.Millisecond,
	GroupChat:   3 * time.Second,
	Supergroup:  time.Second,
	Channel:     3 * time.Second,
}

SendDelays are delays between two consecutive /send* API calls per chat with a given type.

ValidStatusCodes is a slice of valid API HTTP status codes.

Functions

This section is empty.

Types

type AnswerOptions

type AnswerOptions struct {
	Text      string `url:"text,omitempty"`
	ShowAlert bool   `url:"show_alert,omitempty"`
	URL       string `url:"url,omitempty"`
	CacheTime int    `url:"cache_time,omitempty"`
}

type Bot

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

func NewBot

func NewBot(clock syncf.Clock, client httpf.Client, token string) *Bot

func (Bot) Answer added in v0.10.5

func (a Bot) Answer(ctx context.Context, message *Message) error

func (Bot) AnswerCallbackQuery added in v0.10.5

func (c Bot) AnswerCallbackQuery(ctx context.Context, id string, options *AnswerOptions) error

AnswerCallbackQuery is used to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. https://core.telegram.org/bots/api#answercallbackquery

func (Bot) Ask added in v0.10.5

func (a Bot) Ask(ctx context.Context, chatID ChatID, sendable Sendable, options *SendOptions) (*Message, error)

func (*Bot) Close

func (b *Bot) Close() error

func (*Bot) CommandListener

func (b *Bot) CommandListener(value interface{}) *Bot

func (*Bot) CommandListenerFunc

func (b *Bot) CommandListenerFunc(fun CommandListenerFunc) *Bot

func (*Bot) Commands

func (b *Bot) Commands() <-chan *Command

func (Bot) CopyMessage added in v0.10.5

func (c Bot) CopyMessage(ctx context.Context, chatID ChatID, ref MessageRef, options *CopyOptions) (ID, error)

func (Bot) DeleteMessage added in v0.10.5

func (c Bot) DeleteMessage(ctx context.Context, ref MessageRef) error

DeleteMessage is used to delete a message, including service messages, with the following limitations: - A message can only be deleted if it was sent less than 48 hours ago. - Bots can delete outgoing messages in private chats, groups, and supergroups. - Bots granted can_post_messages permissions can delete outgoing messages in channels. - If the bot is an administrator of a group, it can delete any message there. - If the bot has can_delete_messages permission in a supergroup or a updateChannel, it can delete any message there. Returns True on success. See

https://core.telegram.org/bots/api#deletemessage

func (Bot) DeleteMyCommands added in v0.10.5

func (c Bot) DeleteMyCommands(ctx context.Context, scope *BotCommandScope) error

func (Bot) EditMessageReplyMarkup added in v0.10.5

func (c Bot) EditMessageReplyMarkup(ctx context.Context, ref MessageRef, markup ReplyMarkup) (*Message, error)

func (Bot) Execute added in v0.10.5

func (c Bot) Execute(ctx context.Context, method string, body flu.EncoderTo, resp interface{}) error
func (c Bot) ExportChatInviteLink(ctx context.Context, chatID ChatID) (string, error)

func (Bot) ForwardMessage added in v0.10.5

func (c Bot) ForwardMessage(ctx context.Context, chatID ChatID, ref MessageRef, options *SendOptions) (ID, error)

func (Bot) GetChat added in v0.10.5

func (c Bot) GetChat(ctx context.Context, chatID ChatID) (*Chat, error)

GetChat is used to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or updateChannel, etc.). Returns a Chat object on success. See https://core.telegram.org/bots/api#getchat

func (Bot) GetChatAdministrators added in v0.10.5

func (c Bot) GetChatAdministrators(ctx context.Context, chatID ChatID) ([]ChatMember, error)

GetChatAdministrators is used to get a 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. See https://core.telegram.org/bots/api#getchatadministrators

func (Bot) GetChatMember added in v0.10.5

func (c Bot) GetChatMember(ctx context.Context, chatID ChatID, userID ID) (*ChatMember, error)

GetChatMember is used to get information about a member of a chat. Returns a ChatMember object on success. See https://core.telegram.org/bots/api#getchatmember

func (Bot) GetChatMemberCount added in v0.10.5

func (c Bot) GetChatMemberCount(ctx context.Context, chatID ChatID) (int64, error)

func (Bot) GetMe added in v0.10.5

func (c Bot) GetMe(ctx context.Context) (*User, error)

GetMe is a simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object. See https://core.telegram.org/bots/api#getme

func (Bot) GetMyCommands added in v0.10.5

func (c Bot) GetMyCommands(ctx context.Context, scope *BotCommandScope) ([]BotCommand, error)

func (Bot) GetUpdates added in v0.10.5

func (c Bot) GetUpdates(ctx context.Context, options GetUpdatesOptions) ([]Update, error)

GetUpdates is used to receive incoming updates using long polling. An Array of Update objects is returned. See https://core.telegram.org/bots/api#getupdates

func (*Bot) HandleCommand

func (b *Bot) HandleCommand(ctx context.Context, listener CommandListener, cmd *Command) error

func (*Bot) Listen

func (b *Bot) Listen(options GetUpdatesOptions) <-chan Update

func (Bot) Send added in v0.10.5

func (c Bot) Send(ctx context.Context, chatID ChatID, item Sendable, options *SendOptions) (*Message, error)

Send is an umbrella method for various /send* API calls which return only one Message. See

https://core.telegram.org/bots/api#sendmessage
https://core.telegram.org/bots/api#sendphoto
https://core.telegram.org/bots/api#sendvideo
https://core.telegram.org/bots/api#senddocument
https://core.telegram.org/bots/api#sendaudio
https://core.telegram.org/bots/api#sendvoice
https://core.telegram.org/bots/api#sendsticker

func (Bot) SendChatAction added in v0.10.10

func (c Bot) SendChatAction(ctx context.Context, chatID ChatID, action string) error

func (Bot) SendMediaGroup added in v0.10.5

func (c Bot) SendMediaGroup(ctx context.Context, chatID ChatID, media []Media, options *SendOptions) ([]Message, error)

SendMediaGroup is used to send a group of photos or videos as an album. On success, an array of Message's is returned. See https://core.telegram.org/bots/api#sendmediagroup

func (Bot) SetMyCommands added in v0.10.5

func (c Bot) SetMyCommands(ctx context.Context, scope *BotCommandScope, commands []BotCommand) error

func (*Bot) String added in v0.10.5

func (b *Bot) String() string

func (*Bot) Username

func (b *Bot) Username() Username

type BotCommand

type BotCommand struct {
	Command     string `json:"command"`
	Description string `json:"description"`
}

type BotCommandScope

type BotCommandScope struct {
	Type   BotCommandScopeType `json:"type"`
	ChatID ChatID              `json:"chat_id,omitempty"`
	UserID ID                  `json:"user_id,omitempty"`
}

type BotCommandScopeType

type BotCommandScopeType string
const (
	BotCommandScopeDefault               BotCommandScopeType = "default"
	BotCommandScopeAllPrivateChats       BotCommandScopeType = "all_private_chats"
	BotCommandScopeAllGroupChats         BotCommandScopeType = "all_group_chats"
	BotCommandScopeAllChatAdministrators BotCommandScopeType = "all_chat_administrators"
	BotCommandScopeChat                  BotCommandScopeType = "chat"
	BotCommandScopeChatAdministrators    BotCommandScopeType = "chat_administrators"
	BotCommandScopeChatMember            BotCommandScopeType = "chat_member"
)

type Button

type Button [3]string

func (Button) StartCallbackURL

func (b Button) StartCallbackURL(username string) string

type CallbackQuery

type CallbackQuery struct {
	ID              string   `json:"id"`
	From            User     `json:"from"`
	Message         *Message `json:"message"`
	InlineMessageID *string  `json:"inline_message_id"`
	ChatInstance    *string  `json:"chat_instance"`
	Data            *string  `json:"data"`
	GameShortName   *string  `json:"game_short_name"`
}

CallbackQuery (https://core.telegram.org/bots/api#callbackquery)

type Chat

type Chat struct {
	ID                          ID        `json:"id"`
	Type                        ChatType  `json:"type"`
	Title                       string    `json:"title"`
	Username                    *Username `json:"username"`
	FirstName                   string    `json:"first_name"`
	LastName                    string    `json:"last_name"`
	AllMembersAreAdministrators bool      `json:"all_members_are_administrators"`
	InviteLink                  string    `json:"invite_link"`
}

Chat (https://core.telegram.org/bots/api#chat)

type ChatID

type ChatID interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

ChatID is either an ID or channel Username in various API calls.

type ChatMember

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

ChatMember (https://core.telegram.org/bots/api#chatmember)

type ChatType

type ChatType string

ChatType can be either “private”, “group”, “supergroup” or “channel”

const (
	PrivateChat ChatType = "private"
	GroupChat   ChatType = "group"
	Supergroup  ChatType = "supergroup"
	Channel     ChatType = "channel"
)

func (ChatType) SendDelay

func (t ChatType) SendDelay() time.Duration

type Client

type Client interface {
	GetMe(ctx context.Context) (*User, error)
	ForwardMessage(ctx context.Context, chatID ChatID, ref MessageRef, options *SendOptions) (ID, error)
	CopyMessage(ctx context.Context, chatID ChatID, ref MessageRef, options *CopyOptions) (ID, error)
	DeleteMessage(ctx context.Context, ref MessageRef) error
	EditMessageReplyMarkup(ctx context.Context, ref MessageRef, markup ReplyMarkup) (*Message, error)
	ExportChatInviteLink(ctx context.Context, chatID ChatID) (string, error)
	GetChat(ctx context.Context, chatID ChatID) (*Chat, error)
	GetChatAdministrators(ctx context.Context, chatID ChatID) ([]ChatMember, error)
	GetChatMemberCount(ctx context.Context, chatID ChatID) (int64, error)
	GetChatMember(ctx context.Context, chatID ChatID, userID ID) (*ChatMember, error)
	AnswerCallbackQuery(ctx context.Context, id string, options *AnswerOptions) error
	Send(ctx context.Context, chatID ChatID, item Sendable, options *SendOptions) (*Message, error)
	SendChatAction(ctx context.Context, chatID ChatID, action string) error
	SendMediaGroup(ctx context.Context, chatID ChatID, media []Media, options *SendOptions) ([]Message, error)
	SetMyCommands(ctx context.Context, scope *BotCommandScope, commands []BotCommand) error
	GetMyCommands(ctx context.Context, scope *BotCommandScope) ([]BotCommand, error)
	DeleteMyCommands(ctx context.Context, scope *BotCommandScope) error
	Ask(ctx context.Context, chatID ChatID, sendable Sendable, options *SendOptions) (*Message, error)
	Answer(ctx context.Context, message *Message) error
	Username() Username
}

type Command

type Command struct {
	Chat            *Chat
	User            *User
	Message         *Message
	Key             string
	Payload         string
	Args            []string
	CallbackQueryID string
}

Command is a text bot command.

func (*Command) Arg

func (cmd *Command) Arg(i int) string

func (*Command) Button

func (cmd *Command) Button(text string) Button

func (*Command) Reply

func (cmd *Command) Reply(ctx context.Context, client Client, text string) error

func (*Command) ReplyCallback added in v0.10.9

func (cmd *Command) ReplyCallback(ctx context.Context, client Client, text string) error

func (*Command) Start

func (cmd *Command) Start(ctx context.Context, client Client) error

func (*Command) String

func (cmd *Command) String() string

type CommandListener

type CommandListener interface {
	OnCommand(ctx context.Context, client Client, cmd *Command) error
}

type CommandListenerFunc

type CommandListenerFunc func(context.Context, Client, *Command) error

func (CommandListenerFunc) OnCommand

func (fun CommandListenerFunc) OnCommand(ctx context.Context, client Client, cmd *Command) error

type CommandRegistry

type CommandRegistry map[string]CommandListener

func (CommandRegistry) Add

func (CommandRegistry) AddFunc

func (r CommandRegistry) AddFunc(key string, listener CommandListenerFunc) CommandRegistry

func (CommandRegistry) From added in v0.10.5

func (r CommandRegistry) From(v any) error

func (CommandRegistry) OnCommand

func (r CommandRegistry) OnCommand(ctx context.Context, client Client, cmd *Command) error

type CopyOptions

type CopyOptions struct {
	*SendOptions
	Caption   string    `url:"caption,omitempty"`
	ParseMode ParseMode `url:"parse_mode,omitempty"`
}

type Error

type Error struct {
	// ErrorCode is an integer error code.
	ErrorCode int
	// Description explains the error.
	Description string
}

Error is an error returned by Telegram Bot API. See https://core.telegram.org/bots/api#making-requests

func (Error) Error

func (e Error) Error() string

type ForceReply

type ForceReply struct {
	ForceReply bool `json:"force_reply,omitempty"`
	Selective  bool `json:"selective,omitempty"`
}

type GetUpdatesOptions

type GetUpdatesOptions struct {
	// Identifier of the first update to be returned.
	// Must be greater by one than the highest among the identifiers of previously received updates.
	// By default, updates starting with the earliest unconfirmed update are returned.
	// An update is considered confirmed as soon as getUpdates is called with an offset
	// higher than its update_id. The negative offset can be specified to retrieve updates
	// starting from -offset update from the end of the updates queue.
	// All previous updates will be forgotten.
	Offset ID `json:"offset,omitempty"`
	// Limits the number of updates to be retrieved.
	// Values between 1—100 are accepted. Defaults to 100.
	Limit int `json:"limit,omitempty"`
	// Timeout for long polling.
	TimeoutSecs int `json:"timeout,omitempty"`
	// List the types of updates you want your bot to receive.
	AllowedUpdates []string `json:"allowed_updates,omitempty"`
}

GetUpdatesOptions is /getUpdates request options. See https://core.telegram.org/bots/api#getupdates

type ID

type ID int64

ID is an item identifier (chat, message, user, etc.)

func MustParseID

func MustParseID(value string) ID

MustParseID does what ParseID does, except on error it panics.

func ParseID

func ParseID(value string) (ID, error)

ParseID tries to parse a value as ID.

func (ID) Increment

func (id ID) Increment() ID

Increment increments the new ID value equal to the old one incremented by one.

func (ID) String

func (id ID) String() string

type InlineKeyboardButton

type InlineKeyboardButton struct {
	Text                         string `json:"text"`
	URL                          string `json:"url,omitempty"`
	CallbackData                 string `json:"callback_data,omitempty"`
	SwitchInlineQuery            string `json:"switch_inline_query,omitempty"`
	SwitchInlineQueryCurrentChat string `json:"switch_inline_query_current_chat,omitempty"`
}

InlineKeyboardButton (https://core.telegram.org/bots/api#inlinekeyboardbutton)

type InlineKeyboardMarkup

type InlineKeyboardMarkup struct {
	InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
}

InlineKeyboardMarkup (https://core.telegram.org/bots/api#inlinekeyboardmarkup)

type Media

type Media struct {
	Type      MediaType `url:"-" json:"type"`
	Input     flu.Input `url:"-" json:"-"`
	Filename  string    `url:"-" json:"-"`
	Caption   string    `url:"caption,omitempty" json:"caption,omitempty"`
	ParseMode ParseMode `url:"parse_mode,omitempty" json:"parse_mode,omitempty"`
}

type MediaGroup

type MediaGroup []Media

type MediaType

type MediaType string
const (
	Photo     MediaType = "photo"
	Animation MediaType = "animation"
	Video     MediaType = "video"
	Document  MediaType = "document"
	Audio     MediaType = "audio"
	Sticker   MediaType = "sticker"
	Voice     MediaType = "voice"
)

func MediaTypeByMIMEType

func MediaTypeByMIMEType(mimeType string) MediaType

func (MediaType) AttachMaxSize

func (mt MediaType) AttachMaxSize() int64

func (MediaType) RemoteMaxSize

func (mt MediaType) RemoteMaxSize() int64

type Message

type Message struct {
	ID             ID              `json:"message_id"`
	From           User            `json:"from"`
	Date           int             `json:"date"`
	Chat           Chat            `json:"chat"`
	Text           string          `json:"text"`
	Entities       []MessageEntity `json:"entities"`
	ReplyToMessage *Message        `json:"reply_to_message"`
	Photo          []MessageFile   `json:"photo"`
	Video          *MessageFile    `json:"video"`
	Animation      *MessageFile    `json:"animation"`
}

Message (https://core.telegram.org/bots/api#message)

func (*Message) Ref

func (m *Message) Ref() MessageRef

type MessageEntity

type MessageEntity struct {
	Type   string `json:"type"`
	Offset int    `json:"offset"`
	Length int    `json:"length"`
	URL    string `json:"url"`
	User   *User  `json:"user"`
}

MessageEntity (https://core.telegram.org/bots/api#messageentity)

type MessageFile

type MessageFile struct {
	ID string `json:"file_id"`
}

type MessageRef

type MessageRef struct {
	ChatID ChatID `url:"from_chat_id"`
	ID     ID     `url:"message_id"`
}

MessageRef is used for message copying and forwarding.

type ParseMode

type ParseMode string

ParseMode is a parse_mode request parameter type.

const (
	// None is used for empty parse_mode.
	None ParseMode = ""
	// Markdown is "Markdown" parse_mode value.
	Markdown ParseMode = "Markdown"
	// HTML is "HTML" parse_mode value.
	HTML ParseMode = "HTML"

	// MaxMessageSize is maximum message character length.
	MaxMessageSize = 4096
	// MaxCaptionSize is maximum caption character length.
	MaxCaptionSize = 1024
)

type Question

type Question chan *Message

type ReplyMarkup

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

func InlineKeyboard

func InlineKeyboard(rows ...[]Button) ReplyMarkup

type SendOptions

type SendOptions struct {
	DisableNotification bool
	ReplyToMessageID    ID
	ReplyMarkup         ReplyMarkup
}

type Sendable

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

type Sender

type Sender interface {
	Send(ctx context.Context, chatID ChatID, sendable Sendable, options *SendOptions) (*Message, error)
}

type Text

type Text struct {
	Text                  string    `url:"text"`
	ParseMode             ParseMode `url:"parse_mode,omitempty"`
	DisableWebPagePreview bool      `url:"disable_web_page_preview,omitempty"`
}

type TooManyMessages

type TooManyMessages struct {
	RetryAfter time.Duration
}

TooManyMessages is returned in case of exceeding flood control.

func (TooManyMessages) Error

func (e TooManyMessages) Error() string

type Update

type Update struct {
	ID                ID             `json:"update_id"`
	Message           *Message       `json:"message"`
	EditedMessage     *Message       `json:"edited_message"`
	ChannelPost       *Message       `json:"channel_post"`
	EditedChannelPost *Message       `json:"edited_message_post"`
	CallbackQuery     *CallbackQuery `json:"callback_query"`
}

Update (https://core.telegram.org/bots/api#update)

type User

type User struct {
	ID        ID        `json:"id"`
	IsBot     bool      `json:"is_bot"`
	FirstName string    `json:"first_name"`
	LastName  string    `json:"last_name"`
	Username  *Username `json:"username"`
}

User (https://core.telegram.org/bots/api#user)

type Username

type Username string

Username represents a Telegram username.

func (Username) String

func (username Username) String() string

Directories

Path Synopsis
ext

Jump to

Keyboard shortcuts

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