tbcomctl

package module
v3.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2021 License: MIT Imports: 17 Imported by: 0

README

===================================
Common Controls Library for Telebot
===================================

Library provides common controls to use with Telebot_ library.

* Picklist
* Rating
* Post Buttons
* Keyboard
* Middleware
* Helper functions for logging.

.. _Telebot: https://github.com/tucnak/telebot

Documentation

Overview

Package tbcomctl provides common controls for telegram bots.

Index

Constants

View Source
const (
	MsgUnexpected  = "🤯 (500) Unexpected error occurred."
	MsgRetry       = "Incorrect choice."
	MsgChooseVal   = "Choose value from the list:"
	MsgOK          = "✅"
	MsgVoteCounted = "✅ Vote counted."
	MsgSubCheck    = "? Check subscription >>"
	MsgSubNoSub    = "❌ You're not subscribed to one or more of the required channels."
)
View Source
const (
	FallbackLang = "en-US"
)
View Source
const (
	None = "<none>"
)

Variables

View Source
var (
	// ErrRetry should be returned by CallbackFunc if the retry should be performed.
	ErrRetry = &Error{Type: TErrRetry, Msg: "retry", Alert: true}
	// ErrNoChange should be returned if the user picked the same value as before, and no update needed.
	ErrNoChange = &Error{Type: TErrNoChange, Msg: "no change"}
)
View Source
var BackPressed = errors.New("back")

BackPressed is a special type of error indicating that callback handler should call the previous handler.

View Source
var ErrAlreadyVoted = errors.New("already voted")

Functions

func ButtonMarkup

func ButtonMarkup(c tb.Context, values []string, maxRowButtons int, cbFn func(c tb.Context) error) *tb.ReplyMarkup

ButtonMarkup returns the button markup for the message. It creates handlers for all the buttons assigning the cbFn callback function to each of them. Values must be unique. maxRowButtons is maximum number of buttons in a row.

func ButtonPatternMarkup

func ButtonPatternMarkup(c tb.Context, values []string, pattern []uint, cbFn func(c tb.Context) error) (*tb.ReplyMarkup, error)

func ChatInfo

func ChatInfo(ch *tb.Chat) string

ChatInfo returns the chat info.

func NewControllerChain

func NewControllerChain(first Controller, cc ...Controller) tb.HandlerFunc

func NewInputError

func NewInputError(msg string) error

NewInputError returns an input error with msg.

func NoDebugLogger

func NoDebugLogger()

NoDebugLogger switches off debug messages.

func NoLogging

func NoLogging()

NoLogging switches off default logging, if you're brave.

func Nvlstring

func Nvlstring(s string, ss ...string) string

func Printer

func Printer(lang string, fallback ...string) *message.Printer

Printer returns the Message Printer for the desired lang. If the lang is not valid, the fallback languages will be used, if set.

func PrinterContext added in v3.0.1

func PrinterContext(c tb.Context, fallback ...string) *message.Printer

PrinterContext returns the Message Printer set to the language of the sender. It is a convenience wrapper around Printer.

func PrivateOnly

func PrivateOnly(fn tb.HandlerFunc) tb.HandlerFunc

PrivateOnly is the middleware that restricts the handler to only private messages.

func PrivateOnlyMsg

func PrivateOnlyMsg(msg string, fn tb.HandlerFunc) tb.HandlerFunc

func Sdump

func Sdump(m interface{}) string

Sdump dumps the structure.

func SenderInfo

func SenderInfo(c tb.Context) string

SenderInfo is the convenience function to log the sender info in the context.

func SetDebugLogger

func SetDebugLogger(l Logger)

SetDebugLogger sets the debug logger which is used to output debug messages, if you must. By default, debug logging is disabled.

func SetLogger

func SetLogger(l Logger)

SetLogger sets the current logger.

func Userinfo

func Userinfo(u *tb.User) string

Userinfo returns the user info.

func WithController

func WithController(ctx context.Context, ctrl Controller) context.Context

Types

type BtnCallbackFunc

type BtnCallbackFunc func(ctx context.Context, c tb.Context) error

BtnCallbackFunc is being called once the user picks the value, it should return error if the value is incorrect, or ErrRetry if the retry should be performed.

type BtnLabel

type BtnLabel string

type Button

