post_pr_comment.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import json
  2. import os
  3. import sys
  4. import urllib2
  5. GITHUB_URL = 'https://api.github.com'
  6. def post_comment(pr_id, repo_slug, comment_body, user_token):
  7. # Constructing the url
  8. url = '{api_url}/repos/{slug}/issues/{number}/comments'.format(
  9. api_url=GITHUB_URL, slug=repo_slug, number=pr_id)
  10. req = urllib2.Request(url=url,
  11. data=json.dumps({'body': comment_body}))
  12. req.add_header('Authorization', 'token ' + user_token)
  13. # Making the request
  14. f = urllib2.urlopen(req)
  15. if f.getcode() != 201:
  16. print f.read()
  17. # Get the environment variables
  18. PR_NUMBER = os.environ.get('TRAVIS_PULL_REQUEST')
  19. REPO_SLUG = os.environ.get('TRAVIS_REPO_SLUG') # owner_name/repo_name
  20. BOT_TOKEN = os.environ.get('TRAVIS_BOT_GITHUB_TOKEN')
  21. BUILD_ID = os.environ.get('TRAVIS_BUILD_ID')
  22. # Read the test result output from stdin
  23. test_result = sys.stdin.read().strip()
  24. # Populate the template text
  25. comment = (
  26. "The [build]"
  27. "(https://travis-ci.org/tldr-pages/tldr/builds/{build_id})"
  28. " for this PR has failed with the following message:"
  29. "\n```\n"
  30. "{comment_body}"
  31. "\n```\n"
  32. "Please fix the error(s) and push again."
  33. ).format(build_id=BUILD_ID, comment_body=test_result)
  34. # If its a PR, post a comment on it
  35. if PR_NUMBER != "false":
  36. post_comment(PR_NUMBER, REPO_SLUG, comment, BOT_TOKEN)