Fix messages being deleted as they are added to the queue (fix #26)

This commit is contained in:
Noah 2024-06-11 14:17:15 -05:00
parent d54fd47375
commit ba045a947f

View File

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