type Button struct {
	Name  string `json:"n"`
	Value int    `json:"v"`
}

func (*Button) String

func (ri *Button) String() string

type Controller

type Controller interface {
	// Handler is the controller's message handler.
	Handler(c tb.Context) error
	// Name returns the name of the control assigned to it on creation.  When
	// Controller is a part of a form, one can call Form.Controller(name) method
	// to get the controller.
	Name() string
	// SetNext sets the next handler, when control is part of a form.
	SetNext(Controller)
	// SetPrev sets the previous handler.
	SetPrev(Controller)
	// SetForm assigns the form to the controller, this will allow controller to
	// address other controls in a form by name.
	SetForm(*Form)
	// Form returns the form associated with the controller.
	Form() *Form
	// Value returns the value stored in the controller for the recipient.
	Value(recipient string) (string, bool)
	// OutgoingID should return the value of the outgoing message ID for the
	// user and true if the message is present or false otherwise.
	OutgoingID(recipient string) (int, bool)
}

Controller is the interface that some of the common controls implement. Controllers can be chained together

func ControllerFromCtx

func ControllerFromCtx(ctx context.Context) (Controller, bool)

type ErrFunc

type ErrFunc func(ctx context.Context, m *tb.Message, err error)

ErrFunc is the error processing function.

type ErrType

type ErrType int

ErrType is the type of error returned by the callback functions.

const (
	TErrNoChange ErrType = iota // there has been no change to the selection
	TErrRetry                   // error of this type will ask user to retry the selection or input
	TInputError                 // tell user that there was an input error (user-error)
)

type Error

type Error struct {
	Alert bool
	Msg   string
	Type  ErrType
}

Error is the type of error returned by the input-processing callback functions

func (*Error) Error

func (e *Error) Error() string

type Form

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

func NewForm

func NewForm(ctrls ...Controller) *Form

func (*Form) Controller

func (fm *Form) Controller(name string) (Controller, bool)

Controller returns the Form Controller by it's name.

func (*Form) Data

func (fm *Form) Data(r tb.Recipient) map[string]string

Data returns form data for the recipient.

func (*Form) Handler

func (fm *Form) Handler(c tb.Context) error

func (*Form) OnTextMiddleware

func (fm *Form) OnTextMiddleware(onText tb.HandlerFunc) tb.HandlerFunc

OnTextMiddleware returns the middleware for OnText handler.

func (*Form) SetOverwrite

func (fm *Form) SetOverwrite(b bool) *Form

SetOverwrite sets the overwrite flag on all controllers within the form.

func (*Form) SetRemoveButtons

func (fm *Form) SetRemoveButtons(b bool) *Form

SetRemoveButtons sets the remove buttons flag on all controllers within the form.

func (*Form) Value

func (fm *Form) Value(ctrlName, recipient string) (string, bool)

Value returns the form control value for recipient by name

type Input

type Input struct {

	// UniqName is the unique name of the field (used to create pipelines, not
	// shown to the user)
	UniqName string
	// OnTextFn is the message callback function called when user responds.  If
	// it returns the error, user will be informed about it.
	OnTextFn MsgErrFunc
	// contains filtered or unexported fields
}

func NewInput

func NewInput(name string, textFn TextFunc, onTextFn MsgErrFunc, opts ...InputOption) *Input

NewInput text creates a new text input, optionally chaining with the `next` handler. One must use Handle as a handler for bot endpoint, and then hook the OnText to OnTextMw. msgFn is the function that should produce the text that user initially sees, onTextFn is the function that should process the user input. It should return an error if the user input is not accepted, and then user is offered to retry. It can format the return error with fmt.Errorf, as this is what user will see. next is allowed to be nil.

func NewInputText

func NewInputText(name string, text string, onTextFn MsgErrFunc, opts ...InputOption) *Input

func (*Input) Form

func (c *Input) Form() *Form

func (*Input) Handler

func (ip *Input) Handler(c tb.Context) error

func (*Input) Name

func (c *Input) Name() string

func (*Input) OnTextMw

func (ip *Input) OnTextMw(fn tb.HandlerFunc) tb.HandlerFunc

OnTextMw returns the middleware that should wrap the OnText handler. It will process the message only if control awaits for this particular user input.

func (*Input) OutgoingID

