Esempio n. 1
0
func main() {
	flag.Parse()
	if *token == "" || *roomId == "" {
		flag.PrintDefaults()
		return
	}
	c := hipchat.NewClient(*token)
	hist, resp, err := c.Room.History(*roomId, &hipchat.HistoryRequest{})
	if err != nil {
		fmt.Printf("Error during room history req %q\n", err)
		fmt.Printf("Server returns %+v\n", resp)
		return
	}
	for _, m := range hist.Items {
		from := ""
		switch m.From.(type) {
		case string:
			from = m.From.(string)
		case map[string]interface{}:
			f := m.From.(map[string]interface{})
			from = f["name"].(string)
		}
		msg := m.Message
		if len(m.Message) > (maxMsgLen - len(moreString)) {
			msg = fmt.Sprintf("%s%s", strings.Replace(m.Message[:maxMsgLen], "\n", " - ", -1), moreString)
		}
		fmt.Printf("%s [%s]: %s\n", from, m.Date, msg)
	}
}
Esempio n. 2
0
func main() {
	flag.Parse()
	if *token == "" || *roomId == "" {
		flag.PrintDefaults()
		return
	}
	hipchat.AuthTest = *test

	c := hipchat.NewClient(*token)

	notifRq := &hipchat.NotificationRequest{Message: "Hey there!"}

	resp, err := c.Room.Notification(*roomId, notifRq)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error during room notification %q\n", err)
		fmt.Fprintf(os.Stderr, "Server returns %+v\n", resp)
		return
	}

	if hipchat.AuthTest {
		_, ok := hipchat.AuthTestResponse["success"]
		fmt.Println("Authentification succeed :", ok)
	} else {
		fmt.Println("Lol sent !")
	}
}
Esempio n. 3
0
// KnockKnock sends a private message to a user.
func (h *HipChat) KnockKnock(d *doorbot.Door, p *doorbot.Person) error {

	log.WithFields(log.Fields{
		"account_id": h.Account.ID,
		"person_id":  p.ID,
		"door_id":    d.ID,
	}).Info("Notificator::HipChat->Notify request")

	c := hipchat.NewClient(h.Token)

	dbb := rendering.DoorbotBar()

	renderingData := map[string]string{
		"name": p.Name,
		"door": d.Name,
	}

	messageRequest := &hipchat.MessageRequest{
		Message: dbb.Render("Hi {{name}},\nThere is someone waiting at the {{door}}.\n\n - Doorbot", renderingData),
		Notify:  true,
	}

	response, err := c.User.Message(p.Email, messageRequest)
	if response.StatusCode != 200 {
		return err
	}

	return nil
}
Esempio n. 4
0
// Run shells out external program and store the output on c.Data.
func (hc *HipChat) Run() error {
	hc.Data["Conditions"] = hc.Conditions

	if hc.IsConditionMet() && hc.LowThresholdExceeded() && !hc.HighThresholdExceeded() {
		c := hipchat.NewClient(hc.AuthToken)

		rooms, _, err := c.Room.List()
		if err != nil {
			return err
		}

		hc.Data["Message"] = fmt.Sprintf("Conditions: %v, Message: %v", hc.Conditions, hc.Message)

		notificationReq := &hipchat.NotificationRequest{Message: hc.Data["Message"].(string)}

		for _, room := range rooms.Items {
			if room.Name == hc.RoomName {
				_, err := c.Room.Notification(room.Name, notificationReq)
				if err != nil {
					return err
				}
			}
		}

		if err != nil {
			return err
		}
	}

	return nil
}
Esempio n. 5
0
func main() {

	flag.Parse()

	notification, _ := readMessageFromStdin()
	if notification == nil {
		notification = message
	}

	if isValidRequest(token, room, notification) {
		client := hipchat.NewClient(*token)

		request := hipchat.NotificationRequest{
			Message:       *notification,
			Color:         *color,
			Notify:        *notify,
			MessageFormat: *format,
		}

		response, err := client.Room.Notification(*room, &request)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error during room notification %q\n", err)
			fmt.Fprintf(os.Stderr, "Server returns %+v\n", response)
			return
		}
	} else {
		fmt.Fprintln(os.Stderr, "Message, Token, and Room must be specified.")
	}
}
Esempio n. 6
0
// NewHipchat -
func NewHipchat(config *HipchatConfig) (h *Hipchat) {
	h = &Hipchat{
		Config:   config,
		Room:     config.Room,
		messages: make(chan *hipchat.NotificationRequest),
	}

	if config.Token == "" {
		h.handler = func(msg *hipchat.NotificationRequest) {
			fmt.Printf("hipchat: warning auth token not set")
		}
	} else {
		client := hipchat.NewClient(config.Token)
		h.handler = func(msg *hipchat.NotificationRequest) {
			if _, err := client.Room.Notification(h.Room, msg); err != nil {
				fmt.Printf("hipchat: Failed to send - %q", err)
			}
		}
	}

	go func() {
		for m := range h.messages {
			h.handler(m)
		}
	}()

	return h
}
Esempio n. 7
0
func main() {
	flag.Parse()
	if *token == "" || *path == "" || ((*roomId == "") && (*userId == "")) {
		flag.PrintDefaults()
		return
	}
	c := hipchat.NewClient(*token)

	shareFileRq := &hipchat.ShareFileRequest{Path: *path, Message: *message, Filename: *filename}

	if *roomId != "" {
		resp, err := c.Room.ShareFile(*roomId, shareFileRq)

		if err != nil {
			fmt.Printf("Error during room file share %q\n", err)
			fmt.Printf("Server returns %+v\n", resp)
			return
		}
	}

	if *userId != "" {
		resp, err := c.User.ShareFile(*userId, shareFileRq)

		if err != nil {
			fmt.Printf("Error during user file share %q\n", err)
			fmt.Printf("Server returns %+v\n", resp)
			return
		}
	}

	fmt.Println("File sent !")
}
Esempio n. 8
0
func (h *HipChat) GetUsers() ([]*HipChatUser, error) {
	log.WithFields(log.Fields{
		"account_id": h.AccountID,
		"token":      h.Token,
	}).Info("Bridges::HipChat::GetUsers started")

	c := hipchat.NewClient(h.Token)

	svcUsers, _, err := c.User.List(0, 1000, false, false)
	if err != nil {
		log.WithFields(log.Fields{
			"account_id": h.AccountID,
			"error":      err,
		}).Error("Bridges::HipChat::GetUsers error")
	}

	users := make([]*HipChatUser, len(svcUsers))

	for k, u := range svcUsers {
		details, _, err := c.User.View(strconv.FormatInt(int64(u.ID), 10))

		if err != nil {
			return users, err
		}

		users[k] = &HipChatUser{
			ID:          u.ID,
			Email:       details.Email,
			DisplayName: details.Name,
			Title:       details.Title,
		}
	}

	return users, err
}
func send_Notify(token string, id string, message string, color string) {

	c := hipchat.NewClient(token)

	notifRq := &hipchat.NotificationRequest{Message: message, Color: color}
	resp2, err := c.Room.Notification(id, notifRq)

	if err != nil {
		fmt.Printf("Error during room notification %q\n", err)
		fmt.Printf("Server returns %+v\n", resp2)
	}
}
Esempio n. 10
0
func (hc *HipChat2) newClient() *hipchat.Client {
	client := hipchat.NewClient(hc.Token)
	if hc.BaseURL == "" {
		return client
	}

	baseURL, err := url.Parse(hc.BaseURL)
	if err != nil {
		log.Errorf("Invalid Hipchat Base URL...: %s", err.Error())
		return nil
	}
	client.BaseURL = baseURL
	return client
}
Esempio n. 11
0
func setupHipchat() {
	hipchat_api = hipchat.NewClient(os.Getenv("HIPCHAT_API_TOKEN"))
	if len(os.Getenv("HIPCHAT_API_TOKEN")) == 0 ||
		len(os.Getenv("HIPCHAT_ROOM_ID")) == 0 {
		color.Yellow("[>] Skipping Hipchat setup, missing HIPCHAT_API_TOKEN and HIPCHAT_ROOM_ID")
		return
	}
	if os.Getenv("HIPCHAT_SERVER") != "" {
		hipchat_api.BaseURL, err = url.Parse(os.Getenv("HIPCHAT_SERVER"))
		if err != nil {
			color.Red("Error connecting to private hipchat server: ", err)
			panic(err)
		}
	}
}
Esempio n. 12
0
func (hh *HiprusHook) initClient() error {
	c := hipchat.NewClient(hh.AuthToken)

	if hh.BaseURL != "" {
		hipchatUrl, _ := url.Parse(hh.BaseURL)
		c.BaseURL = hipchatUrl
	}

	hh.c = c

	if hh.Username == "" {
		hh.Username = "******"
	}

	return nil
}
Esempio n. 13
0
func (m *Message) Notify() (success bool, err error) {
	c := hipchat.NewClient(token)
	nr := &hipchat.NotificationRequest{
		Message:       m.formatted(),
		MessageFormat: "html",
		Color:         m.color(),
		From:          "( •_•)",
		Notify:        true,
	}
	resp, err := c.Room.Notification(roomId, nr)
	if err != nil {
		log.Println("error notifying room", err)
		return false, err
	}
	log.Println("success notifying room", resp.StatusCode)
	return resp.StatusCode == http.StatusNoContent, err
}
Esempio n. 14
0
func newHipCat(authToken string, roomId string, roomName string) (*HipCat, error) {
	hc := HipCat{
		api:      hipchat.NewClient(authToken),
		queue:    newStreamQ(),
		shutdown: make(chan os.Signal, 1),
		roomName: roomName,
		roomId:   roomId,
	}
	if hc.roomId == "" {
		err := hc.lookupRoomId()
		if err != nil {
			return nil, err
		}
	}
	signal.Notify(hc.shutdown, os.Interrupt)
	return &hc, nil
}
Esempio n. 15
0
func main() {
	flag.Parse()
	if *token == "" || *roomId == "" {
		flag.PrintDefaults()
		return
	}
	c := hipchat.NewClient(*token)

	notifRq := &hipchat.NotificationRequest{Message: "Hey there!"}
	resp, err := c.Room.Notification(*roomId, notifRq)
	if err != nil {
		fmt.Printf("Error during room notification %q\n", err)
		fmt.Printf("Server returns %+v\n", resp)
		return
	}
	fmt.Println("Lol sent !")
}
Esempio n. 16
0
func (h *HipChat) Notify(msg Message) {
	c := hipchat.NewClient(h.Token)

	// https://www.hipchat.com/docs/apiv2/method/send_room_notification
	nr := &hipchat.NotificationRequest{
		Message: msg.String(),
		// Update info here based on what type of notify message we have (status)
		Notify: false, // Send desktop notification
		Color:  "green",
	}

	_, err := c.Room.Notification(h.Room, nr)
	if err != nil {
		log.WithFields(log.Fields{
			"notify": "hipchat",
		}).Warn(err)
	}
}
Esempio n. 17
0
func (d *Discovery) initHipChatClient() error {

	if len(d.settings.HipChatToken) == 0 {
		return errors.New("No HipChat token specified.")
	}

	d.hipchatClient = hipchat.NewClient(d.settings.HipChatToken)
	hipchat.AuthTest = true
	d.hipchatClient.Room.List()
	_, ok := hipchat.AuthTestResponse["success"]
	hipchat.AuthTest = false

	if !ok {
		return errors.New("Invalid HipChat token.")
	}

	return nil
}
func (notifier *HipChatNotifier) Notify(messages Messages) bool {

	overallStatus, pass, warn, fail := messages.Summary()

	text := fmt.Sprintf(header, notifier.ClusterName, overallStatus, fail, warn, pass)

	for _, message := range messages {
		text += fmt.Sprintf("\n%s:%s:%s is %s.", message.Node, message.Service, message.Check, message.Status)
		text += fmt.Sprintf("\n%s", message.Output)
	}

	level := "green"
	if fail > 0 {
		level = "red"
	} else if warn > 0 {
		level = "yellow"
	}

	client := hipchat.NewClient(notifier.AuthToken)
	if notifier.BaseURL != "" {
		url, err := url.Parse(notifier.BaseURL)
		if err != nil {
			log.Printf("Error parsing hipchat base url: %s\n", err)
		}
		client.BaseURL = url
	}

	notifRq := &hipchat.NotificationRequest{
		Message: text,
		Color:   level,
		Notify:  true,
	}
	resp, err := client.Room.Notification(notifier.RoomId, notifRq)
	if err != nil {
		log.Printf("Error sending notification to hipchat: %s\n", err)
		log.Printf("Server returns %+v\n", resp)
		return false
	}

	return true
}
Esempio n. 19
0
func get_Room_ID(token string, name string) (string, error) {

	c := hipchat.NewClient(token)
	rooms, resp1, err := c.Room.List()
	handleRequestError(resp1, err)

	for _, room := range rooms.Items {
		if name == room.Name {
			fmt.Printf("%-25v%10v\n", room.Name, room.ID)
			fmt.Println("---")

			hooks, resp, err := c.Room.ListWebhooks(room.ID, nil)
			handleRequestError(resp, err)

			for _, webhook := range hooks.Webhooks {
				fmt.Printf("  %v %v\t%v\t%v\t%v\n", webhook.Name, webhook.ID, webhook.Event, webhook.URL, webhook.WebhookLinks.Links.Self)
			}
			fmt.Println("---")
			return strconv.Itoa(room.ID), nil
		}
	}
	return "", errors.New("Cannot find name of chart room , Please check again \n")
}
Esempio n. 20
0
//sendHipChat transform email to message, log and send to hipchat room
func sendHipChat(mime *enmime.MIMEBody, hnd *HipChatHandler) error {

	s := `
De    : %s
Sujet : %s
Text  : %d chars
Html  : %d chars
Inlines      : %d
Attachements : %d
Others       : %d`

	message := fmt.Sprintf(s,
		mime.GetHeader("From"),
		mime.GetHeader("Subject"),
		len(mime.Text),
		len(mime.Html),
		len(mime.Inlines),
		len(mime.Attachments),
		len(mime.OtherParts),
	)

	//log general message information
	log.Println(message)

	messageFormat := "text"

	if strings.Contains(mime.Text, "<html>") {
		messageFormat = "html"
		message = sanitizeMessage(mime.Html)
	} else {

		s = `
From     : %s
Subject  : %s
%s`

		message = fmt.Sprintf(s,
			mime.GetHeader("From"),
			mime.GetHeader("Subject"),
			mime.Text,
		)
	}

	//need to truncate message to 10000, supported by hipchat api
	message = short(message, 10000)

	//log what sending to hipchat
	log.Println(message)

	c := hipchat.NewClient(hnd.RoomAuth)

	//If specify html, need to determine/format the escape characters
	notifRq := &hipchat.NotificationRequest{Color: hnd.RoomColor, Message: message, MessageFormat: messageFormat}

	_, err := c.Room.Notification(hnd.RoomName, notifRq)
	if err != nil {
		log.Println("failed to send to hipchat: " + err.Error())
		return err
	}

	return nil
}
Esempio n. 21
0
func main() {
	flag.Parse()
	if *token == "" {
		flag.PrintDefaults()
		return
	}
	c := hipchat.NewClient(*token)

	if *action == "" {
		if *roomId == "" {
			// If no room is given, look up all rooms and all of their webhooks
			rooms, resp, err := c.Room.List()
			handleRequestError(resp, err)

			for _, room := range rooms.Items {
				fmt.Printf("%-25v%10v\n", room.Name, room.ID)

				hooks, resp, err := c.Room.GetAllWebhooks(room.ID, nil)
				handleRequestError(resp, err)

				for _, webhook := range hooks.Webhooks {
					fmt.Printf("  %v %v\t%v\t%v\t%v\n", webhook.Name, webhook.ID, webhook.Event, webhook.URL, webhook.WebhookLinks.Links.Self)
				}

				fmt.Println("---")
			}
		} else {
			// If room is given, just get the webhooks for that room
			hooks, resp, err := c.Room.GetAllWebhooks(*roomId, nil)
			handleRequestError(resp, err)

			for _, webhook := range hooks.Webhooks {
				fmt.Printf("  %v %v\t%v\t%v\t%v\n", webhook.Name, webhook.ID, webhook.Event, webhook.URL, webhook.WebhookLinks.Links.Self)
			}
		}
	} else if *action == "create" {
		if *roomId == "" {
			fmt.Println("roomId is required for webhook creation")
			flag.PrintDefaults()
			return
		}

		webhook, resp, err := c.Room.CreateWebhook(*roomId, &hipchat.CreateWebhookRequest{
			Name:    *name,
			Event:   "room_" + *event,
			Pattern: *pattern,
			URL:     *url,
		})
		handleRequestError(resp, err)
		fmt.Printf("%v\t%v\t%v\t%v\n", webhook.Name, webhook.Event, webhook.URL, webhook.WebhookLinks.Links.Self)
	} else if *action == "delete" {
		if *roomId == "" {
			fmt.Println("roomId is required for webhook deletion")
			flag.PrintDefaults()
			return
		}

		if *webhookId == "" {
			fmt.Println("webhookId is required for webhook deletion")
			flag.PrintDefaults()
			return
		}

		resp, err := c.Room.DeleteWebhook(*roomId, *webhookId)
		handleRequestError(resp, err)

		fmt.Println("Deleted webhook with id", *webhookId)
	}

}