]> git.jsancho.org Git - midgaard_bot.git/blobdiff - sessions.go
Sessions working
[midgaard_bot.git] / sessions.go
index a0ff861d591fdee13a3825cbf867879cd874ae36..7dd2df3c1b448d7f0e22742451978c23585d0d18 100644 (file)
@@ -1,18 +1,24 @@
 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() {
+func initSessions(ctx context.Context) error {
        sessions = make(map[int64]*Session)
+       sessionsCtx = ctx
+       return nil
 }
 
 func getSession(chat *tgbotapi.Chat) *Session {
@@ -24,7 +30,30 @@ func getSession(chat *tgbotapi.Chat) *Session {
 }
 
 func newSession(chat *tgbotapi.Chat) *Session {
-       session := Session{chat, make(chan tgbotapi.Message)}
+       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
+}