send-to-bot.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. import os
  4. import sys
  5. import json
  6. import urllib.request
  7. BOT_URL = 'https://tldr-bot.starbeamrainbowlabs.com'
  8. COMMENT_ERROR="""
  9. The [build](https://github.com/tldr-pages/tldr/actions/runs/{build_id}) 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 double-check the commits.
  19. """
  20. ################################################################################
  21. def post_comment(pr_id, body, once):
  22. endpoint = BOT_URL + '/comment'
  23. if once:
  24. endpoint += '/once'
  25. headers = {'Content-Type': 'application/json'}
  26. data = json.dumps({'pr_id': pr_id, 'body': body})
  27. req = urllib.request.Request(endpoint, data.encode(), headers)
  28. try:
  29. resp = urllib.request.urlopen(req)
  30. code = resp.getcode()
  31. except Exception as e:
  32. print('Error sending data to tldr-bot:', str(e), file=sys.stderr)
  33. return False
  34. if code != 200:
  35. print('Error: tldr-bot responded with code', code, file=sys.stderr)
  36. print(resp.read(), file=sys.stderr)
  37. return False
  38. return True
  39. def main(action):
  40. if action not in ('report-errors', 'report-check-results'):
  41. print('Unknown action:', action, file=sys.stderr)
  42. sys.exit(1)
  43. content = sys.stdin.read().strip()
  44. if action == 'report-errors':
  45. comment_body = COMMENT_ERROR.format(build_id=BUILD_ID, content=content)
  46. comment_once = False
  47. elif action == 'report-check-results':
  48. comment_body = COMMENT_CHECK.format(content=content)
  49. comment_once = True
  50. if post_comment(PR_ID, comment_body, comment_once):
  51. print('Success.')
  52. else:
  53. print('Error sending data to tldr-bot!', file=sys.stderr)
  54. ################################################################################
  55. if __name__ == '__main__':
  56. REPO_SLUG = os.environ.get('GITHUB_REPOSITORY')
  57. PR_ID = os.environ.get('PULL_REQUEST_ID')
  58. BUILD_ID = os.environ.get('GITHUB_RUN_ID')
  59. if PR_ID is None or BUILD_ID is None or REPO_SLUG is None:
  60. print('Needed environment variables are not set.', file=sys.stderr)
  61. sys.exit(1)
  62. if PR_ID is None or PR_ID == 'false':
  63. print('Not a pull request, refusing to run.', file=sys.stderr)
  64. sys.exit(0)
  65. if len(sys.argv) != 2:
  66. print('Usage:', sys.argv[0], '<ACTION>', file=sys.stderr)
  67. sys.exit(1)
  68. main(sys.argv[1])