]> git.jsancho.org Git - midgaard_bot.git/blob - sessions.go
Sessions working
[midgaard_bot.git] / sessions.go
1 package main
2
3 import (
4         "context"
5         "log"
6
7         "github.com/go-telegram-bot-api/telegram-bot-api"
8 )
9
10 type Session struct {
11         Chat *tgbotapi.Chat
12         Input chan *tgbotapi.Message
13 }
14
15 var sessions map[int64]*Session
16 var sessionsCtx context.Context
17
18 func initSessions(ctx context.Context) error {
19         sessions = make(map[int64]*Session)
20         sessionsCtx = ctx
21         return nil
22 }
23
24 func getSession(chat *tgbotapi.Chat) *Session {
25         session, ok := sessions[chat.ID]
26         if !ok {
27                 session = newSession(chat)
28         }
29         return session
30 }
31
32 func newSession(chat *tgbotapi.Chat) *Session {
33         session := Session{chat, make(chan *tgbotapi.Message)}
34         sessions[chat.ID] = &session
35         startSession(&session)
36         return &session
37 }
38
39 func startSession(session *Session) {
40         ctx, _ := context.WithCancel(sessionsCtx)
41         go func() {
42                 for {
43                         select {
44                         case msg := <-session.Input:
45                                 log.Printf("[%s] %s", msg.From.UserName, msg.Text)
46
47                                 newMsg := tgbotapi.NewMessage(msg.Chat.ID, msg.Text)
48                                 newMsg.ReplyToMessageID = msg.MessageID
49                                 sendToTelegram(newMsg)
50                         case <-ctx.Done():
51                                 return
52                         }
53                 }
54         }()
55 }
56
57 func sendToSession(session *Session, message *tgbotapi.Message) {
58         session.Input <- message
59 }