Skip to content

Instantly share code, notes, and snippets.

@DavidWittman
Last active May 10, 2016 14:37
Show Gist options
  • Save DavidWittman/73d4059c6409862ffdae to your computer and use it in GitHub Desktop.
Save DavidWittman/73d4059c6409862ffdae to your computer and use it in GitHub Desktop.
Room-to-room message relay for Hipchat, with support across accounts.
package main
import (
"flag"
"fmt"
"github.com/andybons/hipchat"
"log"
"os"
"path"
"strings"
"time"
)
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:]
}
}
func messageSender(client hipchat.Client, room, name, message string) {
log.Printf("Relaying message(s) to %s", room)
req := hipchat.MessageRequest{
RoomId: room,
From: name,
Message: message,
Color: hipchat.ColorYellow,
MessageFormat: hipchat.FormatText,
Notify: true,
}
if err := client.PostMessage(req); err != nil {
log.Printf("Error sending message: %v", err)
}
}
func Usage() {
fmt.Printf(`usage: %s [options]
Room-to-room message relay for Hipchat, with support across accounts.
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 sourceToken = flag.String("source-token", "", "Hipchat AuthToken for the source account")
var destToken = flag.String("dest-token", "", "Hipchat AuthToken for the destination account")
var sourceRoom = flag.String("source-room", "", "Hipchat room to relay messages from")
var destRoom = flag.String("dest-room", "", "Hipchat room to send relayed messages to")
var botName = flag.String("name", "Polly", "Username to use for notifications")
flag.Parse()
if *sourceToken == "" || *destToken == "" || *sourceRoom == "" || *destRoom == "" {
Usage()
}
sourceClient := hipchat.Client{AuthToken: *sourceToken}
destClient := hipchat.Client{AuthToken: *destToken}
go messageReceiver(sourceClient, *sourceRoom, ci)
for {
messages := <-ci
if len(messages) != 0 {
log.Printf("Found %d new message(s)", len(messages))
formattedMsg := make([]string, len(messages))
for _, msg := range messages {
formattedMsg = append(formattedMsg, fmt.Sprintf("%s: %s", msg.From.Name, msg.Message))
}
go messageSender(destClient, *destRoom, *botName, strings.Join(formattedMsg, "\n"))
}
<-ticker.C
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment