Added a global bot value to make it usable with databases etc.

This commit is contained in:
Andrey Parhomenko 2023-08-19 13:34:21 +03:00
parent cdc1a737b7
commit fc91490c18
2 changed files with 27 additions and 0 deletions

View file

@ -8,6 +8,10 @@ import (
"github.com/mojosa-software/got/tg" "github.com/mojosa-software/got/tg"
) )
type BotData struct {
Name string
}
type UserData struct { type UserData struct {
Counter int Counter int
} }
@ -158,6 +162,12 @@ var beh = tg.NewBehaviour().
img := tg.NewFile("media/cat.jpg").Image().Caption("A cat!") img := tg.NewFile("media/cat.jpg").Image().Caption("A cat!")
c.Send(img) 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 { func mutateMessage(fn func(string) string) tg.ActionFunc {
@ -201,6 +211,9 @@ func main() {
bot = bot. bot = bot.
WithBehaviour(beh). WithBehaviour(beh).
WithGroupBehaviour(gBeh). WithGroupBehaviour(gBeh).
WithValue(&BotData{
Name: "Jay",
}).
Debug(true) Debug(true)
log.Printf("Authorized on account %s", bot.Api.Self.UserName) log.Printf("Authorized on account %s", bot.Api.Self.UserName)

View file

@ -24,6 +24,7 @@ type Bot struct {
channelBehaviour *ChannelBehaviour channelBehaviour *ChannelBehaviour
sessions SessionMap sessions SessionMap
groupSessions GroupSessionMap groupSessions GroupSessionMap
value any
} }
// Return the new bot with empty sessions and behaviour. // Return the new bot with empty sessions and behaviour.
@ -38,6 +39,19 @@ func NewBot(token string) (*Bot, error) {
}, nil }, 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 { func (bot *Bot) Debug(debug bool) *Bot {
bot.Api.Debug = debug bot.Api.Debug = debug
return bot return bot