Added way to store custom information for each user.

This commit is contained in:
Andrey Parhomenko 2023-07-12 14:59:07 +03:00
parent 521709f87d
commit 6bbea7c6d9
3 changed files with 33 additions and 8 deletions

View file

@ -2,7 +2,7 @@ package behx
import (
apix "github.com/go-telegram-bot-api/telegram-bot-api/v5"
//"fmt"
"fmt"
)
// The type represents way to interact with user in
@ -71,6 +71,12 @@ func (c *Context) ChangeScreen(screenId ScreenId) error {
// Sends to the user specified text.
func (c *Context) Send(text string) error {
return nil
msg := apix.NewMessage(c.Id.ToTelegram(), text)
_, err := c.B.Send(msg)
return err
}
func (c *Context) Sendf(format string, v ...any) error {
return c.Send(fmt.Sprintf(format, v...))
}

View file

@ -21,6 +21,9 @@ type Session struct {
PreviousScreenId ScreenId
// The currently showed on display keyboard.
KeyboardId KeyboardId
// Custom data for each user.
V map[string] any
}
// The type represents map of sessions using
@ -31,6 +34,7 @@ type SessionMap map[SessionId] *Session
func NewSession(id SessionId) *Session {
return &Session{
Id: id,
V: make(map[string] any),
}
}

View file

@ -11,14 +11,21 @@ import (
var rootKbd = behx.NewKeyboard(
behx.NewButtonRow(
behx.NewButton(
"1",
"Increment",
behx.NewCustomAction(func(c *behx.Context){
log.Println("pressed the button!")
counter := c.V["counter"].(*int)
*counter++
c.Sendf("%d", *counter)
}),
),
behx.NewButton(
"Decrement",
behx.NewCustomAction(func(c *behx.Context){
counter := c.V["counter"].(*int)
*counter--
c.Sendf("%d", *counter)
}),
),
behx.NewButton("PRESS ME 2", behx.NewCustomAction(func(c *behx.Context){
log.Println("pressed another button!")
})),
),
behx.NewButtonRow(
behx.NewButton("To second screen", behx.NewScreenChange("second")),
@ -68,7 +75,15 @@ var secondScreen = behx.NewScreen(
)
var behaviour = behx.NewBehaviour(
behx.NewScreenChange("start"),
behx.NewCustomAction(func(c *behx.Context){
// This way we provide counter for EACH user.
c.V["counter"] = new(int)
// Do NOT forget to change to some of the screens
// since they are the ones who provide behaviour
// definition.
c.ChangeScreen("start")
}),
behx.ScreenMap{
"start": startScreen,
"second": secondScreen,