func (c *Input) OutgoingID(recipient string) (int, bool)

OutgoingID returns the controller's outgoing message ID for the user.

func (*Input) SetForm

func (c *Input) SetForm(fm *Form)

func (*Input) SetNext

func (c *Input) SetNext(ctrl Controller)

SetNext sets next controller in the chain.

func (*Input) SetPrev

func (c *Input) SetPrev(ctrl Controller)

SetPrev sets the previous controller in the chain.

func (*Input) SetValue

func (c *Input) SetValue(recipient string, value string)

SetValue sets the Controller value.

func (*Input) Value

func (c *Input) Value(recipient string) (string, bool)

Value returns the Controller value for the recipient.

type InputOption

type InputOption func(*Input)

func IOptNoReply

func IOptNoReply(b bool) InputOption

func IOptPrivateOnly

func IOptPrivateOnly(b bool) InputOption

type KbdOption

type KbdOption func(k *Keyboard)

func KbdOptButtonsInRow

func KbdOptButtonsInRow(n int) KbdOption

type Keyboard

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

func NewKeyboard

func NewKeyboard(cmds KeyboardCommands, opts ...KbdOption) *Keyboard

func (*Keyboard) Form

func (c *Keyboard) Form() *Form

func (*Keyboard) InitForLanguages

func (k *Keyboard) InitForLanguages(b *tb.Bot, lang ...string)

InitForLanguages initialises handlers for languages listed.

func (*Keyboard) Markup

func (k *Keyboard) Markup(b *tb.Bot, lang string) *tb.ReplyMarkup

Markup returns the markup to be sent to user.

func (*Keyboard) Name

func (c *Keyboard) Name() string

func (*Keyboard) OutgoingID

func (c *Keyboard) OutgoingID(recipient string) (int, bool)

OutgoingID returns the controller's outgoing message ID for the user.

func (*Keyboard) SetForm

func (c *Keyboard) SetForm(fm *Form)

func (*Keyboard) SetNext

func (c *Keyboard) SetNext(ctrl Controller)

SetNext sets next controller in the chain.

func (*Keyboard) SetPrev

func (c *Keyboard) SetPrev(ctrl Controller)

SetPrev sets the previous controller in the chain.

func (*Keyboard) SetValue

func (c *Keyboard) SetValue(recipient string, value string)

SetValue sets the Controller value.

func (*Keyboard) Value

func (c *Keyboard) Value(recipient string) (string, bool)

Value returns the Controller value for the recipient.

type KeyboardCmd

type KeyboardCmd struct {
	Label   BtnLabel
	Handler tb.HandlerFunc
}

type KeyboardCommands

type KeyboardCommands []KeyboardCmd

type Logger

type Logger interface {
	Print(v ...interface{})
	Println(v ...interface{})
	Printf(format string, a ...interface{})
}

Logger is the interface for logging.

func GetLogger

func GetLogger() Logger

GetLogger returns current logger.

type Message

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

Message is the controller that sends a message.

func NewMessage

func NewMessage(name string, textfn TextFunc, sendOpts ...interface{}) *Message

NewMessage creates new Message Controller. One must pass Bot instance, name of the controller, text function that returns the desired message and optionally any sendOpts that will be supplied to telebot.Bot.Send.

func NewMessageText

func NewMessageText(name, text string, sendOpts ...interface{}) *Message

NewMessageText is a convenience wrapper for NewMessage with a fixed text.

func (*Message) Form

func (c *Message) Form() *Form

func (*Message) Handler

func (m *Message) Handler(c tb.Context) error

Handler is the Message controller's message handler.

func (*Message) Name

func (c *Message) Name() string

func (*Message) OutgoingID

func (c *Message) OutgoingID(recipient string) (int, bool)

OutgoingID returns the controller's outgoing message ID for the user.

func (*Message) SetForm

func (c *Message) SetForm(fm *Form)

func (*Message) SetNext

func (c *Message) SetNext(ctrl Controller)

SetNext sets next controller in the chain.

func (*Message) SetPrev

func (c *Message) SetPrev(ctrl Controller)

SetPrev sets the previous controller in the chain.

func (*Message) SetValue

func (c *Message) SetValue(recipient string, value string)

SetValue sets the Controller value.

func (*Message) Value

