handlers

package
v0.0.0-...-6dcbb19 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2022 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package handlers provides handlers & predicates for TGO.

Bot handlers provide an easy way to make net/http like handlers, but with predicates instead of paths.

You can create BotHandler, register new handlers and start processing updates from the update channel which you provide. All handlers process updates concurrently, but keep in mind that predicates are checked sequentially. This gives an ability to process one update only with the first matched handler.

Example

This example shows how you can create BotHandler and register new handlers. Note, that order of registration directly impacts order of checking matched handlers, and only the first matched handler will process the update.

package main

import (
	"fmt"
	"os"

	"github.com/dsurl/tgo"
	handlers "github.com/dsurl/tgo/handlers"
	tu "github.com/dsurl/tgo/utils"
)

func main() {
	botToken := os.Getenv("TOKEN")

	bot, err := tgo.NewBot(botToken, tgo.WithDefaultDebugLogger())
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Get updates channel
	updates, _ := bot.UpdatesViaLongPulling(nil)
	defer bot.StopLongPulling()

	// Create bot handler and specify from where to get updates
	bh, _ := th.NewBotHandler(bot, updates)

	// Register new handler with match on command `/start`
	bh.Handle(func(bot *tgo.Bot, update tgo.Update) {
		// Send message
		_, _ = bot.SendMessage(tu.Message(
			tu.ID(update.Message.Chat.ID),
			fmt.Sprintf("Hello %s!", update.Message.From.FirstName),
		))
	}, th.CommandEqual("start"))

	// Register new handler with match on any command
	// Handlers will match only once and in order of registration, so this handler will be called on any command
	// except `/start` command
	bh.Handle(func(bot *tgo.Bot, update tgo.Update) {
		// Send message
		_, _ = bot.SendMessage(tu.Message(
			tu.ID(update.Message.Chat.ID),
			"Unknown command, use /start",
		))
	}, th.AnyCommand())

	// Start handling updates
	bh.Start()

	// Stop handling updates
	defer bh.Stop()
}

One more example of handler usage. It shows how to use specific handlers to process individual fields of tgo.Update.

package main

import (
	"fmt"
	"os"

	"github.com/dsurl/tgo"
	handlers "github.com/dsurl/tgo/handlers"
	tu "github.com/dsurl/tgo/utils"
)

func main() {
	botToken := os.Getenv("TOKEN")

	// Note: Please keep in mind that default logger may expose sensitive information, use in development only
	bot, err := tgo.NewBot(botToken, tgo.WithDefaultDebugLogger())
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Get updates channel
	updates, _ := bot.UpdatesViaLongPulling(nil)
	defer bot.StopLongPulling()

	// Create bot handler and specify from where to get updates
	bh, _ := th.NewBotHandler(bot, updates)

	// Register new handler with match on command `/start`
	bh.HandleMessage(func(bot *tgo.Bot, message tgo.Message) {
		// Send message with inline keyboard
		_, _ = bot.SendMessage(tu.Message(
			tu.ID(message.Chat.ID),
			fmt.Sprintf("Hello %s!", message.From.FirstName),
		).WithReplyMarkup(tu.InlineKeyboard(
			tu.InlineKeyboardRow(tu.InlineKeyboardButton("Go!").WithCallbackData("go"))),
		))
	}, th.CommandEqual("start"))

	// Register new handler with match on call back query with data equal to `go` and non nil message
	bh.HandleCallbackQuery(func(bot *tgo.Bot, query tgo.CallbackQuery) {
		// Send message
		_, _ = bot.SendMessage(tu.Message(tu.ID(query.Message.Chat.ID), "GO GO GO"))

		// Answer callback query
		_ = bot.AnswerCallbackQuery(&tgo.AnswerCallbackQueryParams{
			CallbackQueryID: query.ID,
			Text:            "Done",
		})
	}, th.AnyCallbackQueryWithMessage(), th.CallbackDataEqual("go"))

	// Start handling updates
	bh.Start()

	// Stop handling updates
	defer bh.Stop()
}

Index

Constants

View Source
const CommandMatchGroupsLen = 3

CommandMatchGroupsLen represents the length of match groups in the CommandRegexp

