From fc91490c18d1522744e76510321f190652471f0e Mon Sep 17 00:00:00 2001 From: surdeus Date: Sat, 19 Aug 2023 13:34:21 +0300 Subject: [PATCH] Added a global bot value to make it usable with databases etc. --- cmd/test/main.go | 13 +++++++++++++ tg/bot.go | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/cmd/test/main.go b/cmd/test/main.go index 3c8548a..917ea51 100644 --- a/cmd/test/main.go +++ b/cmd/test/main.go @@ -8,6 +8,10 @@ import ( "github.com/mojosa-software/got/tg" ) +type BotData struct { + Name string +} + type UserData struct { Counter int } @@ -158,6 +162,12 @@ var beh = tg.NewBehaviour(). img := tg.NewFile("media/cat.jpg").Image().Caption("A cat!") c.Send(img) }), + tg.NewCommand("botname"). + Desc("get the bot name"). + ActionFunc(func(c *tg.Context) { + bd := c.Bot.Value().(*BotData) + c.Sendf("My name is %q", bd.Name) + }), ) func mutateMessage(fn func(string) string) tg.ActionFunc { @@ -201,6 +211,9 @@ func main() { bot = bot. WithBehaviour(beh). WithGroupBehaviour(gBeh). + WithValue(&BotData{ + Name: "Jay", + }). Debug(true) log.Printf("Authorized on account %s", bot.Api.Self.UserName) diff --git a/tg/bot.go b/tg/bot.go index 774642b..e158340 100644 --- a/tg/bot.go +++ b/tg/bot.go @@ -24,6 +24,7 @@ type Bot struct { channelBehaviour *ChannelBehaviour sessions SessionMap groupSessions GroupSessionMap + value any } // Return the new bot with empty sessions and behaviour. @@ -38,6 +39,19 @@ func NewBot(token string) (*Bot, error) { }, nil } +// Set the custom global value for the bot, +// so it can be accessed from the callback +// functions. +func (bot *Bot) WithValue(v any) *Bot { + bot.value = v + return bot +} + +// Get the global bot value. +func (bot *Bot) Value() any { + return bot.value +} + func (bot *Bot) Debug(debug bool) *Bot { bot.Api.Debug = debug return bot