Skip to content

Instantly share code, notes, and snippets.

@DavidWittman
Created July 9, 2015 03:17
Show Gist options
  • Save DavidWittman/f0ad3b9df6fde77d13e8 to your computer and use it in GitHub Desktop.
Save DavidWittman/f0ad3b9df6fde77d13e8 to your computer and use it in GitHub Desktop.
Relay for posting messages from a HipChat room into a Slack room
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"path"
"strings"
"time"
"github.com/andybons/hipchat"
)
func messageReceiver(client hipchat.Client, room string, ci chan []hipchat.Message) {
var lastMsg hipchat.Message
var start int
log.Printf("Receiver for %s started", room)
for {
start = 0
messages, err := client.RoomHistory(room, "recent", "CST")
if err != nil {
log.Printf("Error: %v", err)
time.Sleep(time.Second * 10)
continue
}
if (lastMsg == hipchat.Message{}) {
lastMsg = messages[len(messages)-1]
continue
}
for i, msg := range messages {
if msg == lastMsg {
start = i + 1
break
}
}
lastMsg = messages[len(messages)-1]
ci <- messages[start:]
}
}
type slackMessage struct {
Text string `json:"text"`
}
func messageSender(slackURL, message string) {
log.Print("Relaying message(s) to Slack")
msg := slackMessage{Text: message}
msgJson, err := json.Marshal(msg)
if err != nil {
log.Printf("Error converting message to JSON: %v", err)
return
}
resp, err := http.Post(slackURL, "application/json", bytes.NewReader(msgJson))
if err != nil {
log.Printf("Error posting to Slack: %v", err)
return
}
if resp.StatusCode == 200 {
log.Print("Message relayed successfully!")
} else {
log.Printf("Error posting message to slack: %v", resp.Status)
}
}
func Usage() {
fmt.Printf(`usage: %s [options]
Relay for posting messages from a HipChat room to a Slack room.
Options:
`, path.Base(os.Args[0]))
flag.PrintDefaults()
os.Exit(2)
}
func main() {
ci := make(chan []hipchat.Message)
ticker := time.NewTicker(30 * time.Second)
flag.Usage = Usage
var hipchatToken = flag.String("hipchat-token", "", "HipChat AuthToken for the source account")
var hipchatRoom = flag.String("hipchat-room", "", "HipChat room to relay messages from")
var slackWebhookURL = flag.String("slack-webhook-url", "", "Incoming webhook URL for Slack room. (e.g. 'https://hooks.slack.com/services/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')")
var messagePrefix = flag.String("prefix", "", "Text to prefix each Slack message with")
flag.Parse()
if *hipchatToken == "" || *hipchatRoom == "" || *slackWebhookURL == "" {
Usage()
}
hipchatClient := hipchat.Client{AuthToken: *hipchatToken}
go messageReceiver(hipchatClient, *hipchatRoom, ci)
for {
messages := <-ci
if len(messages) != 0 {
log.Printf("Found %d new message(s)", len(messages))
formattedMsg := make([]string, len(messages)+1)
if *messagePrefix != "" {
formattedMsg = append(formattedMsg, *messagePrefix)
}
for _, msg := range messages {
formattedMsg = append(formattedMsg, fmt.Sprintf("%s: %s", msg.From.Name, msg.Message))
}
go messageSender(*slackWebhookURL, strings.Join(formattedMsg, "\n"))
} else {
log.Print("No new messages received")
}
<-ticker.C
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment