tgb

package
v0.15.3 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2024 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package tgb is a Telegram bot framework. It's contains high level API to easily create Telegram bots.

Index

Constants

This section is empty.

Variables

View Source
var DefaultCallbackDataCodec = NewCallackDataCodec()
View Source
var DefaultWebhookRequestIP = realip.FromRequest

DefaultWebhookRequestIP is the default function to get the IP address from the request. By default the IP address is resolved through the X-Real-Ip and X-Forwarded-For headers.

View Source
var (
	// ErrFilterNoAllow is returned when filter doesn't allow to handle Update.
	ErrFilterNoAllow = fmt.Errorf("filter no allow")
)

Functions

func DecodeCallbackData

func DecodeCallbackData(data string, dst any) error

DecodeCallbackData deserializes callback data into a struct using default parser.

func EncodeCallbackData

func EncodeCallbackData(src any) (string, error)

EncodeCallbackData serializes a struct into callback data using default parser.

Types

type BusinessConnectionHandler

type BusinessConnectionHandler func(context.Context, *BusinessConnectionUpdate) error

BusinessConnection it's typed handler for BusinessConnectionUpdate.

func (BusinessConnectionHandler) Handle

func (handler BusinessConnectionHandler) Handle(ctx context.Context, update *Update) error

type BusinessConnectionUpdate

type BusinessConnectionUpdate struct {
	*tg.BusinessConnection
	Update *Update
	Client *tg.Client
}

BusinessConnectionUpdate it's extend wrapper around tg.BusinessConnectionUpdate

type CallbackDataCodec

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

CallbackDataCodec is a helper for parsing and serializing callback data.

func NewCallackDataCodec

func NewCallackDataCodec(opts ...CallbackDataCodecOption) *CallbackDataCodec

NewCallackDataCodec creates a new CallbackDataParser with custom options. With no options it will use ':' as a delimiter, 36 as a base for integer fields, 'f' as a format and -1 as a precision for float fields.

func (*CallbackDataCodec) Decode

func (p *CallbackDataCodec) Decode(data string, dst any) error

func (*CallbackDataCodec) Encode

func (p *CallbackDataCodec) Encode(src any) (string, error)

MarshalCallbackData serializes a struct into callback data. This data will be in format prefix:field_value_1:field_value_2:...:field_value_n Only plain structures are supported.

type CallbackDataCodecOption

type CallbackDataCodecOption func(*CallbackDataCodec)

NewCallbackDataParser creates a new CallbackDataParser with default options.

func WithCallbackDataCodecDelimiter

func WithCallbackDataCodecDelimiter(delimiter rune) CallbackDataCodecOption

WithCallbackDataCodecDelimiter sets a delimiter for callback data. Default is ':'.

func WithCallbackDataCodecDisableLengthCheck

func WithCallbackDataCodecDisableLengthCheck(disable bool) CallbackDataCodecOption

WithCallbackDataCodecDisableLengthCheck disables length check for callback data. Default is false.

func WithCallbackDataCodecFloatFmt

func WithCallbackDataCodecFloatFmt(fmt byte) CallbackDataCodecOption

WithCallbackDataCodecFloatFmt sets a format for float fields in callback data. Default is 'f'.

func WithCallbackDataCodecFloatPrec

func WithCallbackDataCodecFloatPrec(prec int) CallbackDataCodecOption

WithCallbackDataCodecFloatPrec sets a precision for float fields in callback data. Default is -1.

func WithCallbackDataCodecIntBase

func WithCallbackDataCodecIntBase(base int) CallbackDataCodecOption

WithCallbackDataCodecIntBase sets a base for integer fields in callback data. Default is 36.

type CallbackDataFilter

type CallbackDataFilter[T any] struct {
	// contains filtered or unexported fields
}

func NewCallbackDataFilter

func NewCallbackDataFilter[T any](prefix string, opts ...CallbackDataCodecOption) *CallbackDataFilter[T]

NewCallbackDataFilter creates a new CallbackDataPrefixFilter with default options.

func (*CallbackDataFilter[T]) Button

func (p *CallbackDataFilter[T]) Button(text string, v T) (tg.InlineKeyboardButton, error)

Button returns a new tg.InlineKeyboardButton with the given data as callback data. If an error occurs while encoding, it will be returned.

func (*CallbackDataFilter[T]) Decode

func (p *CallbackDataFilter[T]) Decode(data string) (T, error)

Decode deserializes callback data into a struct using the filter's codec. It checks if the data has the correct prefix. If not, an error will be returned.

func (*CallbackDataFilter[T]) Encode

func (p *CallbackDataFilter[T]) Encode(src T) (string, error)

Encode serializes a struct into callback data using the filter's parser.

func (*CallbackDataFilter[T]) Filter

func (p *CallbackDataFilter[T]) Filter() Filter

Filter returns a tgb.Filter for the given prefix It checks if the data has the correct prefix. If not, it will return false.

func (*CallbackDataFilter[T]) FilterFunc

