tbcomctl

package module
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2021 License: MIT Imports: 16 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 ErrAlreadyVoted = errors.New("already voted")

Functions

func ButtonMarkup

func ButtonMarkup(b Boter, values []string, maxRowButtons int, cbFn func(*tb.Callback)) *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 added in v0.2.4

func ButtonPatternMarkup(b Boter, values []string, pattern []uint, cbFn func(*tb.Callback)) (*tb.ReplyMarkup, error)

func ChatInfo

func ChatInfo(ch *tb.Chat) string

ChatInfo returns the chat info.

func NewControllerChain

func NewControllerChain(first Controller, cc ...Controller) func(m *tb.Message)

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

func PrivateOnly

func PrivateOnly(fn func(m *tb.Message)) func(*tb.Message)

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

func PrivateOnlyMsg

func PrivateOnlyMsg(b Boter, msg string, fn func(m *tb.Message)) func(*tb.Message)

func Sdump

func Sdump(m interface{}) string

Sdump dumps the structure.

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 BotChecker

type BotChecker interface {
	Boter
	ChatMemberOf(chat *tb.Chat, user *tb.User) (*tb.ChatMember, error)
	ChatByID(id string) (*tb.Chat, error)
}

type BotNotifier

type BotNotifier interface {
	Boter
	Notify(to tb.Recipient, action tb.ChatAction) error
}

type Boter

type Boter interface {
	Handle(endpoint interface{}, handler interface{})
	Send(to tb.Recipient, what interface{}, options ...interface{}) (*tb.Message, error)
	Edit(msg tb.Editable, what interface{}, options ...interface{}) (*tb.Message, error)
	Respond(c *tb.Callback, resp ...*tb.CallbackResponse) error
}

Boter is the interface to send messages.

type BtnCallbackFunc

type BtnCallbackFunc func(ctx context.Context, cb *tb.Callback) 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(m *tb.Message)
	// 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)
	// Bot returns the bot that is used to inialise the controller.
	Bot() Boter
	// 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)

type ErrType

type ErrType int
const (
	TErrNoChange ErrType = iota
	TErrRetry
	TInputError
)

type Error

type Error struct {
	Alert bool
	Msg   string
	Type  ErrType
}

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(m *tb.Message)

func (*Form) OnTextMiddleware

func (fm *Form) OnTextMiddleware(onText func(m *tb.Message)) func(m *tb.Message)

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(b BotNotifier, 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(b BotNotifier, name string, text string, onTextFn MsgErrFunc, opts ...InputOption) *Input

func (*Input) Bot added in v0.2.4

func (c *Input) Bot() Boter

func (*Input) Form

func (c *Input) Form() *Form

func (*Input) Handler

func (ip *Input) Handler(m *tb.Message)

func (*Input) Name

func (c *Input) Name() string

func (*Input) OnTextMw

func (ip *Input) OnTextMw(fn func(m *tb.Message)) func(*tb.Message)

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 added in v0.2.5

type KbdOption func(k *Keyboard)

func KbdOptButtonsInRow added in v0.2.5

func KbdOptButtonsInRow(n int) KbdOption

type Keyboard

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

func NewKeyboard

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

func (*Keyboard) Bot added in v0.2.4

func (c *Keyboard) Bot() Boter

func (*Keyboard) Form

func (c *Keyboard) Form() *Form

func (*Keyboard) InitForLanguages

func (k *Keyboard) InitForLanguages(lang ...string)

InitForLanguages initialises handlers for languages listed.

func (*Keyboard) Markup

func (k *Keyboard) Markup(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 added in v0.2.6

type KeyboardCmd struct {
	Label   BtnLabel
	Handler func(m *tb.Message)
}

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(b Boter, 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(b Boter, name, text string, sendOpts ...interface{}) *Message

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

func (*Message) Bot added in v0.2.4

func (c *Message) Bot() Boter

func (*Message) Form

func (c *Message) Form() *Form

func (*Message) Handler

func (m *Message) Handler(msg *tb.Message)

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(func(m *tb.Message)) func(m *tb.Message)

type MsgErrFunc

type MsgErrFunc func(ctx context.Context, m *tb.Message) 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(b Boter, name string, textFn TextFunc, valuesFn ValuesFunc, callbackFn BtnCallbackFunc, opts ...PicklistOption) *Picklist

NewPicklist creates a new picklist.

func NewPicklistText

func NewPicklistText(b Boter, 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) Bot added in v0.2.4

func (c *Picklist) Bot() Boter

func (*Picklist) Callback

func (p *Picklist) Callback(cb *tb.Callback)

func (*Picklist) Form

func (c *Picklist) Form() *Form

func (*Picklist) Handler

func (p *Picklist) Handler(m *tb.Message)

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 PickOptBtnPattern added in v0.2.4

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(b Boter, callbackFn func(cb *tb.Callback), 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(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(b Boter, fn RatingFunc, opts ...RBOption) *Rating

func (*Rating) Bot added in v0.2.4

func (c *Rating) Bot() Boter

func (*Rating) Form

func (c *Rating) Form() *Form

func (*Rating) Markup

func (rb *Rating) Markup(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(b BotChecker, name string, textFn TextFunc, chats []string, 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) Bot added in v0.2.4

func (c *SubChecker) Bot() Boter

func (*SubChecker) Form

func (c *SubChecker) Form() *Form

func (*SubChecker) Handler

func (sc *SubChecker) Handler(m *tb.Message)

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)

TextFunc 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