Skip to content

Instantly share code, notes, and snippets.

@bdclark
Last active July 29, 2018 17:58
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bdclark/4bc8ed06643e077fa620 to your computer and use it in GitHub Desktop.
Save bdclark/4bc8ed06643e077fa620 to your computer and use it in GitHub Desktop.
Example python function to notify HipChat room using API version 2
#!/usr/bin/env python
from __future__ import print_function
import requests
import sys
import json
def hipchat_notify(token, room, message, color='yellow', notify=False,
format='text', host='api.hipchat.com'):
"""Send notification to a HipChat room via API version 2
Parameters
----------
token : str
HipChat API version 2 compatible token (room or user token)
room: str
Name or API ID of the room to notify
message: str
Message to send to room
color: str, optional
Background color for message, defaults to yellow
Valid values: yellow, green, red, purple, gray, random
notify: bool, optional
Whether message should trigger a user notification, defaults to False
format: str, optional
Format of message, defaults to text
Valid values: text, html
host: str, optional
Host to connect to, defaults to api.hipchat.com
"""
if len(message) > 10000:
raise ValueError('Message too long')
if format not in ['text', 'html']:
raise ValueError("Invalid message format '{0}'".format(format))
if color not in ['yellow', 'green', 'red', 'purple', 'gray', 'random']:
raise ValueError("Invalid color {0}".format(color))
if not isinstance(notify, bool):
raise TypeError("Notify must be boolean")
url = "https://{0}/v2/room/{1}/notification".format(host, room)
headers = {'Content-type': 'application/json'}
headers['Authorization'] = "Bearer " + token
payload = {
'message': message,
'notify': notify,
'message_format': format,
'color': color
}
r = requests.post(url, data=json.dumps(payload), headers=headers)
r.raise_for_status()
try:
hipchat_notify('MY_HIPCHAT_TOKEN', 'room_name_or_id', 'Hello World!')
except Exception as e:
msg = "[ERROR] HipChat notify failed: '{0}'".format(e)
print(msg, file=sys.stderr)
sys.exit(1)
@sjtower
Copy link

sjtower commented Jul 20, 2017

Thanks for this! 👍

@yang-liu
Copy link

yang-liu commented Oct 3, 2017

Thanks a lot. It works perfectly for me.

@hotcoder
Copy link

hotcoder commented Dec 1, 2017

thanks , it helped me 👍

@pedy711
Copy link

pedy711 commented Jan 12, 2018

Awesome!!!

@yeukhon
Copy link

yeukhon commented Jul 29, 2018

This is so helpful! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment