X-Git-Url: https://git.jsancho.org/?p=midgaard_bot.git;a=blobdiff_plain;f=sessions.go;h=17fa54555dcc062ec2a449e6f9700f4162070ec0;hp=7dd2df3c1b448d7f0e22742451978c23585d0d18;hb=refs%2Fheads%2Fmaster;hpb=54d3318115d6fd32364f5993ff67d0461c162aef diff --git a/sessions.go b/sessions.go index 7dd2df3..17fa545 100644 --- a/sessions.go +++ b/sessions.go @@ -1,10 +1,28 @@ +/* +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" + "github.com/reiver/go-telnet" ) type Session struct { @@ -13,10 +31,12 @@ type Session struct { } var sessions map[int64]*Session +var mercHost string var sessionsCtx context.Context -func initSessions(ctx context.Context) error { +func initSessions(host string, ctx context.Context) error { sessions = make(map[int64]*Session) + mercHost = host sessionsCtx = ctx return nil } @@ -38,19 +58,31 @@ func newSession(chat *tgbotapi.Chat) *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 - } + telnetInput, telnetOutput := make(chan string), make(chan string) + caller := TelnetCaller{ + Input: telnetInput, + Output: telnetOutput, } + + go func() { + for { + select { + case msg := <-session.Input: + if msg.Text != "/start" { + telnetInput <- msg.Text + } + case body := <-telnetOutput: + newMsg := tgbotapi.NewMessage(session.Chat.ID, body) + sendToTelegram(newMsg) + case <-ctx.Done(): + return + } + } + }() + + telnet.DialToAndCall(mercHost, caller) }() }