]> git.jsancho.org Git - midgaard_bot.git/blob - sessions.go
a4f0c89a0e0ce4c7fcd10002118211407cf0ed09
[midgaard_bot.git] / sessions.go
1 /*
2 midgaard_bot, a Telegram bot which sets a bridge to Midgaard Merc MUD
3 Copyright (C) 2017 by Javier Sancho Fernandez <jsf at jsancho dot org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package main
20
21 import (
22         "context"
23         "log"
24
25         "github.com/go-telegram-bot-api/telegram-bot-api"
26 )
27
28 type Session struct {
29         Chat *tgbotapi.Chat
30         Input chan *tgbotapi.Message
31 }
32
33 var sessions map[int64]*Session
34 var sessionsCtx context.Context
35
36 func initSessions(ctx context.Context) error {
37         sessions = make(map[int64]*Session)
38         sessionsCtx = ctx
39         return nil
40 }
41
42 func getSession(chat *tgbotapi.Chat) *Session {
43         session, ok := sessions[chat.ID]
44         if !ok {
45                 session = newSession(chat)
46         }
47         return session
48 }
49
50 func newSession(chat *tgbotapi.Chat) *Session {
51         session := Session{chat, make(chan *tgbotapi.Message)}
52         sessions[chat.ID] = &session
53         startSession(&session)
54         return &session
55 }
56
57 func startSession(session *Session) {
58         ctx, _ := context.WithCancel(sessionsCtx)
59         go func() {
60                 for {
61                         select {
62                         case msg := <-session.Input:
63                                 log.Printf("[%s] %s", msg.From.UserName, msg.Text)
64
65                                 newMsg := tgbotapi.NewMessage(msg.Chat.ID, msg.Text)
66                                 newMsg.ReplyToMessageID = msg.MessageID
67                                 sendToTelegram(newMsg)
68                         case <-ctx.Done():
69                                 return
70                         }
71                 }
72         }()
73 }
74
75 func sendToSession(session *Session, message *tgbotapi.Message) {
76         session.Input <- message
77 }