1
0

send-to-bot.py 2.4 KB

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