a simple matrix package for basic actions
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.

113 lines
2.7 KiB

package matrix
import (
"bytes"
"encoding/json"
"fmt"
"time"
"gopkg.in/h2non/gentleman.v2"
"gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/headers"
"gopkg.in/h2non/gentleman.v2/plugins/query"
)
// Send allows sending messages
func Send(authinfo Authinfo, roomID string, message string) error {
cli := gentleman.New()
cli.URL(authinfo.HomeServer)
eventType := "m.room.message"
txID := fmt.Sprintf("%d", time.Now().UnixNano())
req := cli.Request()
req.Path(fmt.Sprintf("/_matrix/client/r0/rooms/%s/send/%s/%s", roomID, eventType, txID))
req.Method("PUT")
formattedMessage := fmt.Sprintf("<pre><samp style=\"font-family: monospace\">%s\n</samp></pre>\n", message)
// Define the JSON payload via body plugin
data := map[string]string{
"msgtype": "m.text",
"body": "A", // notifications
"format": "org.matrix.custom.html",
"formatted_body": formattedMessage,
}
req.Use(body.JSON(data))
req.Use(query.Set("access_token", authinfo.AccessToken))
res, err := req.Send()
if err != nil {
fmt.Println("ERR1")
return err
}
if !res.Ok {
fmt.Println("ERR2")
fmt.Println(res)
return err
}
fmt.Printf("Sent %s\n", message)
return nil
}
// Upload uploads stuff to the matrix homeserver returning the files MXC
func Upload(authinfo Authinfo, filename string, file *bytes.Buffer) (UploadResponse, error) {
cli := gentleman.New()
cli.URL(authinfo.HomeServer)
req := cli.Request()
req.Path("/_matrix/media/r0/upload")
req.Method("POST")
req.Use(headers.Set("Content-Type", "image/png"))
req.Use(headers.Set("filename", filename))
req.Use(body.Reader(file))
req.Use(query.Set("access_token", authinfo.AccessToken))
res, err := req.Send()
if err != nil {
fmt.Println("ERR1")
return UploadResponse{}, err
}
if !res.Ok {
fmt.Println("ERR2")
fmt.Println(res)
return UploadResponse{}, err
}
var uploadResponse UploadResponse
if err := json.Unmarshal(res.Bytes(), &uploadResponse); err != nil {
return UploadResponse{}, err
}
return uploadResponse, nil
}
// SendImage sends the image with the given mxc ID to the room (currently
// hardcoded some lines below)
func SendImage(authinfo Authinfo, roomID string, image map[string]interface{}) error {
cli := gentleman.New()
cli.URL(authinfo.HomeServer)
eventType := "m.room.message"
txID := fmt.Sprintf("%d", time.Now().UnixNano())
req := cli.Request()
req.Path(fmt.Sprintf("/_matrix/client/r0/rooms/%s/send/%s/%s", roomID, eventType, txID))
req.Method("PUT")
req.Use(body.JSON(image))
req.Use(query.Set("access_token", authinfo.AccessToken))
res, err := req.Send()
if err != nil {
fmt.Println("ERR1")
return err
}
if !res.Ok {
fmt.Println("ERR2")
fmt.Println(res)
return err
}
return nil
}