func (p *CallbackDataFilter[T]) FilterFunc(check func(v T) bool) Filter

FilterFunc returns a tgb.Filter for the given prefix and a custom data check function. It checks if the data has the correct prefix and if the custom function returns true.

func (*CallbackDataFilter[T]) Handler

Handler returns a tgb.CallbackQueryHandler that wraps the given handler with decoded callback data. If an error occurs while decoding, it will be returned and passed handler will not be called.

func (*CallbackDataFilter[T]) MustButton

func (p *CallbackDataFilter[T]) MustButton(text string, v T) tg.InlineKeyboardButton

MustButton returns a new tg.InlineKeyboardButton with the given data as callback data. If an error occurs while encoding, empty button will be returned.

type CallbackDataFilterHandler

type CallbackDataFilterHandler[T any] func(ctx context.Context, cbq *CallbackQueryUpdate, cbd T) error

type CallbackDataIsTooLongError

type CallbackDataIsTooLongError struct {
	Length int
}

CallbackDataIsTooLongError is returned when callback data length is too long.

func (*CallbackDataIsTooLongError) Error

Error returns a string representation of the error.

type CallbackQueryHandler

type CallbackQueryHandler func(context.Context, *CallbackQueryUpdate) error

CallbackQueryHandler it's typed handler for CallbackQuery.

func (CallbackQueryHandler) Handle

func (handler CallbackQueryHandler) Handle(ctx context.Context, update *Update) error

type CallbackQueryUpdate

type CallbackQueryUpdate struct {
	*tg.CallbackQuery

	Update *Update
	Client *tg.Client
}

func (*CallbackQueryUpdate) Answer

func (cbq *CallbackQueryUpdate) Answer() *tg.AnswerCallbackQueryCall

Answer without response (just hide loading icon)

func (*CallbackQueryUpdate) AnswerText

func (cbq *CallbackQueryUpdate) AnswerText(text string, alert bool) *tg.AnswerCallbackQueryCall

AnswerText with text response and optional alert

func (*CallbackQueryUpdate) AnswerURL

func (cbq *CallbackQueryUpdate) AnswerURL(url string) *tg.AnswerCallbackQueryCall

AnswerURL with URL response and optional. URL has limitations, see CallbackQuery.Url for more details.

type ChatBoostHandler

type ChatBoostHandler func(context.Context, *ChatBoostUpdate) error

ChatBoostHandler it's typed handler for ChatBoostUpdate.

func (ChatBoostHandler) Handle

func (handler ChatBoostHandler) Handle(ctx context.Context, update *Update) error

type ChatBoostUpdate

type ChatBoostUpdate struct {
	*tg.ChatBoostUpdated
	Update *Update
	Client *tg.Client
}

ChatBoostUpdate it's extend wrapper around tg.ChatBoostUpdated.

type ChatJoinRequestHandler

type ChatJoinRequestHandler func(context.Context, *ChatJoinRequestUpdate) error

ChatJoinRequestHandler it's typed handler for ChatJoinRequest.

func (ChatJoinRequestHandler) Handle

func (handler ChatJoinRequestHandler) Handle(ctx context.Context, update *Update) error

type ChatJoinRequestUpdate

type ChatJoinRequestUpdate struct {
	*tg.ChatJoinRequest
	Update *Update
	Client *tg.Client
}

func (*ChatJoinRequestUpdate) Approve

func (joinRequest *ChatJoinRequestUpdate) Approve() *tg.ApproveChatJoinRequestCall

Approve join request

func (*ChatJoinRequestUpdate) Decline

func (joinRequest *ChatJoinRequestUpdate) Decline() *tg.DeclineChatJoinRequestCall

Decline join request

type ChatMemberUpdatedHandler

type ChatMemberUpdatedHandler func(context.Context, *ChatMemberUpdatedUpdate) error

UpdateHandler it's typed handler for ChatMemberUpdate subtype.

func (ChatMemberUpdatedHandler) Handle

func (handler ChatMemberUpdatedHandler) Handle(ctx context.Context, update *Update) error

type ChatMemberUpdatedUpdate

type ChatMemberUpdatedUpdate struct {
	*tg.ChatMemberUpdated
	Update *Update
	Client *tg.Client
}

type ChosenInlineResultHandler

type ChosenInlineResultHandler func(context.Context, *ChosenInlineResultUpdate) error

ChosenInlineResultHandler it's typed handler for ChosenInlineResult. Impliment Handler interface.

func (ChosenInlineResultHandler) Handle

func (handler ChosenInlineResultHandler) Handle(ctx context.Context, update *Update) error

type ChosenInlineResultUpdate

type ChosenInlineResultUpdate struct {
	*tg.ChosenInlineResult
	Update *Update
	Client *tg.Client
}

type CommandFilterOption

type CommandFilterOption func(*commandFilter)

func WithCommandAlias

func WithCommandAlias(aliases ...string) CommandFilterOption

WithCommandAlias adds alias to command.

func WithCommandIgnoreCaption

func WithCommandIgnoreCaption(ignoreCaption bool) CommandFilterOption

