wizard

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2024 License: MIT Imports: 16 Imported by: 6

Documentation

Overview

Package wizard provides support for field based forms defined by client code. A key-value storage is used to save the state of a form between messages.

To add a form to your github.com/kozalosev/goSadTgBot/base.MessageHandler, it must implement the WizardMessageHandler interface and create a Wizard in its github.com/kozalosev/goSadTgBot/base.MessageHandler.Handle method.

Index

Constants

View Source
const (
	InvalidFieldValueErrorTr     = "wizard.errors.field.invalid.value"
	InvalidFieldValueTypeErrorTr = "wizard.errors.field.invalid.type"
	MissingStateErrorTr          = "wizard.errors.state.missing"
)

localization keys

View Source
const (
	// CallbackDataFieldPrefix is used in routing of callback updates.
	CallbackDataFieldPrefix = "field" + callbackDataSep
)
View Source
const ValidErrNotInListTr = "errors.validation.option.not.in.list"

Variables

This section is empty.

Functions

func CallbackQueryHandler

func CallbackQueryHandler(reqenv *base.RequestEnv, query *tgbotapi.CallbackQuery, resources *Env)

CallbackQueryHandler is a handler for callback updates generated by messages for fields with inline buttons.

func PopulateWizardDescriptors

func PopulateWizardDescriptors(handlers []base.MessageHandler) bool

PopulateWizardDescriptors fills in the map that should be initialized at startup time to prevent the user from receiving the "wizard.errors.state.missing" message.

Types

type Env

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

func NewEnv

func NewEnv(appEnv *base.ApplicationEnv, stateStorage StateStorage) *Env

type FakeStorage

type FakeStorage struct{}

func (FakeStorage) Close

func (FakeStorage) Close() error

func (FakeStorage) DeleteState

func (FakeStorage) DeleteState(int64) error

func (FakeStorage) GetCurrentState

func (FakeStorage) GetCurrentState(int64, Wizard) error

func (FakeStorage) SaveState

func (FakeStorage) SaveState(int64, Wizard) error

type Field

type Field struct {
	Name         string      `json:"name"`
	Data         interface{} `json:"data,omitempty"` // the value
	WasRequested bool        `json:"wasRequested"`
	Type         FieldType   `json:"type"`

	Form *Form `json:"-"`
	// contains filtered or unexported fields
}

type FieldDescriptor

type FieldDescriptor struct {
	Validator FieldValidator

	// if this condition is true, the field will be skipped
	SkipIf SkipCondition

	// keyboard options; you can attach either a reply keyboard or inline one, but not both
	ReplyKeyboardBuilder      ReplyKeyboardBuilder
	InlineKeyboardAnswers     []string
	InlineKeyboardBuilder     InlineKeyboardBuilder
	DisableKeyboardValidation bool
	// contains filtered or unexported fields
}

FieldDescriptor is the description of a concrete field of the form, describing all non-storable parameters. Use FormDescriptor.AddField to create one and attach to a FormDescriptor instance.

func (*FieldDescriptor) InlineButtonCustomizer

func (descriptor *FieldDescriptor) InlineButtonCustomizer(option string, customizer InlineButtonCustomizer) bool

InlineButtonCustomizer is a method for modifying the inline button generated for a specific option. By default, an inline button with callback_data is created. By using this type of customizer, you're able to change this behavior.

type FieldType

type FieldType string
const (
	Auto      FieldType = "<auto>" // will be automatically resolved from the type of message sent by the user
	Text      FieldType = "text"
	Sticker   FieldType = "sticker"
	Image     FieldType = "image"
	Voice     FieldType = "voice"
	Audio     FieldType = "audio"
	Video     FieldType = "video"
	VideoNote FieldType = "video_note"
	Gif       FieldType = "gif"
	Document  FieldType = "document"
	Location  FieldType = "location"
)

type FieldValidator

type FieldValidator func(msg *tgbotapi.Message, lc *loc.Context) error

FieldValidator is, obviously, a validation function. Returned error will be sent to the user and may be a key for the translation mechanism.

type Fields

type Fields []*Field

func (Fields) FindField

func (fs Fields) FindField(name string) *Field

FindField is useful in a FormAction function to get values of the fields.

type File

type File struct {
	ID       string // file_id
	UniqueID string // file_unique_id
	Caption  string // optional, not for all types
	Entities []tgbotapi.MessageEntity
}

File is a representation of Telegram cached files. https://core.telegram.org/bots/api#file

type Form

type Form struct {
	Fields     Fields `json:"fields"`
	Index      int    `json:"index"`      // index of the current field
	WizardType string `json:"wizardType"` // name of the form
	// contains filtered or unexported fields
}

Form is an implementation of the Wizard interface.

func (*Form) AddEmptyField

func (form *Form) AddEmptyField(name string, fieldType FieldType)

func (*Form) AddPrefilledAutoField added in v0.3.1

func (form *Form) AddPrefilledAutoField(name string, msg *tgbotapi.Message)

func (*Form) AddPrefilledField

func (form *Form) AddPrefilledField(name string, value interface{})

func (*Form) AllRequiredFieldsFilled added in v0.3.1

func (form *Form) AllRequiredFieldsFilled() bool

func (*Form) FixDataTypes added in v0.2.0

func (form *Form) FixDataTypes()

FixDataTypes is mandatory for now to cast prefilled Data (Txt) and restored from Redis (map[string]interface{}) to the unified Txt type. Call it before or after PopulateRestored().

func (*Form) PopulateRestored

func (form *Form) PopulateRestored(msg *tgbotapi.Message, resources *Env)

PopulateRestored sets non-storable fields of the form restored from StateStorage.

func (*Form) ProcessNextField