func (c *Message) Value(recipient string) (string, bool)

Value returns the Controller value for the recipient.

type MiddlewareFunc

type MiddlewareFunc func(tb.HandlerFunc) tb.HandlerFunc

MiddlewareFunc is the function that wraps a telebot handler and returns a handler.

type MsgErrFunc

type MsgErrFunc func(ctx context.Context, c tb.Context) error

MsgErrFunc is the function that processes the user input. If the input is invalid, it should return InputError with the message, then the user is offered to retry the input.

type PBOption

type PBOption func(*PostButtons)

func PBOptMaxButtons

func PBOptMaxButtons(n int) PBOption

type Picklist

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

func NewPicklist

func NewPicklist(name string, textFn TextFunc, valuesFn ValuesFunc, callbackFn BtnCallbackFunc, opts ...PicklistOption) *Picklist

NewPicklist creates a new picklist.

func NewPicklistText

func NewPicklistText(name string, text string, values []string, callbackFn BtnCallbackFunc, opts ...PicklistOption) *Picklist

NewPicklistText is a convenience function to return picklist with fixed text and values.

func (*Picklist) Callback

func (p *Picklist) Callback(c tb.Context) error

func (*Picklist) Form

func (c *Picklist) Form() *Form

func (*Picklist) Handler

func (p *Picklist) Handler(c tb.Context) error

func (*Picklist) Name

func (c *Picklist) Name() string

func (*Picklist) OutgoingID

func (c *Picklist) OutgoingID(recipient string) (int, bool)

OutgoingID returns the controller's outgoing message ID for the user.

func (*Picklist) SetForm

func (c *Picklist) SetForm(fm *Form)

func (Picklist) SetMaxButtons

func (b Picklist) SetMaxButtons(n int)

func (*Picklist) SetNext

func (c *Picklist) SetNext(ctrl Controller)

SetNext sets next controller in the chain.

func (*Picklist) SetPrev

func (c *Picklist) SetPrev(ctrl Controller)

SetPrev sets the previous controller in the chain.

func (*Picklist) SetValue

func (c *Picklist) SetValue(recipient string, value string)

SetValue sets the Controller value.

func (*Picklist) Value

func (c *Picklist) Value(recipient string) (string, bool)

Value returns the Controller value for the recipient.

type PicklistOption

type PicklistOption func(p *Picklist)

func PickOptBtnBack added in v3.0.2

func PickOptBtnBack(textFn TextFunc) PicklistOption

func PickOptBtnBackWithText added in v3.0.2

func PickOptBtnBackWithText(s string) PicklistOption

func PickOptBtnPattern

func PickOptBtnPattern(pattern []uint) PicklistOption

PickOptBtnPattern sets the inline markup button pattern. Each unsigned integer in the pattern represents the number of buttons shown on each of the rows.

Example:

pattern: []uint{1, 2, 3}
will produce the following markup for the picklist choices

+-------------------+
| Picklist text     |
+-------------------+
|     button 1      |
+---------+---------+
| button 2| button 3|
+------+--+---+-----+
| btn4 | btn5 | btn6|
+------+------+-----+

func PickOptErrFunc

func PickOptErrFunc(fn ErrFunc) PicklistOption

func PickOptFallbackLang

func PickOptFallbackLang(lang string) PicklistOption

func PickOptMaxInlineButtons

func PickOptMaxInlineButtons(n int) PicklistOption

func PickOptNoUpdate

func PickOptNoUpdate(b bool) PicklistOption

PickOptNoUpdate sets the No Update option. If No Update is set, the text is not updated once the user makes their choice.

func PickOptOverwrite

func PickOptOverwrite(b bool) PicklistOption

func PickOptPrivateOnly

func PickOptPrivateOnly(b bool) PicklistOption

func PickOptRemoveButtons

func PickOptRemoveButtons(b bool) PicklistOption

PickOptRemoveButtons set the Remove Buttons option. If Remove Buttons is set, the inline buttons will be removed once the user make the choice.

type PostButtons

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

func NewPostButtons

func NewPostButtons(callbackFn func(c tb.Context) error, opts ...PBOption) *PostButtons

NewPostButtons creates an instance of PostButtons. The callbackFunction is the function that will be assigned and called for each button press, so it should handle all possible values.

func (*PostButtons) Markup

