From 6bbea7c6d9523b7b6fb48187b2fe757a0b5d3bff Mon Sep 17 00:00:00 2001 From: surdeus Date: Wed, 12 Jul 2023 14:59:07 +0300 Subject: [PATCH] Added way to store custom information for each user. --- src/behx/context.go | 10 ++++++++-- src/behx/session.go | 4 ++++ src/cmd/test/main.go | 27 +++++++++++++++++++++------ 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/behx/context.go b/src/behx/context.go index 2300569..510c410 100644 --- a/src/behx/context.go +++ b/src/behx/context.go @@ -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...)) } diff --git a/src/behx/session.go b/src/behx/session.go index 3f5c421..f012494 100644 --- a/src/behx/session.go +++ b/src/behx/session.go @@ -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), } } diff --git a/src/cmd/test/main.go b/src/cmd/test/main.go index 8c92736..d0ab2fd 100644 --- a/src/cmd/test/main.go +++ b/src/cmd/test/main.go @@ -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,