func (form *Form) ProcessNextField(reqenv *base.RequestEnv, msg *tgbotapi.Message)

type FormAction

type FormAction func(reqenv *base.RequestEnv, msg *tgbotapi.Message, fields Fields)

FormAction is a function that will be executed when all of required fields are filled in.

type FormDescriptor

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

FormDescriptor is the description of a wizard, describing all non-storable parameters. Use NewWizardDescriptor to create one.

func NewWizardDescriptor

func NewWizardDescriptor(action FormAction) *FormDescriptor

func (*FormDescriptor) AddField

func (descriptor *FormDescriptor) AddField(name, promptDescriptionOrTrKey string) *FieldDescriptor

type InlineButtonCustomizer

type InlineButtonCustomizer func(btn *tgbotapi.InlineKeyboardButton, f *Field)

InlineButtonCustomizer is a function that allows you to customize the inline button generated for a field prompt. https://core.telegram.org/bots/api#inlinekeyboardbutton

type InlineKeyboardBuilder added in v0.3.2

type InlineKeyboardBuilder func(reqenv *base.RequestEnv, msg *tgbotapi.Message, form *Form) []string

InlineKeyboardBuilder is used to generate variants for the inline keyboard. It can be used instead of InlineKeyboardAnswers when you want to have different sets of buttons depending on the current state of the wizard.

type LocData added in v0.1.1

type LocData struct {
	Latitude  float64
	Longitude float64
}

LocData represents a point on the map. https://core.telegram.org/bots/api#location

type RedisStateStorage

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

RedisStateStorage is an implementation of the StateStorage interface, using Redis as the storage.

func ConnectToRedis

func ConnectToRedis(ctx context.Context, ttl time.Duration, options *redis.Options) RedisStateStorage

ConnectToRedis is a constructor of the RedisStateStorage. - ctx is the application context; - ttl is the lifetime of forms; after this duration the command will be cancelled; - options is the connection options.

func (RedisStateStorage) Close

func (rss RedisStateStorage) Close() error

func (RedisStateStorage) DeleteState

func (rss RedisStateStorage) DeleteState(uid int64) error

func (RedisStateStorage) GetCurrentState

func (rss RedisStateStorage) GetCurrentState(uid int64, dest Wizard) error

func (RedisStateStorage) SaveState

func (rss RedisStateStorage) SaveState(uid int64, wizard Wizard) error

type ReplyKeyboardBuilder

type ReplyKeyboardBuilder func(reqenv *base.RequestEnv, msg *tgbotapi.Message) []string

ReplyKeyboardBuilder is used to generate variants for the reply keyboard, since I use it for fields when the user must choose the option from a result set fetched from the database.

type SkipCondition

type SkipCondition interface {
	ShouldBeSkipped(form *Form) bool
}

SkipCondition is the condition type for [FieldDescriptor.SkipIf] field.

type SkipIfFieldNotEmpty added in v0.2.0

type SkipIfFieldNotEmpty struct {
	Name string
}

SkipIfFieldNotEmpty is another SkipCondition implementation which gives a way to express the intention to fill one of two fields but not both.

func (SkipIfFieldNotEmpty) ShouldBeSkipped added in v0.2.0

func (s SkipIfFieldNotEmpty) ShouldBeSkipped(form *Form) bool

type SkipOnFieldValue

type SkipOnFieldValue struct {
	Name  string
	Value string
}

SkipOnFieldValue is a SkipCondition implementation that skips the field if the value of another field is equal to Value.

func (SkipOnFieldValue) ShouldBeSkipped

func (s SkipOnFieldValue) ShouldBeSkipped(form *Form) bool

type StateStorage

type StateStorage interface {
	GetCurrentState(uid int64, dest Wizard) error
	SaveState(uid int64, wizard Wizard) error
	DeleteState(uid int64) error
	Close() error
}

StateStorage is an abstraction over the connection to some storage which provides methods for saving, restoring and deletion of the states of the wizards.

type Txt added in v0.2.0

type Txt struct {
	Value    string
	Entities []tgbotapi.MessageEntity
}

Txt is a structure for formatted text consisting of non-formatted text and 'entities' https://core.telegram.org/bots/api#messageentity

type Wizard

type Wizard interface {
	// AddEmptyField creates a new empty field of fieldType type.
	AddEmptyField(name string, fieldType FieldType)
	// AddPrefilledField creates a field with already filled in value. It may be useful when some arguments were passed in a command immediately.
	AddPrefilledField(name string, value interface{})
	// AddPrefilledAutoField is supposed for a special case when you want to fill the field with a value of unknown type, determined by the content of some message (ReplyToMessage, for example).
	AddPrefilledAutoField(name string, msg *tgbotapi.Message)
	// AllRequiredFieldsFilled returns true if all required fields are already prefilled.
	AllRequiredFieldsFilled() bool
	// ProcessNextField runs the form machinery. Call this method when all fields were created.
	ProcessNextField(reqenv *base.RequestEnv, msg *tgbotapi.Message)
}

Wizard is another name for a form. Create a Wizard instance in your handler with NewWizard function and add fields to it.

func NewWizard

func NewWizard(handler WizardMessageHandler, fields int) Wizard

NewWizard is a constructor for Wizard. The fields parameter is used only for array initialization.

type WizardMessageHandler

type WizardMessageHandler interface {
	base.MessageHandler

	// GetWizardEnv should return the application environment and an implementation of the storage (an instance of [RedisStateStorage] for example).
	GetWizardEnv() *Env
	// GetWizardDescriptor should return the description of all non-storable parameters of your form.
	GetWizardDescriptor() *FormDescriptor
}

WizardMessageHandler is an extended interface of base.MessageHandler which your handler must implement if you want to use this package facilities

Jump to

Keyboard shortcuts

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