From 02fc3d217dd35021025feb5735e23f1cbef6792a Mon Sep 17 00:00:00 2001 From: shoopea Date: Tue, 5 Nov 2019 10:34:26 +0800 Subject: [PATCH] try using locks for not spamming live message --- main.go | 15 +++++++++------ td.go | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 7419b7f..e83baa4 100644 --- a/main.go +++ b/main.go @@ -34,12 +34,15 @@ var ( cfg Config - ownUserID64 = int64(0) - ownUserID32 = int32(0) - lastOwnTDMsg time.Time - lastOwnTDMsgMux sync.Mutex - MQCWMsgQueue chan ChatWarsMessage - MQTGCmdQueue chan TGCommand + ownUserID64 = int64(0) + ownUserID32 = int32(0) + lastOwnTDMsg time.Time + lastOwnTDMsgMux sync.Mutex + lastChatTDMsg map[uint64]time.Time + lastChatTDMsgMux map[uint64]sync.Mutex + lastChatMsgMux sync.RWMutex + MQCWMsgQueue chan ChatWarsMessage + MQTGCmdQueue chan TGCommand ) func main() { diff --git a/td.go b/td.go index a3fb3ef..2d33afa 100644 --- a/td.go +++ b/td.go @@ -69,6 +69,28 @@ func ListenTG(c *tdlib.Client) { m.Date = time.Unix(int64(updateMsg.Message.Date), 0) + lastChatMsgMux.RLock() + if _, ok := lastChatTDMsg[m.ChatID64]; !ok { + lastChatMsgMux.RUnlock() + lastChatMsgMux.Lock() + if _, ok := lastChatTDMsg[m.ChatID64]; !ok { + lastChatTDMsg[m.ChatID64] = time.Now().Add(-1 * time.Second) + lastChatTDMsgMux[m.ChatID64] = new(sync.Mutex) + } + lastChatMsgMux.Unlock() + } + for { + lastChatTDMsgMux[m.ChatID64].Lock() + now := time.Now() + if lastChatTDMsg[m.ChatID64].Add(time.Second).Before(now) { + lastChatTDMsg[m.ChatID64] = now + lastChatTDMsgMux[m.ChatID64].Unlock() + break + } + lastChatTDMsgMux[m.ChatID64].Unlock() + time.Sleep(time.Until(now.Add(time.Second))) + } + MQCWMsgQueue <- m fmt.Printf("[%d-%02d-%02d %02d:%02d:%02d-00:00]", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())