Variables

View Source
var CommandRegexp = regexp.MustCompile(`^/(\w+) ?(.*)$`)

CommandRegexp matches to command and has match groups on command and arguments

Functions

This section is empty.

Types

type BotHandler

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

BotHandler represents bot handler that can handle updated matching by predicates

func NewBotHandler

func NewBotHandler(bot *tgo.Bot, updates <-chan tgo.Update, options ...BotHandlerOption) (*BotHandler, error)

NewBotHandler creates new bot handler

func (*BotHandler) Handle

func (h *BotHandler) Handle(handler Handler, predicates ...Predicate)

Handle registers new handler, update will be processed only by first matched handler, order of registration determines order of matching handlers Note: All handlers will process updates in parallel, there is no guaranty on order of processed updates also, keep in mind that predicates checked sequentially

Warning: Panics if nil handler or predicate passed

func (*BotHandler) HandleCallbackQuery

func (h *BotHandler) HandleCallbackQuery(handler CallbackQueryHandler, predicates ...Predicate)

HandleCallbackQuery same as Handle, but assumes that the update contains a callback query

func (*BotHandler) HandleChannelPost

func (h *BotHandler) HandleChannelPost(handler MessageHandler, predicates ...Predicate)

HandleChannelPost same as Handle, but assumes that the update contains a channel post

func (*BotHandler) HandleChatJoinRequest

func (h *BotHandler) HandleChatJoinRequest(handler ChatJoinRequestHandler, predicates ...Predicate)

HandleChatJoinRequest same as Handle, but assumes that the update contains chat join request

func (*BotHandler) HandleChatMemberUpdated

func (h *BotHandler) HandleChatMemberUpdated(handler ChatMemberUpdatedHandler, predicates ...Predicate)

HandleChatMemberUpdated same as Handle, but assumes that the update contains chat member

func (*BotHandler) HandleChosenInlineResult

func (h *BotHandler) HandleChosenInlineResult(handler ChosenInlineResultHandler, predicates ...Predicate)

HandleChosenInlineResult same as Handle, but assumes that the update contains a chosen inline result

func (*BotHandler) HandleEditedChannelPost

func (h *BotHandler) HandleEditedChannelPost(handler MessageHandler, predicates ...Predicate)

HandleEditedChannelPost same as Handle, but assumes that the update contains an edited channel post

func (*BotHandler) HandleEditedMessage

func (h *BotHandler) HandleEditedMessage(handler MessageHandler, predicates ...Predicate)

HandleEditedMessage same as Handle, but assumes that the update contains an edited message

func (*BotHandler) HandleInlineQuery

func (h *BotHandler) HandleInlineQuery(handler InlineQueryHandler, predicates ...Predicate)

HandleInlineQuery same as Handle, but assumes that the update contains an inline query

func (*BotHandler) HandleMessage

func (h *BotHandler) HandleMessage(handler MessageHandler, predicates ...Predicate)

HandleMessage same as Handle, but assumes that the update contains a message

func (*BotHandler) HandleMyChatMemberUpdated

func (h *BotHandler) HandleMyChatMemberUpdated(handler ChatMemberUpdatedHandler, predicates ...Predicate)

HandleMyChatMemberUpdated same as Handle, but assumes that the update contains my chat member

func (*BotHandler) HandlePoll

func (h *BotHandler) HandlePoll(handler PollHandler, predicates ...Predicate)

HandlePoll same as Handle, but assumes that the update contains a poll

func (*BotHandler) HandlePollAnswer

func (h *BotHandler) HandlePollAnswer(handler PollAnswerHandler, predicates ...Predicate)

HandlePollAnswer same as Handle, but assumes that the update contains a poll answer

func (*BotHandler) HandlePreCheckoutQuery

func (h *BotHandler) HandlePreCheckoutQuery(handler PreCheckoutQueryHandler, predicates ...Predicate)

HandlePreCheckoutQuery same as Handle, but assumes that the update contains a pre checkout query

func (*BotHandler) HandleShippingQuery

func (h *BotHandler) HandleShippingQuery(handler ShippingQueryHandler, predicates ...Predicate)

HandleShippingQuery same as Handle, but assumes that the update contains a shipping query

