Skip to content

Instantly share code, notes, and snippets.

@gerco
Created August 9, 2017 02:08
Show Gist options
  • Save gerco/e1d281cc946bc22f974c8b563fb81d5b to your computer and use it in GitHub Desktop.
Save gerco/e1d281cc946bc22f974c8b563fb81d5b to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
)
const MATRIX_URL = ""
const ACCESS_TOKEN = ""
func main() {
flag.Parse()
command := flag.Arg(0)
switch command {
case "login":
login(flag.Arg(1), flag.Arg(2))
case "invite":
invite(flag.Arg(1), flag.Arg(2), ACCESS_TOKEN)
case "createroom":
createRoom(flag.Arg(1), ACCESS_TOKEN)
case "notify":
notify(flag.Arg(1), flag.Arg(2), ACCESS_TOKEN)
default:
fmt.Println("Unrecognized command " + command)
os.Exit(1)
}
}
func login(username string, password string) {
type Login struct {
Type string `json:"type"`
Username string `json:"user"`
Password string `json:"password"`
}
request, err := json.Marshal(Login{"m.login.password", username, password})
panicif(err)
resp, err := http.Post(MATRIX_URL+"_matrix/client/r0/login",
"application/json",
bytes.NewBuffer(request))
panicif(err)
printBody(resp)
}
func invite(userid string, roomid string, accessToken string) {
type Invite struct {
UserId string `json:"user_id"`
}
request, err := json.Marshal(Invite{userid})
panicif(err)
os.Stdout.Write(request)
resp, err := http.Post(MATRIX_URL+"_matrix/client/r0/rooms/"+roomid+"/invite?access_token="+accessToken,
"application/json",
bytes.NewBuffer(request))
panicif(err)
printBody(resp)
}
func createRoom(name string, accessToken string) {
type CreateRoom struct {
RoomAlias string `json:"room_alias_name"`
}
request, err := json.Marshal(CreateRoom{name})
panicif(err)
resp, err := http.Post(MATRIX_URL+"_matrix/client/r0/createRoom?access_token="+accessToken,
"application/json",
bytes.NewBuffer(request))
panicif(err)
printBody(resp)
}
func notify(roomid string, message string, accessToken string) {
type SendMessage struct {
MsgType string `json:"msgtype"`
Body string `json:"body"`
}
request, err := json.Marshal(SendMessage{"m.text", message})
panicif(err)
url := MATRIX_URL + "_matrix/client/r0/rooms/" + roomid + "/send/m.room.message?access_token=" + accessToken
resp, err := http.Post(url,
"application/json",
bytes.NewBuffer(request))
panicif(err)
printBody(resp)
}
func printBody(resp *http.Response) {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
panicif(err)
os.Stdout.Write(body)
}
func panicif(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment