X-Git-Url: https://git.jsancho.org/?p=midgaard_bot.git;a=blobdiff_plain;f=sessions.go;h=a4f0c89a0e0ce4c7fcd10002118211407cf0ed09;hp=a0ff861d591fdee13a3825cbf867879cd874ae36;hb=afe75f075ad32184cb03cdc0c3d6a1d35e518b1c;hpb=287bb6b379833a10a1eca80a5fbe52422e345c76 diff --git a/sessions.go b/sessions.go index a0ff861..a4f0c89 100644 --- a/sessions.go +++ b/sessions.go @@ -1,18 +1,42 @@ +/* +midgaard_bot, a Telegram bot which sets a bridge to Midgaard Merc MUD +Copyright (C) 2017 by Javier Sancho Fernandez + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + 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 +48,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 +}