Skip to content

Instantly share code, notes, and snippets.

@stefanfoulis
Created March 22, 2013 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanfoulis/5218064 to your computer and use it in GitHub Desktop.
Save stefanfoulis/5218064 to your computer and use it in GitHub Desktop.
Ugly as hell quick and dirty script to automatically add github notifications for a list of projects to hipchat and to create a room per project based on a naming convention.
# -*- coding: utf-8 -*-
import requests
import json
import pprint
from secrets import hipchat_api_key # the hipchat API key with admin rights
from secrets import github_credentials # a tuple for github access (github_username, password),
from secrets import hipchat_notification_api_key # the hipchat API key to use for the notification hooks on github
hipchat_apps_room_name = 'Divio Application Suite'
hipchat_headers = {'content-type': 'application/x-www-form-urlencoded'}
# url = "https://api.hipchat.com/v1/rooms/list?auth_token=%s" % hipchat_api_key
# r = requests.get(url)
# pprint.pprint(r.json())
# pprint.pprint(requests.get('https://api.github.com/repos/divio/djangocms-accounts/hooks', auth=github_credentials).json())
def build_github_notification_hook_config(room_name, api_key=None):
api_key = api_key or hipchat_notification_api_key
return {
'name': 'hipchat',
'active': True,
# 'events': ['push', 'pull_request'],
'config': {
'auth_token': api_key,
'room': room_name,
'notify': True,
}
}
# check if hook already exists
def get_hook(repo):
for hook in requests.get('https://api.github.com/repos/%s/hooks' % repo, auth=github_credentials).json():
if hook['name'] == 'hipchat':
return hook
return None
def create_or_update_hook(repo, config, test_on_update=False):
hook = get_hook(repo)
if not hook:
print "creating hook for '%s'" % repo
url = 'https://api.github.com/repos/%s/hooks' % repo
else:
print "updating hook for '%s'" % repo
url = 'https://api.github.com/repos/%s/hooks/%s' % (repo, hook['id'])
r = requests.post(
url,
auth=github_credentials,
data=json.dumps(config),
headers={'content-type': 'application/json'}
)
r_data = r.json()
if not hook or test_on_update:
print "testing hook for %s" % repo
id = r_data['id']
tr = requests.post('https://api.github.com/repos/%s/hooks/%s/test' % (repo, id), auth=github_credentials)
app_repos = [
'divio/djangocms-events',
'divio/djangocms-stacks',
'divio/django-shop',
'divio/djangocms-text-ckeditor',
'divio/djangocms-admin-style',
'divio/djangocms-link',
'divio/djangocms-column',
'divio/djangocms-oembed',
'divio/djangocms-table',
'divio/django-contactform',
'divio/djangocms-simple-gallery',
'divio/djangocms-common',
'divio/django-siteinfo',
]
# update/create apps
def update_app_webooks(repos=None):
if repos is None:
repos = list(app_repos)
for repo in repos:
create_or_update_hook(repo, build_github_notification_hook_config(hipchat_apps_room_name))
# projects
def get_project_data(org='divio'):
# pprint.pprint(requests.get('https://api.github.com/orgs/%s/repos' % (org,), auth=github_credentials, params={'type': 'private'}).json())
projects = {}
r = requests.get('https://api.github.com/orgs/%s/repos' % (org,), auth=github_credentials, params={'type': 'private', 'per_page': 50})
projects.update({p['full_name']: p for p in r.json() if p['full_name'].endswith('-project')})
while r.links.get('next'):
print ' getting page'
r = requests.get(r.links.get('next')['url'], auth=github_credentials)
projects.update({p['full_name']:p for p in r.json() if p['full_name'].endswith('-project')})
return projects
def build_hipchat_project_room_config(room_name):
return {'name': room_name}
def get_room_list():
print 'fetching room list'
return requests.get('https://api.hipchat.com/v1/rooms/list', params={'format': 'json', 'auth_token': hipchat_api_key}).json().get('rooms', [])
def create_or_update_project_room(room_name, topic=None, rooms=None):
if rooms is None:
rooms = get_room_list()
if not len(rooms):
print " no rooms found!"
room_names = [r['name'] for r in rooms]
if not room_name in room_names:
# create the room
data = {
'name': room_name,
'owner_user_id': 266418,
}
if topic is not None:
data['topic'] = topic
print "creating room '%s'" % room_name
requests.post('https://api.hipchat.com/v1/rooms/create', params={'format': 'json', 'auth_token': hipchat_api_key}, data=data, headers=hipchat_headers)
elif topic is not None:
# update topic of room
for rs in rooms:
if rs['name'] == room_name:
room_id = rs['room_id']
break
data = {
'room_id': room_id,
'topic': topic
}
print "updating room '%s'" % room_name
requests.post('https://api.hipchat.com/v1/rooms/topic', params={'format': 'json', 'auth_token': hipchat_api_key}, data=data, headers=headers)
def hookup_room_and_notification(repo, topic=None, rooms=None):
org, project_name = repo.split('/')
short_project_name, __ = project_name.split('-project')
room_name = '{p} %s' % short_project_name
create_or_update_project_room(room_name, topic, rooms=rooms)
create_or_update_hook(repo, build_github_notification_hook_config(room_name))
def hookup_all_rooms_and_notifications():
projects = get_project_data()
repos = projects.keys()
all_rooms = get_room_list()
if not len(all_rooms):
print "NO ROOMS FOUND!!!"
return
for repo in repos:
data = {'description': repo,
'default_branch': '',
'homepage': ''}
data.update(projects[repo])
topic = u"""%(description)s
default branch: %(default_branch)s
homepage: %(homepage)s""" % data
hookup_room_and_notification(repo, topic=topic, rooms=all_rooms)
def delete_room(room_id, room_name):
print u"deleting room '%s' (%s)" % (room_name, room_id)
data = {'room_id': room_id}
requests.post('https://api.hipchat.com/v1/rooms/delete', params={'format': 'json', 'auth_token': hipchat_api_key}, data=data, headers=hipchat_headers)
def delete_rooms(starting_with='[p] '):
for room in get_room_list():
if room['name'].startswith(starting_with):
delete_room(room['room_id'], room['name'])
# update_app_webooks()
hookup_all_rooms_and_notifications()
# delete_rooms()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment