send-to-bot.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. import os
  4. import sys
  5. import requests
  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. data = {"pr_id": pr_id, "body": body}
  25. try:
  26. with requests.post(endpoint, json=data) as r:
  27. if r.status_code != requests.codes.ok:
  28. print(
  29. "Error: tldr-bot responded with code",
  30. r.status_code,
  31. file=sys.stderr,
  32. )
  33. print(r.text, file=sys.stderr)
  34. return False
  35. except requests.exceptions.RequestException as e:
  36. print("Error sending data to tldr-bot:", str(e), 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])