send-to-bot.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 = """<!-- tldr-bot - errors -->
  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 = """<!-- tldr-bot - check-results -->
  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):
  21. endpoint = f"{BOT_URL}/comment/recreate"
  22. data = {"pr_id": pr_id, "body": body}
  23. try:
  24. with requests.post(endpoint, json=data) as r:
  25. if r.status_code != requests.codes.ok:
  26. print(
  27. "Error: tldr-bot responded with code",
  28. r.status_code,
  29. file=sys.stderr,
  30. )
  31. print(r.text, file=sys.stderr)
  32. return False
  33. except requests.exceptions.RequestException as e:
  34. print("Error sending data to tldr-bot:", str(e), file=sys.stderr)
  35. return False
  36. return True
  37. def main(action):
  38. if action not in ("report-errors", "report-check-results"):
  39. print("Unknown action:", action, file=sys.stderr)
  40. sys.exit(1)
  41. content = sys.stdin.read().strip()
  42. if action == "report-errors":
  43. comment_body = COMMENT_ERROR.format(build_id=BUILD_ID, content=content)
  44. elif action == "report-check-results":
  45. comment_body = COMMENT_CHECK.format(content=content)
  46. if post_comment(PR_ID, comment_body):
  47. print("Success.")
  48. else:
  49. print("Error sending data to tldr-bot!", file=sys.stderr)
  50. ################################################################################
  51. if __name__ == "__main__":
  52. REPO_SLUG = os.environ.get("GITHUB_REPOSITORY")
  53. PR_ID = os.environ.get("PULL_REQUEST_ID")
  54. BUILD_ID = os.environ.get("GITHUB_RUN_ID")
  55. if PR_ID is None or BUILD_ID is None or REPO_SLUG is None:
  56. print("Needed environment variables are not set.", file=sys.stderr)
  57. sys.exit(1)
  58. if PR_ID is None or PR_ID == "false":
  59. print("Not a pull request, refusing to run.", file=sys.stderr)
  60. sys.exit(0)
  61. if len(sys.argv) != 2:
  62. print("Usage:", sys.argv[0], "<ACTION>", file=sys.stderr)
  63. sys.exit(1)
  64. main(sys.argv[1])