Skip to content

Instantly share code, notes, and snippets.

@JLospinoso
Created June 18, 2016 21:57
Show Gist options
  • Save JLospinoso/c8f1f55c418216b96b32d365195a00ca to your computer and use it in GitHub Desktop.
Save JLospinoso/c8f1f55c418216b96b32d365195a00ca to your computer and use it in GitHub Desktop.
Example of using the mattermost golang driver
package main
import (
"log"
"time"
mattermost "github.com/mattermost/platform/model"
)
func printTeams(client *mattermost.Client) {
r, e := client.GetAllTeams()
if e != nil {
log.Fatal("Couldn't get team map: ", e)
}
teamMap := r.Data.(map[string]*mattermost.Team)
log.Print("Teams:")
for teamId, team := range teamMap {
log.Printf("%s -> %s", teamId, team.DisplayName)
}
}
func printChannels(client *mattermost.Client) {
r,e := client.GetChannels("")
if e != nil {
log.Fatal("Couldn't get channels: ", e)
}
channelList := r.Data.(*mattermost.ChannelList)
log.Print("Channels:")
for _, channel := range channelList.Channels {
log.Printf("%s -> %s", channel.Id, channel.DisplayName)
}
}
func printPosts(client *mattermost.Client, channelId string, start int, max int) {
r, e := client.GetPosts(channelId, start, max, "")
if e != nil {
log.Fatal("Couldn't get posts: ", e)
}
posts := r.Data.(*mattermost.PostList)
log.Print("Posts:")
for _, post := range posts.Posts {
log.Printf("%s -> %s @ %f", post.Id, post.Message, post.CreateAt)
}
}
func getClient(url string, username string, password string) (*mattermost.Client) {
client := mattermost.NewClient(url)
r, e := client.Login(username, password)
if e != nil {
log.Fatal("Couldn't login: ", e)
}
log.Printf("Client logged in. Auth Token: %s.", client.AuthToken)
user := r.Data.(*mattermost.User)
log.Printf("User information: %s", user.ToJson())
return client
}
func postMessage(client *mattermost.Client, userId string, channelId string, message string) {
newPost := mattermost.Post{
UserId: userId,
ChannelId: channelId,
Message: "Heartbeat.",
}
r,e := client.CreatePost(&newPost)
if e != nil {
log.Fatal("Couldn't make post: ", e)
}
post := r.Data.(*mattermost.Post)
log.Print("Post created: ", post)
}
func main() {
url := "http://172.17.0.1:8065"
username := "username"
password := "password"
userId := "zzzzzzzzzzzzzzzzz" //TODO: Fill this in from getClient output
teamId := "zzzzzzzzzzzzzzzzz" //TODO: Fill this in from printTeams output
channelId := "zzzzzzzzzzzzzzzzz" //TODO: Fill this in from printChannels output
client := getClient(url, username, password)
printTeams(client)
client.SetTeamId(teamId)
printChannels(client)
for _ = range []int{1, 2, 3, 4, 5} {
printPosts(client, channelId, 0, 1000)
postMessage(client, userId, channelId, "Heartbeat");
oneSecond,_ := time.ParseDuration("1s")
time.Sleep(oneSecond)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment