tgkit

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInternalServerErrorResponse = errors.New("got internal server error response from Telegram API")

ErrInternalServerErrorResponse is an error indicating Telegram API responded with a code >= 500.

Functions

This section is empty.

Types

type Bot

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

Bot is a telegram bot model.

func MustNewBot added in v1.0.0

func MustNewBot(identity string) Bot

MustNewBot creates new Bot and panics on failure.

func NewBot

func NewBot(identity string) (Bot, error)

NewBot receives a string of the bot identity ("<botID>:<botToken>") and returns the new Bot instance. Returns an error if given identity is not in valid format.

Examples of the identity strings: - `bot12345:botToken1` - `54321:botToken2`

func (Bot) GetID

func (b Bot) GetID() BotID

GetID returns a Bot ID number.

func (Bot) GetIdentity

func (b Bot) GetIdentity() BotIdentity

GetIdentity returns a Bot identity string to pass it to the API.

func (Bot) GetToken

func (b Bot) GetToken() BotToken

GetToken returns a Bot token string.

func (Bot) String

func (b Bot) String() string

String returns a Bot identity with a masked token for the debug purposes.

type BotID

type BotID uint64

BotID is a Bot ID number.

func (BotID) String

func (id BotID) String() string

type BotIdentity

type BotIdentity string

BotIdentity is a Bot identity string.

func (BotIdentity) String

func (t BotIdentity) String() string

type BotToken

type BotToken string

BotToken is a Bot token string.

func (BotToken) String

func (t BotToken) String() string

type ChatID

type ChatID string

ChatID is a telegram chat ID/username.

func (ChatID) String

func (id ChatID) String() string

type Client

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

Client is a tool to communicate with a Telegram API via the HTTPS.

func NewClientWithOptions added in v0.7.0

func NewClientWithOptions(options ...ClientOption) *Client

NewClientWithOptions creates new Client instance with a construction options.

func NewDefaultClient

func NewDefaultClient() *Client

NewDefaultClient creates a new default telegram Client instance.

func (*Client) Get

func (c *Client) Get(bot Bot, method string, target any) error

Get sends a GET request to the Telegram API. The successful response is decoded into the target.

func (*Client) GetMe

func (c *Client) GetMe(bot Bot) (TgUser, error)

GetMe returns information about the Bot in the TgUser format. See: https://core.telegram.org/bots/api#getme

func (*Client) GetUpdates added in v1.0.0

func (c *Client) GetUpdates(bot Bot) ([]TgUpdate, error)

GetUpdates returns last bot's updates. See https://core.telegram.org/bots/api#getupdates TODO: pass parameters.

func (*Client) Post

func (c *Client) Post(bot Bot, method string, reqData any, target any) error

Post sends a POST request to the Telegram API. The successful response is decoded into the target.

func (*Client) SendMessage

func (c *Client) SendMessage(bot Bot, msg TgMessageRequest) (TgMessage, error)

SendMessage sends a message from the bot via the Telegram API. See: https://core.telegram.org/bots/api#sendmessage

type ClientOption added in v0.7.0

type ClientOption func(*Client)

ClientOption is a client constructor configuration option.

func WithHTTPClient added in v0.7.0

func WithHTTPClient(httpClient HTTPClient) ClientOption

WithHTTPClient defines an HTTPClient instance to use with a Client.

func WithRetrier added in v0.7.0

func WithRetrier(retrier RequestRetrier) ClientOption

WithRetrier defines a way or requests retries using the RequestRetrier instance.

type HTTPClient added in v0.0.6

type HTTPClient interface {
	Get(url string) (resp *http.Response, err error)
	Post(url, contentType string, body io.Reader) (resp *http.Response, err error)
}

HTTPClient is an HTTP client interface; the http.Client fits.

type HTTPClientJSONMock added in v0.0.6

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

HTTPClientJSONMock is a test client returning the predefined response.

func (*HTTPClientJSONMock) Get added in v0.0.6

func (m *HTTPClientJSONMock) Get(url string) (resp *http.Response, err error)

func (*HTTPClientJSONMock) Post added in v0.0.6

func (m *HTTPClientJSONMock) Post(url, _ string, _ io.Reader) (resp *http.Response, err error)

func (*HTTPClientJSONMock) RegisterResponse added in v0.0.6

func (m *HTTPClientJSONMock) RegisterResponse(method string, url string, responseCode int, responseBody any)

RegisterResponse registers response for the url.

type RequestRetrier added in v0.7.0

type RequestRetrier interface {
	Do(reqFn sendRequestFn) (*http.Response, error)
}

RequestRetrier is a tool to retry failed requests.

