-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmatrixHandler.go
58 lines (46 loc) · 1.24 KB
/
matrixHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"encoding/json"
"fmt"
"github.com/matrix-org/gomatrix"
)
var matrixClient *gomatrix.Client
func initMatrix() {
c, err := gomatrix.NewClient(*homeserver, "", "")
if err != nil {
fmt.Println(err)
return
}
matrixClient = c
resp, err := c.Login(&gomatrix.ReqLogin{Type: "m.login.password", User: *username, Password: *password})
if err != nil {
fmt.Println(err)
return
}
c.SetCredentials(resp.UserID, resp.AccessToken)
syncer := c.Syncer.(*gomatrix.DefaultSyncer)
syncer.OnEventType("m.room.message", cbMatrix)
}
func startMatrix() {
err := matrixClient.Sync()
if err != nil {
fmt.Println(err)
}
}
var cbMatrix gomatrix.OnEventListener = func(evt *gomatrix.Event) {
fmt.Printf("[%[5]s]: <%[1]s> %[4]s (%[2]s/%[3]s)\n", evt.Sender, evt.Type, evt.ID, evt.Content, evt.RoomID)
go sendMqttMessage(evt)
}
func sendMqttMessage(message *gomatrix.Event) {
topic := fmt.Sprintf("_tuple/client/r0/rooms/%[1]s/event/%[2]s", message.RoomID, message.Type)
payload, err := json.Marshal(message)
if err != nil {
fmt.Println(err)
}
p := string(payload)
fmt.Println(p)
if token := mqttClient.Publish(topic, 0, false, payload); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
}
fmt.Print("send")
}