func (*BotHandler) IsRunning

func (h *BotHandler) IsRunning() bool

IsRunning tells if Start is running

func (*BotHandler) Start

func (h *BotHandler) Start()

Start starts handling of updates, blocks execution Calling Start() multiple times after the first one does nothing. Note: After you done with handling updates you should call Stop() method, because stopping updates chan will do nothing.

func (*BotHandler) Stop

func (h *BotHandler) Stop()

Stop stops handling of updates, will block until all updates has been processes or on timeout. If timeout set to 0, bot handler will not wait for all handlers to done processing. Note: Calling Stop() multiple times does nothing. Calling before Start() does nothing.

type BotHandlerOption

type BotHandlerOption func(bh *BotHandler) error

BotHandlerOption represents option that can be applied to bot handler

func WithStopTimeout

func WithStopTimeout(timeout time.Duration) BotHandlerOption

WithStopTimeout sets wait timeout to use. If 0 (default value), calling Stop will immediately stop processing updates, else will wait for specified time before force stopping.

type CallbackQueryHandler

type CallbackQueryHandler func(bot *tgo.Bot, query tgo.CallbackQuery)

CallbackQueryHandler handles callback queries that came from bot

type ChatJoinRequestHandler

type ChatJoinRequestHandler func(bot *tgo.Bot, request tgo.ChatJoinRequest)

ChatJoinRequestHandler handles chat join request that came from bot

type ChatMemberUpdatedHandler

type ChatMemberUpdatedHandler func(bot *tgo.Bot, chatMember tgo.ChatMemberUpdated)

ChatMemberUpdatedHandler handles chat member that came from bot

type ChosenInlineResultHandler

type ChosenInlineResultHandler func(bot *tgo.Bot, result tgo.ChosenInlineResult)

ChosenInlineResultHandler handles chosen inline result that came from bot

type Handler

type Handler func(bot *tgo.Bot, update tgo.Update)

Handler handles update that came from bot

type InlineQueryHandler

type InlineQueryHandler func(bot *tgo.Bot, query tgo.InlineQuery)

InlineQueryHandler handles inline queries that came from bot

type MessageHandler

type MessageHandler func(bot *tgo.Bot, message tgo.Message)

MessageHandler handles message that came from bot

type PollAnswerHandler

type PollAnswerHandler func(bot *tgo.Bot, answer tgo.PollAnswer)

PollAnswerHandler handles poll answer that came from bot

type PollHandler

type PollHandler func(bot *tgo.Bot, poll tgo.Poll)

PollHandler handles poll that came from bot

type PreCheckoutQueryHandler

type PreCheckoutQueryHandler func(bot *tgo.Bot, query tgo.PreCheckoutQuery)

PreCheckoutQueryHandler handles pre checkout query that came from bot

type Predicate

type Predicate func(update tgo.Update) bool

Predicate allows filtering updates for handlers

func AnyCallbackQuery

func AnyCallbackQuery() Predicate

AnyCallbackQuery is true if the callback query isn't nil

func AnyCallbackQueryWithMessage

func AnyCallbackQueryWithMessage() Predicate

AnyCallbackQueryWithMessage is true if callback query and its message isn't nil

func AnyChannelPost

func AnyChannelPost() Predicate

AnyChannelPost is true if channel post isn't nil

func AnyChannelPostWithText

func AnyChannelPostWithText() Predicate

AnyChannelPostWithText is true if channel post isn't nil and its text is not empty

func AnyChatJoinRequest

func AnyChatJoinRequest() Predicate

AnyChatJoinRequest is true if chat join request isn't nil

func AnyChatMember

func AnyChatMember() Predicate

AnyChatMember is true if chat member isn't nil

func AnyChosenInlineResult

func AnyChosenInlineResult() Predicate

AnyChosenInlineResult is true if the chosen inline result isn't nil

func AnyCommand

func AnyCommand() Predicate

AnyCommand is true if the message isn't nil, and it matches to command regexp

func AnyEditedChannelPost

func AnyEditedChannelPost() Predicate

AnyEditedChannelPost is true if the edited channel post isn't nil

func AnyEditedChannelPostWithText

