Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joemaffia/bf6b71925842d060b87fd3715e78fffe to your computer and use it in GitHub Desktop.
Save joemaffia/bf6b71925842d060b87fd3715e78fffe to your computer and use it in GitHub Desktop.
Slack Bot reminder for Bitbucket pull requests
import os
import sys
import requests
import json
from datetime import tzinfo, timedelta, datetime
from dateutil.parser import parse
POST_URL = 'https://slack.com/api/chat.postMessage'
REPOSITORY_PR = 'https://api.bitbucket.org/2.0/repositories/team/repository/pullrequests?state=OPEN'
SLACK_CHANNEL = '#channel'
SLACK_API_TOKEN = ''
BITBUCKET_UID = ''
BITBUCKET_PWD = ''
INITIAL_MESSAGE = """\
<!here|here> I'm not angry, I'm happiness challenged.
Review these PRs:
"""
ZERO = timedelta(0)
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
def format_pull_requests(json_obj):
lines = []
present = datetime.now(utc)
for i in json_obj['values']:
created_on = parse(i['created_on'])
delta = round((present - created_on).total_seconds()/86400)
# send message if PR is older than 2 days
if delta > 2:
line = '- *{0}* <{1}|{2}> - by {3}'.format(i['source']['branch']['name'],i['links']['html']['href'],i['title'],i['author']['display_name'])
lines.append(line)
return lines
def fetch_pulls():
lines = []
"""
Returns a formatted string list of open pull request messages.
"""
response = requests.get(REPOSITORY_PR, auth=(BITBUCKET_UID, BITBUCKET_PWD))
if(response.ok):
json_obj = json.loads(response.content)
lines += format_pull_requests(json_obj)
return lines
def send_to_slack(text):
payload = {
'token': SLACK_API_TOKEN,
'channel': SLACK_CHANNEL,
'as_user': True,
'text': text
}
response = requests.post(POST_URL, data=payload)
answer = response.json()
if not answer['ok']:
raise Exception(answer['error'])
def cli():
lines = fetch_pulls()
if lines:
text = INITIAL_MESSAGE + '\n'.join(lines)
send_to_slack(text)
#print(text)
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment