diff --git a/matrix.go b/matrix.go index 7a7dcd4..bdefff1 100644 --- a/matrix.go +++ b/matrix.go @@ -5,6 +5,8 @@ import ( "context" "log" "time" + "strings" + "fmt" "maunium.net/go/mautrix" "maunium.net/go/mautrix/event" @@ -12,19 +14,38 @@ import ( "maunium.net/go/mautrix/format" ) +// MatrixMessage stores information about a matrix message. type MatrixMessage struct { text string } -// I/O queues -var MatrixIn []MatrixMessage +// MatrixCommand stores information about a matrix chat command +type MatrixCommand struct { + cmd string + callback func(ctx context.Context, evt *event.Event) string + description string +} + +// Output queue var MatrixOut []MatrixMessage +// ChatCommands +var Chatcommands []MatrixCommand + // sendMessage sends a message through Matrix func sendMessage(msg MatrixMessage) { MatrixOut = append(MatrixOut, msg) } +// registerChatCommand +func registerChatCommand(cmd string, description string, callback func(ctx context.Context, evt *event.Event) string) { + Chatcommands = append(Chatcommands, MatrixCommand{ + cmd: cmd, + callback: callback, + description: description, + }) +} + // initMatrix starts a Matrix bot. func initMatrix() { client, err := mautrix.NewClient(configuration.matrix.homeserver, "", "") @@ -57,6 +78,26 @@ func initMatrix() { } } }) + syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) { + if evt.RoomID.String() == configuration.matrix.room_id { + for _, command := range Chatcommands { + if command.cmd == strings.TrimPrefix(evt.Content.AsMessage().Body, "!") { + out := command.callback(ctx, evt) + content := format.RenderMarkdown(out, true, false) + content.SetReply(evt) + client.SendMessageEvent(ctx, evt.RoomID, event.EventMessage, content) + } + } + } + }) + + registerChatCommand("help", "Show the help dialouge", func(ctx context.Context, evt *event.Event) string { + text := "" + for _,cmd := range Chatcommands { + text = fmt.Sprintf("%s- %s\n %s\n", text, cmd.cmd, cmd.description) + } + return text + }) go func () { for range time.Tick(time.Second * 3) {