You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.3 KiB

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