WithCommandIgnoreCaption sets ignore caption as text source. By default is true.

func WithCommandIgnoreCase

func WithCommandIgnoreCase(ignoreCase bool) CommandFilterOption

WithCommandIgnoreCase sets ignore case in commands. By default is true.

func WithCommandIgnoreMention

func WithCommandIgnoreMention(ignoreMention bool) CommandFilterOption

WithCommandIgnoreMention sets ignore mention in command with mention (/command@username). By default is false.

func WithCommandPrefix

func WithCommandPrefix(prefixes ...string) CommandFilterOption

WithCommandPrefix sets allowed command prefixies. By default is '/'.

type DeletedBusinessMessageHandler

type DeletedBusinessMessageHandler func(context.Context, *DeletedBusinessMessagesUpdate) error

DeletedBusinessMessageHandler it's typed handler for [DeletedBusinessMessage]

func (DeletedBusinessMessageHandler) Handle

func (handler DeletedBusinessMessageHandler) Handle(ctx context.Context, update *Update) error

type DeletedBusinessMessagesUpdate

type DeletedBusinessMessagesUpdate struct {
	*tg.BusinessMessagesDeleted
	Update *Update
	Client *tg.Client
}

type ErrorHandler

type ErrorHandler func(ctx context.Context, update *Update, err error) error

ErrorHandler define interface for error handling in Bot. See Bot.Error for more information.

type Filter

type Filter interface {
	Allow(ctx context.Context, update *Update) (bool, error)
}

Filter is a interface for generic update filter.

func All

func All(filters ...Filter) Filter

All pass update to handler, if all of filters allow it.

func Any

func Any(filters ...Filter) Filter

Any pass update to handler, if any of filters allow it.

func ChatType

func ChatType(types ...tg.ChatType) Filter

ChatType filter checks if chat type is in specified list.

Check is performed in:

  • Message, EditedMessage, ChannelPost, EditedChannelPost
  • CallbackQuery.Message.Chat.Type (if not nil)
  • InlineQuery.ChatType
  • MyChatMember.Chat.Type
  • ChatMember.Chat.Type
  • ChatJoinRequest.Chat.Type

func Command

func Command(command string, opts ...CommandFilterOption) Filter

Command adds filter for command with specified options.

func MessageEntity

func MessageEntity(types ...tg.MessageEntityType) Filter

MessageEntity checks Message, EditedMessage, ChannelPost, EditedChannelPost .Entities, .CaptionEntities, .Poll.ExplanationEntities or .Game.TextEntities for matching type with specified. If multiple types are specified, it checks if message entity type is one of them.

func MessageType

func MessageType(types ...tg.MessageType) Filter

MessageType checks Message, EditedMessage, ChannelPost, EditedChannelPost for matching type with specified. If multiple types are specified, it checks if message type is one of them.

func Not

func Not(filter Filter) Filter

Not pass update to handler, if specified filter does not allow it.

func Regexp

func Regexp(re *regexp.Regexp) Filter

RegexpFilter handles updates by regexp.

Checks following fields:

  • Update.Message.Text
  • Update.Message.Caption
  • Update.CallbackQuery.Data
  • Update.InlineQuery.Query
  • Update.ChosenInlineResult.Query
  • Update.Poll.Question

func TextContains

func TextContains(v string, opts ...TextFuncFilterOption) Filter

TextContains creates a TextFuncFilter that checks if text of update contains specified.

func TextEqual

func TextEqual(v string, opts ...TextFuncFilterOption) Filter

TextEqual creates a TextFuncFilter that checks if text of update equals to specified.

func TextFunc

func TextFunc(fn func(text string, ignoreCase bool) bool, opts ...TextFuncFilterOption) Filter

TextFunc creates a generic TextFuncFilter with specified function.

func TextHasPrefix

func TextHasPrefix(v string, opts ...TextFuncFilterOption) Filter

TextHasPrefix creates a TextFuncFilter that checks if text of update has prefix.

func TextHasSuffix

func TextHasSuffix(v string, opts ...TextFuncFilterOption) Filter

TextHasSuffix creates a TextFuncFilter that checks if text of update has suffix.

func TextIn

func TextIn(vs []string, opts ...TextFuncFilterOption) Filter

TextIn creates a TextFuncFilter that checks if text of update is in specified slice.

type FilterFunc

type FilterFunc func(ctx context.Context, update *Update) (bool, error)

The FilterFunc type is an adapter to allow the use of ordinary functions as filter. If f is a function with the appropriate signature, FilterFunc(f) is a Filter that calls f.

func (FilterFunc) Allow

func (filter FilterFunc) Allow(ctx context.Context, update *Update) (bool, error)

Allow implements Filter interface.

type GlobalMiddlewareFunc added in v0.15.3

type GlobalMiddlewareFunc func(context.Context, *Update) (context.Context, *Update, error)

type Handler

type Handler interface {
	Handle(ctx context.Context, update *Update) error
}

Handler define generic Update handler.

