tg/src/behx/bot.go

87 lines
1.7 KiB
Go
Raw Normal View History

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 14:06:05 +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) {
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,
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
uc := apix.NewUpdate(0)
2023-07-09 01:28:59 +03:00
uc.Timeout = 60
updates := bot.GetUpdatesChan(uc)
2023-07-12 14:06:05 +03:00
chans := make(map[SessionId] chan *Update)
2023-07-09 01:28:59 +03:00
for u := range updates {
2023-07-12 14:20:52 +03:00
var sid SessionId
2023-07-12 14:06:05 +03:00
if u.Message != nil {
// Create new session if the one does not exist
// for this user.
2023-07-12 14:20:52 +03:00
sid = SessionId(u.Message.Chat.ID)
2023-07-12 14:06:05 +03:00
if _, ok := bot.sessions[sid] ; !ok {
bot.sessions.Add(sid)
}
// The "start" command resets the bot
// by executing the Start Action.
if u.Message.IsCommand() {
cmd := u.Message.Command()
if cmd == "start" {
// Getting current session and context.
session := bot.sessions[sid]
ctx := &Context{
B: bot,
Session: session,
}
chn := make(chan *Update)
chans[sid] = chn
// Starting the goroutine for the user.
go ctx.handleUpdateChan(chn)
continue
}
2023-07-09 01:28:59 +03:00
}
2023-07-12 14:20:52 +03:00
} else if u.CallbackQuery != nil {
sid = SessionId(u.CallbackQuery.Message.Chat.ID)
}
chn, ok := chans[sid]
if ok {
2023-07-12 14:06:05 +03:00
chn <- &u
2023-07-12 14:20:52 +03:00
}
2023-07-09 01:28:59 +03:00
}
return nil
}