diff --git a/main.go b/main.go index ac871d4..5cf13e6 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "log" + "sync" "time" "gopkg.in/gcfg.v1" @@ -42,11 +43,12 @@ var ( cfg Config - ownUserID64 = int64(0) - ownUserID32 = int32(0) - lastOwnTDMsg time.Time - MQCWMsgQueue chan ChatWarsMessage - MQTGCmdQueue chan TGCommand + ownUserID64 = int64(0) + ownUserID32 = int32(0) + lastOwnTDMsg time.Time + lastOwnTDMsgMux sync.Mutex + MQCWMsgQueue chan ChatWarsMessage + MQTGCmdQueue chan TGCommand ) func main() { @@ -133,7 +135,10 @@ func main() { } go MQKeepAliveWorker() + lastOwnTDMsgMux.Lock() lastOwnTDMsg = time.Now() + lastOwnTDMsgMux.Unlock() + go ListenCW(client) go ListenMQ(client, MQTGCmdQueue) go ListenMe(client) diff --git a/td.go b/td.go index c182afa..2ea6a8a 100644 --- a/td.go +++ b/td.go @@ -30,11 +30,6 @@ func ListenMe(c *tdlib.Client) { func ListenMQ(c *tdlib.Client, msgs <-chan TGCommand) { for m := range msgs { - for now := time.Now(); lastOwnTDMsg.Add(time.Second).After(now); { - log.Printf("ListenMQ : channel busy, waiting before acting...\n") - time.Sleep(time.Until(lastOwnTDMsg.Add(time.Second))) - now = time.Now() - } b, _ := json.Marshal(m) log.Printf("****************************** New MQ command ******************************\n%s\n****************************************************************************\n", string(b)) go clientMsg(c, m) @@ -224,9 +219,22 @@ func OwnUserID(c *tdlib.Client) int32 { } func clientMsg(c *tdlib.Client, m TGCommand) { + log.Printf("clientMsg : Delaying message by %d seconds.\n", m.Delay) if m.Delay != 0 { time.Sleep(time.Duration(m.Delay) * time.Second) } + for { + lastOwnTDMsgMux.Lock() + now := time.Now() + if lastOwnTDMsg.Add(time.Second).Before(now) { + lastOwnTDMsg = now + lastOwnTDMsgMux.Unlock() + break + } + lastOwnTDMsgMux.Unlock() + time.Sleep(time.Until(now.Add(time.Second))) + } + switch m.Type { case commandSendMsg: msgTxt := tdlib.NewInputMessageText(tdlib.NewFormattedText(m.Text, nil), true, true)