type HandlerFunc

type HandlerFunc func(ctx context.Context, update *Update) error

HandlerFunc define functional handler.

func (HandlerFunc) Handle

func (handler HandlerFunc) Handle(ctx context.Context, update *Update) error

Handle implements Handler interface.

type InlineQueryHandler

type InlineQueryHandler func(context.Context, *InlineQueryUpdate) error

InlineQueryHandler it's typed handler for InlineQuery. Impliment Handler interface.

func (InlineQueryHandler) Handle

func (handler InlineQueryHandler) Handle(ctx context.Context, update *Update) error

type InlineQueryUpdate

type InlineQueryUpdate struct {
	*tg.InlineQuery
	Update *Update
	Client *tg.Client
}

func (*InlineQueryUpdate) Answer

func (iq *InlineQueryUpdate) Answer(results []tg.InlineQueryResult) *tg.AnswerInlineQueryCall

type Logger

type Logger interface {
	Printf(format string, args ...any)
}

Logger defines generic interface for loggers

type MessageHandler

type MessageHandler func(context.Context, *MessageUpdate) error

MessageHandler it's typed handler for Message. Impliment Handler interface.

func (MessageHandler) Handle

func (handler MessageHandler) Handle(ctx context.Context, update *Update) error

type MessageReactionCountHandler

type MessageReactionCountHandler func(context.Context, *MessageReactionCountUpdate) error

MessageReactionCountHandler it's typed handler for MessageReactionCountUpdate.

func (MessageReactionCountHandler) Handle

func (handler MessageReactionCountHandler) Handle(ctx context.Context, update *Update) error

type MessageReactionCountUpdate

type MessageReactionCountUpdate struct {
	*tg.MessageReactionCountUpdated
	Update *Update
	Client *tg.Client
}

MessageReactionCountUpdate it's extend wrapper around tg.MessageReactionCountUpdated.

type MessageReactionHandler

type MessageReactionHandler func(context.Context, *MessageReactionUpdate) error

MessageReactionHandler it's typed handler for MessageReactionUpdate.

func (MessageReactionHandler) Handle

func (handler MessageReactionHandler) Handle(ctx context.Context, update *Update) error

type MessageReactionUpdate

type MessageReactionUpdate struct {
	*tg.MessageReactionUpdated
	Update *Update
	Client *tg.Client
}

MessageReactionUpdate it's extend wrapper around tg.MessageReactionUpdated.

type MessageUpdate

type MessageUpdate struct {
	*tg.Message
	Client *tg.Client
	Update *Update
}

MessageUpdate it's extend wrapper around tg.Message.

func (*MessageUpdate) Answer

func (msg *MessageUpdate) Answer(text string) *tg.SendMessageCall

Answer calls sendMessage with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerAnimation

func (msg *MessageUpdate) AnswerAnimation(animation tg.FileArg) *tg.SendAnimationCall

AnswerAnimation calls sendAnimation with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerAudio

func (msg *MessageUpdate) AnswerAudio(audio tg.FileArg) *tg.SendAudioCall

AnswerAudio calls sendAudio with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerChatAction

func (msg *MessageUpdate) AnswerChatAction(action tg.ChatAction) *tg.SendChatActionCall

AnswerChatAction calls sendChatAction with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerContact

func (msg *MessageUpdate) AnswerContact(phoneNumber string, firstName string) *tg.SendContactCall

AnswerContact calls sendContact with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerDice

func (msg *MessageUpdate) AnswerDice(emoji string) *tg.SendDiceCall

AnswerDice calls sendDice with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerDocument

func (msg *MessageUpdate) AnswerDocument(document tg.FileArg) *tg.SendDocumentCall

AnswerDocument calls sendDocument with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerLocation

func (msg *MessageUpdate) AnswerLocation(latitude float64, longitude float64) *tg.SendLocationCall

AnswerLocation calls sendLocation with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerMediaGroup

func (msg *MessageUpdate) AnswerMediaGroup(action []tg.InputMedia) *tg.SendMediaGroupCall

AnswerMediaGroup calls sendMediaGroup with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerPhoto

func (msg *MessageUpdate) AnswerPhoto(photo tg.FileArg) *tg.SendPhotoCall

AnswerPhoto calls sendPhoto with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerPoll

func (msg *MessageUpdate) AnswerPoll(question string, options []string) *tg.SendPollCall

AnswerPoll calls sendPoll with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerSticker

func (msg *MessageUpdate) AnswerSticker(sticker tg.FileArg) *tg.SendStickerCall

AnswerSticker calls sendSticker with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerVenue

func (msg *MessageUpdate) AnswerVenue(latitude float64, longitude float64, title string, address string) *tg.SendVenueCall

AnswerVenue calls sendVenue with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerVideo

func (msg *MessageUpdate) AnswerVideo(video tg.FileArg) *tg.SendVideoCall

AnswerVideo calls sendVideo with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerVideoNote

func (msg *MessageUpdate) AnswerVideoNote(videoNote tg.FileArg) *tg.SendVideoNoteCall