func AnyEditedChannelPostWithText() Predicate

AnyEditedChannelPostWithText is true if edited channel post isn't nil and its text is not empty

func AnyEditedMessage

func AnyEditedMessage() Predicate

AnyEditedMessage is true if the edited message isn't nil

func AnyEditedMessageWithText

func AnyEditedMessageWithText() Predicate

AnyEditedMessageWithText is true if the edited message isn't nil and its text is not empty

func AnyInlineQuery

func AnyInlineQuery() Predicate

AnyInlineQuery is true if inline query isn't nil

func AnyMessage

func AnyMessage() Predicate

AnyMessage is true if the message isn't nil

func AnyMessageWithText

func AnyMessageWithText() Predicate

AnyMessageWithText is true if the message isn't nil and its text is not empty

func AnyMyChatMember

func AnyMyChatMember() Predicate

AnyMyChatMember is true if my chat member isn't nil

func AnyPoll

func AnyPoll() Predicate

AnyPoll is true if the poll isn't nil

func AnyPollAnswer

func AnyPollAnswer() Predicate

AnyPollAnswer is true if the poll answer isn't nil

func AnyPreCheckoutQuery

func AnyPreCheckoutQuery() Predicate

AnyPreCheckoutQuery is true if the pre checkout query isn't nil

func AnyShippingQuery

func AnyShippingQuery() Predicate

AnyShippingQuery is true if shipping query isn't nil

func CallbackDataContains

func CallbackDataContains(text string) Predicate

CallbackDataContains is true if the callback query isn't nil, and its data contains specified text

func CallbackDataEqual

func CallbackDataEqual(text string) Predicate

CallbackDataEqual is true if callback query isn't nil, and its data equal to specified text

func CallbackDataEqualFold

func CallbackDataEqualFold(text string) Predicate

CallbackDataEqualFold is true if the callback query isn't nil, and its data equal fold (more general form of case-insensitivity equal) to the specified text

func CallbackDataMatches

func CallbackDataMatches(pattern *regexp.Regexp) Predicate

CallbackDataMatches is true if the callback query isn't nil, and its data matches specified regexp

func CallbackDataPrefix

func CallbackDataPrefix(prefix string) Predicate

CallbackDataPrefix is true if the callback query isn't nil, and its data has specified prefix

func CallbackDataSuffix

func CallbackDataSuffix(suffix string) Predicate

CallbackDataSuffix is true if the callback query isn't nil, and its data has specified suffix

func CommandEqual

func CommandEqual(command string) Predicate

CommandEqual is true if the message isn't nil, and it contains specified command

func CommandEqualArgc

func CommandEqualArgc(command string, argc int) Predicate

CommandEqualArgc is true if the message isn't nil, and it contains specified command with a number of args

func CommandEqualArgv

func CommandEqualArgv(command string, argv ...string) Predicate

CommandEqualArgv is true if the message isn't nil, and it contains specified command and args

func EditedPostTextContains

func EditedPostTextContains(text string) Predicate

EditedPostTextContains is true if edited channel post isn't nil, and its text contains specified text

func EditedPostTextEqual

func EditedPostTextEqual(text string) Predicate

EditedPostTextEqual is true if edited channel post isn't nil, and its text equals to the specified text

func EditedPostTextEqualFold

func EditedPostTextEqualFold(text string) Predicate

EditedPostTextEqualFold is true if edited channel post isn't nil, and its text equal fold (more general form of case-insensitivity equal) to the specified text

func EditedPostTextMatches

func EditedPostTextMatches(pattern *regexp.Regexp) Predicate

EditedPostTextMatches is true if edited channel post isn't nil, and its text matches specified regexp

func EditedPostTextPrefix

func EditedPostTextPrefix(prefix string) Predicate

EditedPostTextPrefix is true if edited channel post isn't nil, and its text has specified prefix

func EditedPostTextSuffix

func EditedPostTextSuffix(suffix string) Predicate

EditedPostTextSuffix is true if edited channel post isn't nil, and its text has specified suffix

func EditedTextContains

func EditedTextContains(text string) Predicate

EditedTextContains is true if the edited message isn't nil, and its text contains specified text

func EditedTextEqual