func NewLinearRetrier added in v0.7.0

func NewLinearRetrier(attempts uint, delay time.Duration) RequestRetrier

NewLinearRetrier returns a RequestRetrier attempting to send request with a fixed delay.

func NewNoopRetrier added in v0.7.0

func NewNoopRetrier() RequestRetrier

NewNoopRetrier returns a RequestRetrier with a single request attempt.

func NewProgressiveRetrier added in v0.7.0

func NewProgressiveRetrier(attempts uint, initialDelay time.Duration, multiplier float64) RequestRetrier

NewProgressiveRetrier returns a RequestRetrier attempting to send request with an increasing delay.

type TgChat added in v1.0.0

type TgChat struct {
	ID        int64  `json:"id"`
	Type      string `json:"type"`
	Title     string `json:"title,omitempty"`
	Username  string `json:"username,omitempty"`
	FirstName string `json:"first_name,omitempty"`
	LastName  string `json:"last_name,omitempty"`
	IsForum   bool   `json:"is_forum,omitempty"`
}

TgChat is a model representing the Telegram API chat object. See: https://core.telegram.org/bots/api#chat

id Integer Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. type String Type of the chat, can be either “private”, “group”, “supergroup” or “channel” title String Optional. Title, for supergroups, channels and group chats username String Optional. Username, for private chats, supergroups and channels if available first_name String Optional. First name of the other party in a private chat last_name String Optional. Last name of the other party in a private chat is_forum True Optional. True, if the supergroup chat is a forum (has topics enabled)

type TgErrorResponse

type TgErrorResponse struct {
	Ok          bool   `json:"ok"`
	ErrorCode   int    `json:"error_code,omitempty"`
	Description string `json:"description,omitempty"`
}

TgErrorResponse is a Telegram response describing the error.

func (TgErrorResponse) Error

func (r TgErrorResponse) Error() string

type TgMessage

type TgMessage struct {
	MessageID       int    `json:"message_id"`
	MessageThreadId int    `json:"message_thread_id,omitempty"`
	Date            uint64 `json:"date"`

	From TgUser `json:"from"`
	Chat TgChat `json:"chat"`
}

TgMessage is a Telegram message model. See https://core.telegram.org/bots/api#message TODO: add a lot of fields :)

type TgMessageRequest

type TgMessageRequest struct {
	ChatID ChatID `json:"chat_id"`
	Text   string `json:"text"`

	BusinessConnectionId string `json:"business_connection_id,omitempty"`
	MessageThreadId      int    `json:"message_thread_id,omitempty"`
	ParseMode            string `json:"parse_mode,omitempty"`

	DisableNotification bool `json:"disable_notification,omitempty"`
	ProtectContent      bool `json:"protect_content,omitempty"`
}

TgMessageRequest is a message request body. See https://core.telegram.org/bots/api#sendmessage TODO: add entities, link_preview_options, reply_parameters and reply_markup fields.

type TgMessageResponse

type TgMessageResponse struct {
	Ok     bool      `json:"ok"`
	Result TgMessage `json:"result"`
}

TgMessageResponse is a Telegram response with a single message result.

type TgUpdate added in v1.0.0

type TgUpdate struct {
	UpdateID int       `json:"update_id"`
	Message  TgMessage `json:"message"`
}

TgUpdate is struct representing the Telegram's Update object. See https://core.telegram.org/bots/api#update TODO: add a lot of fields :)

type TgUpdatesResponse added in v1.0.0

type TgUpdatesResponse struct {
	Ok     bool       `json:"ok"`
	Result []TgUpdate `json:"result"`
}

type TgUser

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

	FirstName    string `json:"first_name"`
	LastName     string `json:"last_name,omitempty"`
	Username     string `json:"username,omitempty"`
	LanguageCode string `json:"language_code,omitempty"`

	IsBot     bool `json:"is_bot"`
	IsPremium bool `json:"is_premium,omitempty"`

	AddedToAttachmentMenu   bool `json:"added_to_attachment_menu,omitempty"`
	CanJoinGroups           bool `json:"can_join_groups,omitempty"`
	CanReadAllGroupMessages bool `json:"can_read_all_group_messages,omitempty"`
	SupportsInlineQueries   bool `json:"supports_inline_queries,omitempty"`
	CanConnectToBusiness    bool `json:"can_connect_to_business,omitempty"`
}

TgUser is a model of the Telegram User. See https://core.telegram.org/bots/api#user

type TgUserResponse

type TgUserResponse struct {
	Ok     bool
	Result TgUser
}

TgUserResponse is a response from the Telegram with a single TgUser object inside.

Jump to

Keyboard shortcuts

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