AnswerVideoNote calls sendVideoNote with pre-defined chatID to incoming message chat.

func (*MessageUpdate) AnswerVoice

func (msg *MessageUpdate) AnswerVoice(voice tg.FileArg) *tg.SendVoiceCall

AnswerVoice calls sendVoice with pre-defined chatID to incoming message chat.

func (*MessageUpdate) Copy

func (msg *MessageUpdate) Copy(to tg.PeerID) *tg.CopyMessageCall

Copy incoming message to another chat.

func (*MessageUpdate) EditCaption

func (msg *MessageUpdate) EditCaption(caption string) *tg.EditMessageCaptionCall

EditCaption of incoming message.

func (*MessageUpdate) EditReplyMarkup

func (msg *MessageUpdate) EditReplyMarkup(markup tg.InlineKeyboardMarkup) *tg.EditMessageReplyMarkupCall

EditReplyMarkup of incoming message.

func (*MessageUpdate) EditText

func (msg *MessageUpdate) EditText(text string) *tg.EditMessageTextCall

EditText of incoming message.

func (*MessageUpdate) Forward

func (msg *MessageUpdate) Forward(to tg.PeerID) *tg.ForwardMessageCall

Forward incoming message to another chat.

func (*MessageUpdate) React

func (msg *MessageUpdate) React(reactions ...tg.ReactionType) *tg.SetMessageReactionCall

React to incoming message. No arguments means remove all reactions from the message.

type Middleware deprecated

type Middleware interface {
	Wrap(Handler) Handler
}

Middleware is used to modify or process the Update before it is passed to the handler. All middleware should be registered before the handlers registration.

Deprecated: Causes performance issues and breaks routing logic. Use GlobalMiddlewareFunc

type MiddlewareFunc deprecated

type MiddlewareFunc func(Handler) Handler

MiddlewareFunc is used to modify or process the Update before it is passed to the handler. All middleware should be registered before the handlers registration.

Deprecated: Causes performance issues and breaks routing logic. Use GlobalMiddlewareFunc

func (MiddlewareFunc) Wrap

func (m MiddlewareFunc) Wrap(h Handler) Handler

type PollAnswerHandler

type PollAnswerHandler func(context.Context, *PollAnswerUpdate) error

PollAnswerHandler it's typed handler for PollAnswer.

func (PollAnswerHandler) Handle

func (handler PollAnswerHandler) Handle(ctx context.Context, update *Update) error

type PollAnswerUpdate

type PollAnswerUpdate struct {
	*tg.PollAnswer
	Update *Update
	Client *tg.Client
}

type PollHandler

type PollHandler func(context.Context, *PollUpdate) error

PollHandler it's typed handler for Poll.

func (PollHandler) Handle

func (handler PollHandler) Handle(ctx context.Context, update *Update) error

type PollUpdate

type PollUpdate struct {
	*tg.Poll
	Update *Update
	Client *tg.Client
}

type Poller

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

Poller is a long polling update deliverer.

func NewPoller

func NewPoller(handler Handler, client *tg.Client, opts ...PollerOption) *Poller

func (*Poller) Run

func (poller *Poller) Run(ctx context.Context) error

type PollerOption

type PollerOption func(*Poller)

func WithPollerAllowedUpdates

func WithPollerAllowedUpdates(allowedUpdates ...tg.UpdateType) PollerOption

WithPollerAllowedUpdates sets the allowed updates.

func WithPollerHandlerTimeout

func WithPollerHandlerTimeout(timeout time.Duration) PollerOption

WithHandlerTimeout sets the timeout for Handler exectution.

func WithPollerLimit

func WithPollerLimit(limit int) PollerOption

WithPollerLimit sets the limit for batch size.

func WithPollerLogger

func WithPollerLogger(logger Logger) PollerOption

WithPollerLogger sets the logger for the poller.

func WithPollerRetryAfter

func WithPollerRetryAfter(retryAfter time.Duration) PollerOption

WithPollerRetryAfter sets the retry after for polling.

func WithPollerTimeout

func WithPollerTimeout(timeout time.Duration) PollerOption

WithPollerTimeout sets the timeout for polling.

type PreCheckoutQueryHandler

type PreCheckoutQueryHandler func(context.Context, *PreCheckoutQueryUpdate) error

PreCheckoutQueryHandler it's typed handler for PreCheckoutQuery.

func (PreCheckoutQueryHandler) Handle

func (handler PreCheckoutQueryHandler) Handle(ctx context.Context, update *Update) error

type PreCheckoutQueryUpdate

type PreCheckoutQueryUpdate struct {
	*tg.PreCheckoutQuery
	Update *Update
	Client *tg.Client
}

func (*PreCheckoutQueryUpdate) Answer

func (pcq *PreCheckoutQueryUpdate) Answer(ok bool) *tg.AnswerPreCheckoutQueryCall

type RemovedChatBoostHandler

type RemovedChatBoostHandler func(context.Context, *RemovedChatBoostUpdate) error

