send-to-bot.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import json
  5. import urllib.request
  6. BOT_URL = 'https://tldr-bot.starbeamrainbowlabs.com'
  7. COMMENT_ERROR="""
  8. The [build](https://travis-ci.org/tldr-pages/tldr/builds/{build_id})
  9. for this PR failed with the following error(s):
  10. ```
  11. {content}
  12. ```
  13. Please fix the error(s) and push again.
  14. """
  15. COMMENT_CHECK="""
  16. Hello! I've noticed something unusual when checking this PR:
  17. {content}
  18. Is this intended? If so, just ignore this comment. Otherwise, please
  19. double-check the commits.
  20. """
  21. ################################################################################
  22. def post_comment(pr_id, body, once):
  23. endpoint = BOT_URL + '/comment'
  24. if once:
  25. endpoint += '/once'
  26. headers = {'Content-Type': 'application/json'}
  27. data = json.dumps({'pr_id': pr_id, 'body': body})
  28. req = urllib.request.Request(endpoint, data.encode(), headers)
  29. try:
  30. resp = urllib.request.urlopen(req)
  31. code = resp.getcode()
  32. except Exception as e:
  33. print('Error sending data to tldr-bot:', str(e), file=sys.stderr)
  34. return False
  35. if code != 200:
  36. print('Error: tldr-bot responded with code', code, file=sys.stderr)
  37. print(resp.read(), file=sys.stderr)
  38. return False
  39. return True
  40. def main(action):
  41. if action not in ('report-errors', 'report-check-results'):
  42. print('Unknown action:', action, file=sys.stderr)
  43. sys.exit(1)
  44. content = sys.stdin.read().strip()
  45. if action == 'report-errors':
  46. comment_body = COMMENT_ERROR.format(build_id=BUILD_ID, content=content)
  47. comment_once = False
  48. elif action == 'report-check-results':
  49. comment_body = COMMENT_CHECK.format(content=content)
  50. comment_once = True
  51. if post_comment(PR_ID, comment_body, comment_once):
  52. print('Success.')
  53. else:
  54. print('Error sending data to tldr-bot!', file=sys.stderr)
  55. ################################################################################
  56. if __name__ == '__main__':
  57. REPO_SLUG = os.environ.get('TRAVIS_REPO_SLUG')
  58. PR_ID = os.environ.get('TRAVIS_PULL_REQUEST')
  59. BUILD_ID = os.environ.get('TRAVIS_BUILD_ID')
  60. if PR_ID is None or BUILD_ID is None or REPO_SLUG is None:
  61. print('Needed environment variables are not set.', file=sys.stderr)
  62. sys.exit(1)
  63. if PR_ID is None or PR_ID == 'false':
  64. print('Not a pull request, refusing to run.', file=sys.stderr)
  65. sys.exit(0)
  66. if len(sys.argv) != 2:
  67. print('Usage:', sys.argv[0], '<ACTION>', file=sys.stderr)
  68. sys.exit(1)
  69. main(sys.argv[1])