func (pb *PostButtons) Markup(c tb.Context, labels []string, pattern ...uint) (*tb.ReplyMarkup, error)

Markup returns the markup with buttons labeled with labels.

func (PostButtons) SetMaxButtons

func (b PostButtons) SetMaxButtons(n int)

type RBOption

type RBOption func(*Rating)

func RBOptShowPostRating

func RBOptShowPostRating(b bool) RBOption

RBOptShowPostRating enables counter of total upvotes/downvotes.

func RBOptShowVoteCounter

func RBOptShowVoteCounter(b bool) RBOption

RBOptShowVoteCounter enables post rating between up/down vote buttons

type Rating

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

Rating is a struct for attaching post rating.

func NewRating

func NewRating(fn RatingFunc, opts ...RBOption) *Rating

func (*Rating) Form

func (c *Rating) Form() *Form

func (*Rating) Markup

func (rb *Rating) Markup(b *tb.Bot, btns [2]Button) *tb.ReplyMarkup

func (*Rating) Name

func (c *Rating) Name() string

func (*Rating) OutgoingID

func (c *Rating) OutgoingID(recipient string) (int, bool)

OutgoingID returns the controller's outgoing message ID for the user.

func (*Rating) SetForm

func (c *Rating) SetForm(fm *Form)

func (*Rating) SetNext

func (c *Rating) SetNext(ctrl Controller)

SetNext sets next controller in the chain.

func (*Rating) SetPrev

func (c *Rating) SetPrev(ctrl Controller)

SetPrev sets the previous controller in the chain.

func (*Rating) SetValue

func (c *Rating) SetValue(recipient string, value string)

SetValue sets the Controller value.

func (*Rating) Value

func (c *Rating) Value(recipient string) (string, bool)

Value returns the Controller value for the recipient.

type RatingFunc

type RatingFunc func(tb.Editable, *tb.User, int) ([2]Button, error)

RatingFunc is the function called by callback, given the message, user and the button index it should update the records and return the new buttons with updated values for the posting, it must maintain count of votes inhouse.

type RatingType

type RatingType int

type SCOption

type SCOption func(sc *SubChecker)

func SCOptFallbackLang

func SCOptFallbackLang(lang string) SCOption

func SCOptShowList

func SCOptShowList(b bool) SCOption

type StoredMessage

type StoredMessage struct {
	MessageID string
	ChatID    int64
}

func (StoredMessage) MessageSig

func (m StoredMessage) MessageSig() (string, int64)

type SubChecker

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

SubChecker is controller to check the chat subscription.

func NewSubChecker

func NewSubChecker(name string, textFn TextFunc, chats []int64, opts ...SCOption) *SubChecker

NewSubChecker creates new subscription checker that checks the subscription on the desired channels. Boter must be added to channels for this to work.

func (*SubChecker) Form

func (c *SubChecker) Form() *Form

func (*SubChecker) Handler

func (sc *SubChecker) Handler(c tb.Context) error

func (*SubChecker) Name

func (c *SubChecker) Name() string

func (*SubChecker) OutgoingID

func (c *SubChecker) OutgoingID(recipient string) (int, bool)

OutgoingID returns the controller's outgoing message ID for the user.

func (*SubChecker) SetForm

func (c *SubChecker) SetForm(fm *Form)

func (*SubChecker) SetNext

func (c *SubChecker) SetNext(ctrl Controller)

SetNext sets next controller in the chain.

func (*SubChecker) SetPrev

func (c *SubChecker) SetPrev(ctrl Controller)

SetPrev sets the previous controller in the chain.

func (*SubChecker) SetValue

func (c *SubChecker) SetValue(recipient string, value string)

SetValue sets the Controller value.

func (*SubChecker) Value

func (c *SubChecker) Value(recipient string) (string, bool)

Value returns the Controller value for the recipient.

type TextFunc

type TextFunc func(ctx context.Context, u *tb.User) (string, error)

TextFunc returns formatted text, possibly personalised for user u.

func TextFn

func TextFn(msg string) TextFunc

TextFn wraps the message in a TextFunc.

type ValuesFunc

type ValuesFunc func(ctx context.Context, u *tb.User) ([]string, error)

ValuesFunc returns values for inline buttons, possibly personalised for user u.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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