arnaucube
arnaucube/canaryBotPublic Self-hosted repository
canaryBot/matrix.go
matrix.goRaw
 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"io/ioutil"
 7	"log"
 8	"math/rand"
 9	"net/http"
10	"strconv"
11	"strings"
12	"time"
13
14	"github.com/fatih/color"
15)
16
17//MatrixToken stores the token data from matrix
18type MatrixToken struct {
19	AccessToken string `json:"access_token"`
20	Server      string `json:"server"`
21	UserId      string `json:"user_id"`
22	DeviceId    string `json:"device_id"`
23}
24
25var matrixToken MatrixToken
26
27var defaultTimeFormat = "15:04:05"
28
29func loginMatrix() {
30	url := config.Matrix.Server + "/_matrix/client/r0/login"
31	jsonStr := `{
32		"type":"m.login.password",
33		"user":"` + config.Matrix.User + `",
34		"password":"` + config.Matrix.Password + `"
35	}`
36	b := strings.NewReader(jsonStr)
37	req, _ := http.NewRequest("POST", url, b)
38	req.Header.Set("Content-Type", "application/json")
39	res, err := http.DefaultClient.Do(req)
40	if err != nil {
41		log.Println(err)
42	}
43	defer res.Body.Close()
44	body, _ := ioutil.ReadAll(res.Body)
45
46	json.Unmarshal([]byte(body), &matrixToken)
47
48}
49func matrixSendMsg(msg string) {
50	txnId := strconv.Itoa(rand.Int())
51	url := config.Matrix.Server + "/_matrix/client/r0/rooms/" + config.Matrix.RoomId + "/send/m.room.message/" + txnId + "?access_token=" + matrixToken.AccessToken
52	jsonStr := `{
53		"body":"` + time.Now().Format(defaultTimeFormat) + `: ` + msg + `",
54		"msgtype":"m.text"
55	}`
56	b := strings.NewReader(jsonStr)
57	req, _ := http.NewRequest("PUT", url, b)
58	req.Header.Set("Content-Type", "application/json")
59	res, err := http.DefaultClient.Do(req)
60	if err != nil {
61		log.Println(err)
62	}
63	defer res.Body.Close()
64	body, _ := ioutil.ReadAll(res.Body)
65
66	fmt.Println(string(body))
67	fmt.Print("msg sent to Matrix: ")
68	color.Green(msg)
69
70}
71
72func matrixSendNotice(msg string) {
73	txnId := strconv.Itoa(rand.Int())
74	url := config.Matrix.Server + "/_matrix/client/r0/rooms/" + config.Matrix.RoomId + "/send/m.room.message/" + txnId + "?access_token=" + matrixToken.AccessToken
75	jsonStr := `{
76		"body":"` + time.Now().Format(defaultTimeFormat) + `: ` + msg + `",
77		"msgtype":"m.notice"
78	}`
79	b := strings.NewReader(jsonStr)
80	req, _ := http.NewRequest("PUT", url, b)
81	req.Header.Set("Content-Type", "application/json")
82	res, err := http.DefaultClient.Do(req)
83	if err != nil {
84		log.Println(err)
85	}
86	defer res.Body.Close()
87	body, _ := ioutil.ReadAll(res.Body)
88
89	fmt.Println(string(body))
90	fmt.Print("msg sent to Matrix: ")
91	color.Green(msg)
92
93}