2023-07-09 01:28:59 +03:00
|
|
|
package behx
|
|
|
|
|
|
|
|
import (
|
|
|
|
apix "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
2023-07-12 02:02:33 +03:00
|
|
|
"log"
|
2023-07-09 01:28:59 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// The wrapper around Telegram API.
|
|
|
|
type Bot struct {
|
|
|
|
*apix.BotAPI
|
|
|
|
*Behaviour
|
|
|
|
sessions SessionMap
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return the new bot for running the Behaviour.
|
|
|
|
func NewBot(token string, beh *Behaviour, sessions SessionMap) (*Bot, error) {
|
2023-07-12 00:33:51 +03:00
|
|
|
bot, err := apix.NewBotAPI(token)
|
2023-07-09 01:28:59 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make new sessions if no current are provided.
|
|
|
|
if sessions == nil {
|
|
|
|
sessions = make(SessionMap)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Bot{
|
|
|
|
BotAPI: bot,
|
|
|
|
Behaviour: beh,
|
2023-07-12 00:33:51 +03:00
|
|
|
sessions: make(SessionMap),
|
2023-07-09 01:28:59 +03:00
|
|
|
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run the bot with the Behaviour.
|
|
|
|
func (bot *Bot) Run() error {
|
|
|
|
bot.Debug = true
|
|
|
|
|
2023-07-12 00:33:51 +03:00
|
|
|
uc := apix.NewUpdate(0)
|
2023-07-09 01:28:59 +03:00
|
|
|
uc.Timeout = 60
|
|
|
|
|
|
|
|
updates := bot.GetUpdatesChan(uc)
|
|
|
|
|
|
|
|
for u := range updates {
|
2023-07-12 00:33:51 +03:00
|
|
|
|
2023-07-09 01:28:59 +03:00
|
|
|
// Create new session if the one does not exist
|
|
|
|
// for this user.
|
|
|
|
sid := SessionId(u.Message.Chat.ID)
|
2023-07-12 00:33:51 +03:00
|
|
|
if _, ok := bot.sessions[sid] ; !ok {
|
2023-07-09 01:28:59 +03:00
|
|
|
bot.sessions.Add(sid)
|
|
|
|
}
|
|
|
|
|
2023-07-12 00:33:51 +03:00
|
|
|
session := bot.sessions[sid]
|
|
|
|
ctx := &Context{
|
2023-07-09 01:28:59 +03:00
|
|
|
B: bot,
|
|
|
|
S: session,
|
|
|
|
}
|
|
|
|
|
|
|
|
// The "start" command resets the bot
|
|
|
|
// by executing the Start Action.
|
2023-07-12 00:33:51 +03:00
|
|
|
if u.Message.IsCommand() {
|
2023-07-09 01:28:59 +03:00
|
|
|
cmd := u.Message.Command()
|
|
|
|
if cmd == "start" {
|
|
|
|
bot.Start.Act(ctx)
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2023-07-12 00:33:51 +03:00
|
|
|
|
|
|
|
screen := bot.Screens[session.CurrentScreenId]
|
2023-07-12 02:02:33 +03:00
|
|
|
err := screen.Render(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("screen rendering:", err)
|
|
|
|
}
|
2023-07-09 01:28:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|