X-Git-Url: https://git.jsancho.org/?p=midgaard_bot.git;a=blobdiff_plain;f=sessions.go;h=7dd2df3c1b448d7f0e22742451978c23585d0d18;hp=dad67abcd87b9047877f4e543eaf67d102f1bbd1;hb=54d3318115d6fd32364f5993ff67d0461c162aef;hpb=04dc2e081ed05a8e6cc77596ff0f694073283d82 diff --git a/sessions.go b/sessions.go index dad67ab..7dd2df3 100644 --- a/sessions.go +++ b/sessions.go @@ -1,10 +1,59 @@ package main import ( + "context" + "log" + "github.com/go-telegram-bot-api/telegram-bot-api" ) type Session struct { Chat *tgbotapi.Chat - Msgbox chan tgbotapi.Message + Input chan *tgbotapi.Message +} + +var sessions map[int64]*Session +var sessionsCtx context.Context + +func initSessions(ctx context.Context) error { + sessions = make(map[int64]*Session) + sessionsCtx = ctx + return nil +} + +func getSession(chat *tgbotapi.Chat) *Session { + session, ok := sessions[chat.ID] + if !ok { + session = newSession(chat) + } + return session +} + +func newSession(chat *tgbotapi.Chat) *Session { + session := Session{chat, make(chan *tgbotapi.Message)} + sessions[chat.ID] = &session + startSession(&session) + return &session +} + +func startSession(session *Session) { + ctx, _ := context.WithCancel(sessionsCtx) + go func() { + for { + select { + case msg := <-session.Input: + log.Printf("[%s] %s", msg.From.UserName, msg.Text) + + newMsg := tgbotapi.NewMessage(msg.Chat.ID, msg.Text) + newMsg.ReplyToMessageID = msg.MessageID + sendToTelegram(newMsg) + case <-ctx.Done(): + return + } + } + }() +} + +func sendToSession(session *Session, message *tgbotapi.Message) { + session.Input <- message }