RemovedChatBoostHandler it's typed handler for RemovedChatBoostUpdate.

func (RemovedChatBoostHandler) Handle

func (handler RemovedChatBoostHandler) Handle(ctx context.Context, update *Update) error

type RemovedChatBoostUpdate

type RemovedChatBoostUpdate struct {
	*tg.ChatBoostRemoved
	Update *Update
	Client *tg.Client
}

RemovedChatBoostUpdate it's extend wrapper around tg.RemovedChatBoost.

type Router

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

Router is a router for incoming Updates. tg.Update should be wrapped into tgb.Update with binded Client and Update.

func NewRouter

func NewRouter() *Router

NewRouter creates new Bot.

func (*Router) BusinessConnection

func (bot *Router) BusinessConnection(handler BusinessConnectionHandler, filters ...Filter) *Router

BusinessConnection register handlers for Update with not empty BusinessConnection field.

func (*Router) BusinessMessage

func (bot *Router) BusinessMessage(handler MessageHandler, filters ...Filter) *Router

BusinessMessage register handlers for Update with not empty BusinessMessage field.

func (*Router) CallbackQuery

func (bot *Router) CallbackQuery(handler CallbackQueryHandler, filters ...Filter) *Router

CallbackQuery register handlers for Update with not empty CallbackQuery field.

func (*Router) ChannelPost

func (bot *Router) ChannelPost(handler MessageHandler, filters ...Filter) *Router

ChannelPost register handlers for Update with not empty ChannelPost field.

func (*Router) ChatBoost

func (bot *Router) ChatBoost(handler ChatBoostHandler, filters ...Filter) *Router

ChatBoost register handlers for Update with not empty ChatBoost field.

func (*Router) ChatJoinRequest

func (bot *Router) ChatJoinRequest(handler ChatJoinRequestHandler, filters ...Filter) *Router

ChatJoinRequest register handlers for Update with not empty ChatJoinRequest field.

func (*Router) ChatMember

func (bot *Router) ChatMember(handler ChatMemberUpdatedHandler, filters ...Filter) *Router

ChatMember register handlers for Update with not empty ChatMember field.

func (*Router) ChosenInlineResult

func (bot *Router) ChosenInlineResult(handler ChosenInlineResultHandler, filters ...Filter) *Router

ChosenInlineResult register handlers for Update with not empty ChosenInlineResult field.

func (*Router) DeletedBusinessMessages

func (bot *Router) DeletedBusinessMessages(handler DeletedBusinessMessageHandler, filters ...Filter) *Router

DeletedBusinessMessages register handlers for Update with not empty DeletedBusinessMessages field.

func (*Router) EditedBusinessMessage

func (bot *Router) EditedBusinessMessage(handler MessageHandler, filters ...Filter) *Router

EditedBusinessMessage register handlers for Update with not empty EditedBusinessMessage field.

func (*Router) EditedChannelPost

func (bot *Router) EditedChannelPost(handler MessageHandler, filters ...Filter) *Router

EditedChannelPost register handlers for Update with not empty EditedChannelPost field.

func (*Router) EditedMessage

func (bot *Router) EditedMessage(handler MessageHandler, filters ...Filter) *Router

EditedMessage register handlers for Update with not empty EditedMessage field.

func (*Router) Error

func (bot *Router) Error(handler ErrorHandler) *Router

Error registers a handler for errors. If any error occurs in the chain, it will be passed to that handler. By default, errors are returned back by handler method. You can customize this behavior by passing a custom error handler.

func (*Router) GlobalUse added in v0.15.3

func (bot *Router) GlobalUse(mws ...GlobalMiddlewareFunc) *Router

GlobalUse add middleware to chain handlers.

func (*Router) Handle

func (bot *Router) Handle(ctx context.Context, update *Update) error

Handle handles an Update.

func (*Router) InlineQuery

func (bot *Router) InlineQuery(handler InlineQueryHandler, filters ...Filter) *Router

InlineQuery register handlers for Update with not empty InlineQuery field.

func (*Router) Message

func (bot *Router) Message(handler MessageHandler, filters ...Filter) *Router

Message register handlers for Update with not empty Message field.

func (*Router) MessageReaction

func (bot *Router) MessageReaction(handler MessageReactionHandler, filters ...Filter) *Router

MessageReaction register handlers for Update with not empty MessageReaction field.

func (*Router) MessageReactionCount

func (bot *Router) MessageReactionCount(handler MessageReactionCountHandler, filters ...Filter) *Router

MessageReactionCount register handlers for Update with not empty MessageReactionCount field.

func (*Router) MyChatMember

func (bot *Router) MyChatMember(handler ChatMemberUpdatedHandler, filters ...Filter) *Router

MyChatMember register handlers for Update with not empty MyChatMember field.

func (*Router) Poll

func (bot *Router) Poll(handler PollHandler, filters ...Filter) *Router

Poll register handlers for Update with not empty Poll field.

func (*Router) PollAnswer

func (bot *Router) PollAnswer(handler PollAnswerHandler, filters ...Filter) *Router

