forked from nikoksr/notify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix.go
65 lines (56 loc) · 1.7 KB
/
matrix.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
59
60
61
62
63
64
65
package matrix
import (
"context"
"errors"
matrix "maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
//go:generate mockery --name=matrixClient --output=. --case=underscore --inpackage
type matrixClient interface {
SendMessageEvent(roomID id.RoomID, eventType event.Type, contentJSON interface{}, extra ...matrix.ReqSendEvent) (resp *matrix.RespSendEvent, err error)
}
// Compile time check to ensure that matrix.Client implements the matrixClient interface
var _ matrixClient = new(matrix.Client)
// New returns a new instance of a Matrix notification service.
// For more information about the Matrix api specs:
//
// -> https://spec.matrix.org/v1.2/client-server-api
func New(userID id.UserID, roomID id.RoomID, homeServer, accessToken string) (*Matrix, error) {
client, err := matrix.NewClient(homeServer, userID, accessToken)
if err != nil {
return nil, err
}
s := &Matrix{
client: client,
options: ServiceOptions{
homeServer: homeServer,
accessToken: accessToken,
userID: userID,
roomID: roomID,
},
}
return s, nil
}
// Send takes a message body and sends them to the previously set channel.
// you will need an account, access token and roomID
// see https://matrix.org
func (s *Matrix) Send(ctx context.Context, _, message string) error {
messageBody := createMessage(message)
select {
case <-ctx.Done():
return ctx.Err()
default:
_, err := s.client.SendMessageEvent(s.options.roomID, event.EventMessage, &messageBody)
if err != nil {
return errors.New("failed to send message to the room using Matrix")
}
}
return nil
}
func createMessage(message string) Message {
return Message{
Body: message,
Msgtype: event.MsgText,
}
}