func EditedTextEqual(text string) Predicate

EditedTextEqual is true if the edited message isn't nil, and its text equals to the specified text

func EditedTextEqualFold

func EditedTextEqualFold(text string) Predicate

EditedTextEqualFold is true if the edited message isn't nil, and its text equal fold (more general form of case-insensitivity equal) to the specified text

func EditedTextMatches

func EditedTextMatches(pattern *regexp.Regexp) Predicate

EditedTextMatches is true if the edited message isn't nil, and its text matches specified regexp

func EditedTextPrefix

func EditedTextPrefix(prefix string) Predicate

EditedTextPrefix is true if the edited message isn't nil, and its text has specified prefix

func EditedTextSuffix

func EditedTextSuffix(suffix string) Predicate

EditedTextSuffix is true if the edited message isn't nil, and its text has specified suffix

func InlineQueryContains

func InlineQueryContains(text string) Predicate

InlineQueryContains is true if inline query isn't nil, and its query contains specified text

func InlineQueryEqual

func InlineQueryEqual(text string) Predicate

InlineQueryEqual is true if inline query isn't nil, and its query equal to specified text

func InlineQueryEqualFold

func InlineQueryEqualFold(text string) Predicate

InlineQueryEqualFold is true if inline query isn't nil, and its query equal fold (more general form of case-insensitivity equal) to the specified text

func InlineQueryMatches

func InlineQueryMatches(pattern *regexp.Regexp) Predicate

InlineQueryMatches is true if inline query isn't nil, and its query matches specified regexp

func InlineQueryPrefix

func InlineQueryPrefix(prefix string) Predicate

InlineQueryPrefix is true if inline query isn't nil, and its query has specified prefix

func InlineQuerySuffix

func InlineQuerySuffix(suffix string) Predicate

InlineQuerySuffix is true if inline query isn't nil, and its query has specified suffix

func Not

func Not(predicate Predicate) Predicate

Not is true if predicate is false

func PostTextContains

func PostTextContains(text string) Predicate

PostTextContains is true if channel post isn't nil, and its text contains specified text

func PostTextEqual

func PostTextEqual(text string) Predicate

PostTextEqual is true if channel post isn't nil, and its text equals to the specified text

func PostTextEqualFold

func PostTextEqualFold(text string) Predicate

PostTextEqualFold is true if channel post isn't nil, and its text equal fold (more general form of case-insensitivity equal) to the specified text

func PostTextMatches

func PostTextMatches(pattern *regexp.Regexp) Predicate

PostTextMatches is true if channel post isn't nil, and its text matches specified regexp

func PostTextPrefix

func PostTextPrefix(prefix string) Predicate

PostTextPrefix is true if channel post isn't nil, and its text has specified prefix

func PostTextSuffix

func PostTextSuffix(suffix string) Predicate

PostTextSuffix is true if channel post isn't nil, and its text has specified suffix

func SuccessPayment

func SuccessPayment() Predicate

SuccessPayment is true if the message isn't nil, and contains success payment

func TextContains

func TextContains(text string) Predicate

TextContains is true if the message isn't nil, and its text contains specified text

func TextEqual

func TextEqual(text string) Predicate

TextEqual is true if the message isn't nil, and its text is equal to the specified text

func TextEqualFold

func TextEqualFold(text string) Predicate

TextEqualFold is true if the message isn't nil, and its text equal fold (more general form of case-insensitivity equal) to the specified text

func TextMatches

func TextMatches(pattern *regexp.Regexp) Predicate

TextMatches is true if the message isn't nil, and its text matches specified regexp

func TextPrefix

func TextPrefix(prefix string) Predicate

TextPrefix is true if the message isn't nil, and its text has specified prefix

func TextSuffix

func TextSuffix(suffix string) Predicate

TextSuffix is true if the message isn't nil, and its text has specified suffix

func Union

func Union(predicates ...Predicate) Predicate

Union is true if at least one of the predicates is true

type ShippingQueryHandler

type ShippingQueryHandler func(bot *tgo.Bot, query tgo.ShippingQuery)

ShippingQueryHandler handles shipping query that came from bot

Jump to

Keyboard shortcuts

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