PollAnswer register handlers for Update with not empty PollAnswer field.

func (*Router) PreCheckoutQuery

func (bot *Router) PreCheckoutQuery(handler PreCheckoutQueryHandler, filters ...Filter) *Router

PreCheckoutQuery register handlers for Update with not empty PreCheckoutQuery field.

func (*Router) RemovedChatBoost

func (bot *Router) RemovedChatBoost(handler RemovedChatBoostHandler, filters ...Filter) *Router

RemovedChatBoost register handlers for Update with not empty RemovedChatBoost field.

func (*Router) ShippingQuery

func (bot *Router) ShippingQuery(handler ShippingQueryHandler, filters ...Filter) *Router

ShippingQuery register handlers for Update with not empty ShippingQuery field.

func (*Router) Update

func (bot *Router) Update(handler HandlerFunc, filters ...Filter) *Router

Update registers a generic Update handler. It will be called as typed handlers only in filters match the update. First check Update handler, then typed.

func (*Router) Use deprecated

func (bot *Router) Use(mws ...Middleware) *Router

Use add middleware to chain handlers. Should be called before any other register handler.

Deprecated: Causes performance issues and breaks routing logic. Use GlobalUse

type ShippingQueryHandler

type ShippingQueryHandler func(context.Context, *ShippingQueryUpdate) error

ShippingQueryHandler it's typed handler for ShippingQuery.

func (ShippingQueryHandler) Handle

func (handler ShippingQueryHandler) Handle(ctx context.Context, update *Update) error

type ShippingQueryUpdate

type ShippingQueryUpdate struct {
	*tg.ShippingQuery
	Update *Update
	Client *tg.Client
}

func (*ShippingQueryUpdate) Answer

func (sq *ShippingQueryUpdate) Answer(ok bool) *tg.AnswerShippingQueryCall

type TextFuncFilterOption

type TextFuncFilterOption func(*textFuncFilter)

TextFuncFilterOption is a filter option for TextFuncFilter.

func WithTextFuncIgnoreCase

func WithTextFuncIgnoreCase(v bool) TextFuncFilterOption

type TextMessageCallBuilder

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

TextMessageCallBuilder contains all common fields for methods sendText, editMessageText, editMessageReplyMarkup. It's useful for building diffrent calls with the same params.

Example:

newMenuBuilder(...).Client(client).AsSend(chat)
newMenuBuilder(...).Client(client).AsEditTextFromCBQ(cbq.CallbackQuery)

Also can be sended as reply to webhook

msg.Update.Reply(ctx, newMenuBuilder(...).AsEditTextFromCBQ(cbq.CallbackQuery))

func NewTextMessageCallBuilder

func NewTextMessageCallBuilder(text string) *TextMessageCallBuilder

NewTextMessageCallBuilder creates new TextMessageCallBuilder with specified text.

func (*TextMessageCallBuilder) AsEditReplyMarkup

func (b *TextMessageCallBuilder) AsEditReplyMarkup(peer tg.PeerID, id int) *tg.EditMessageReplyMarkupCall

AsEditReplyMarkup returns call editReplyMarkup with prepopulated fields.

func (*TextMessageCallBuilder) AsEditReplyMarkupFromCBQ

func (b *TextMessageCallBuilder) AsEditReplyMarkupFromCBQ(callback *tg.CallbackQuery) *tg.EditMessageReplyMarkupCall

AsEditReplyMarkupFromCBQ wraps AsEditReplyMarkup with callback as argument. It's useful if you have an object of CallbackQuery and want to edit it.

func (*TextMessageCallBuilder) AsEditReplyMarkupFromMsg

func (b *TextMessageCallBuilder) AsEditReplyMarkupFromMsg(msg tg.Message) *tg.EditMessageReplyMarkupCall

AsEditReplyMarkupFromMsg wraps AsEditReplyMarkup with message as argument. It's useful if you have an object of Message and want to edit it.

func (*TextMessageCallBuilder) AsEditReplyMarkupInline

func (b *TextMessageCallBuilder) AsEditReplyMarkupInline(id string) *tg.EditMessageReplyMarkupCall

AsEditReplyMarkupInline returns call editReplyMarkup with by inline message id.

func (*TextMessageCallBuilder) AsEditText

func (b *TextMessageCallBuilder) AsEditText(peer tg.PeerID, id int) *tg.EditMessageTextCall

AsEditText returns call editTextMessage with prepopulated fields.

func (*TextMessageCallBuilder) AsEditTextFromCBQ

func (b *TextMessageCallBuilder) AsEditTextFromCBQ(callback *tg.CallbackQuery) *tg.EditMessageTextCall

AsEditTextFromCBQ wraps AsEditText with callback as argument. It's useful if you have an object of CallbackQuery and want to edit it.

func (*TextMessageCallBuilder) AsEditTextFromMsg

func (b *TextMessageCallBuilder) AsEditTextFromMsg(msg *tg.Message) *tg.EditMessageTextCall

