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"
"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()
}
}()