diff --git a/matrix.go b/matrix.go index 99c7944..e39c9d6 100644 --- a/matrix.go +++ b/matrix.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "strings" + "sync" "time" "maunium.net/go/mautrix" @@ -31,12 +32,17 @@ type MatrixCommand struct { } // Output queue. -var MatrixOut []MatrixMessage +var MatrixOut struct { + queue []MatrixMessage + mux sync.Mutex +} // sendMessage sends a message through Matrix. func sendMessage(msg MatrixMessage) { log.Print(msg.text) - MatrixOut = append(MatrixOut, msg) + MatrixOut.mux.Lock() + MatrixOut.queue = append(MatrixOut.queue, msg) + MatrixOut.mux.Unlock() } // sendError sends an error through Matrix. @@ -116,15 +122,16 @@ func initMatrix() { go func() { for range time.Tick(time.Second * 2) { - if len(MatrixOut) > 0 { + MatrixOut.mux.Lock() + if len(MatrixOut.queue) > 0 { text := "" - for i, msg := range MatrixOut { + for i, msg := range MatrixOut.queue { text += msg.text - if i != len(MatrixOut) { + if i != len(MatrixOut.queue) { text += "\n" } } - MatrixOut = []MatrixMessage{} + MatrixOut.queue = []MatrixMessage{} _, err := client.SendMessageEvent(context.Background(), id.RoomID(configuration.matrix.room_id), event.EventMessage, @@ -135,6 +142,7 @@ func initMatrix() { continue } } + MatrixOut.mux.Unlock() } }()