AsEditTextFromMsg wraps AsEditText with message as argument. It's useful if you have an object of Message and want to edit it.

func (*TextMessageCallBuilder) AsEditTextInline

func (b *TextMessageCallBuilder) AsEditTextInline(id string) *tg.EditMessageTextCall

AsEditTextInline returns call editTextMessage with by inline message id.

func (*TextMessageCallBuilder) AsSend

AsSend returns call sendMessage with specified peer.

func (*TextMessageCallBuilder) Client

Client sets client for the message.

func (*TextMessageCallBuilder) Entities

Entities sets entities for the message.

func (*TextMessageCallBuilder) LinkPreviewOptions

func (b *TextMessageCallBuilder) LinkPreviewOptions(options tg.LinkPreviewOptions) *TextMessageCallBuilder

LinkPreviewOptions sets link preview options for the message.

func (*TextMessageCallBuilder) ParseMode

ParseMode sets parse mode for the message.

func (*TextMessageCallBuilder) ReplyMarkup

ReplyMarkup sets reply markup for the message.

func (*TextMessageCallBuilder) Text

Text sets text for the message.

type Update

type Update struct {
	*tg.Update
	Client *tg.Client
	// contains filtered or unexported fields
}

Update wraps around a tg.Update. Also contains Client which is used to send responses.

func (*Update) Reply

func (update *Update) Reply(ctx context.Context, v UpdateReply) error

Reply to Webhook, if possible or make usual call via Client.

func (*Update) Respond deprecated

func (update *Update) Respond(ctx context.Context, v UpdateRespond) error

Deprecated: use Reply instead.

type UpdateReply

type UpdateReply interface {
	json.Marshaler
	DoVoid(ctx context.Context) error
	Bind(client *tg.Client)
}

UpdateReply defines interface for responding to an update via Webhook.

type UpdateRespond deprecated

type UpdateRespond = UpdateReply

Deprecated: use UpdateReply instead.

type Webhook

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

Webhook is a Telegram bot webhook handler. It handles incoming webhook requests and calls the handler function. It implements the http.Handler interface, but can be adapted to any other handlers, see Webhook.ServeRequest.

func NewWebhook

func NewWebhook(handler Handler, client *tg.Client, url string, options ...WebhookOption) *Webhook

func (*Webhook) Run

func (webhook *Webhook) Run(ctx context.Context, listen string) error

Run starts the webhook server.

func (*Webhook) ServeHTTP

func (webhook *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the HTTP handler for webhook requests. Implementation of http.Handler.

func (*Webhook) ServeRequest

func (webhook *Webhook) ServeRequest(ctx context.Context, r *WebhookRequest) *WebhookResponse

ServeRequest is the generic for webhook requests from Telegram.

func (*Webhook) Setup

func (webhook *Webhook) Setup(ctx context.Context) (err error)

type WebhookOption

type WebhookOption func(*Webhook)

WebhookOption used to configure the Webhook

func WithDropPendingUpdates

func WithDropPendingUpdates(dropPendingUpdates bool) WebhookOption

WithDropPendingUpdates drop pending updates (if pending > 0 only)

func WithWebhookAllowedUpdates

func WithWebhookAllowedUpdates(updates ...tg.UpdateType) WebhookOption

WithWebhookAllowedUpdates sets the list of allowed updates. By default all update types except chat_member (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.

func WithWebhookIP

func WithWebhookIP(ip string) WebhookOption

WithWebhookIP the fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS

func WithWebhookLogger

func WithWebhookLogger(logger Logger) WebhookOption

WithWebhookLogger sets the logger which will be used to log the webhook related errors.

func WithWebhookMaxConnections

func WithWebhookMaxConnections(maxConnections int) WebhookOption

WithWebhookMaxConnections sets the maximum number of concurrent connections. By default is 40

func WithWebhookRequestIP

func WithWebhookRequestIP(ip func(r *http.Request) string) WebhookOption

WithWebhookRequestIP sets function to get the IP address from the request. By default the IP address is resolved through the X-Real-Ip and X-Forwarded-For headers.

func WithWebhookSecuritySubnets

func WithWebhookSecuritySubnets(subnets ...netip.Prefix) WebhookOption

WithWebhookSecuritySubnets sets list of subnets which are allowed to send webhook requests.

func WithWebhookSecurityToken

func WithWebhookSecurityToken(token string) WebhookOption

WithWebhookSecurityToken sets the security token which is used to validate the webhook requests. By default the token is generated from the client token via sha256. 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you.

type WebhookRequest

type WebhookRequest struct {
	Method      string
	ContentType string

	IP            netip.Addr
	SecurityToken string

	Body io.Reader
}

WebhookRequest is the request received from Telegram.

type WebhookResponse

type WebhookResponse struct {
	Status      int
	ContentType string
	Body        []byte
}

WebhookResponse is the response to be sent to WebhookRequest.

Directories

Path Synopsis
Package session provides a session managment.
Package session provides a session managment.

Jump to

Keyboard shortcuts

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