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 = """
  8. <!-- tldr-bot - errors -->
  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. <!-- tldr-bot - check-results -->
  17. Hello! I've noticed something unusual when checking this PR:
  18. {content}
  19. Is this intended? If so, just ignore this comment. Otherwise, please double-check the commits.
  20. """
  21. ################################################################################
  22. def post_comment(pr_id, body):
  23. endpoint = f"{BOT_URL}/comment/recreate"
  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. elif action == "report-check-results":
  47. comment_body = COMMENT_CHECK.format(content=content)
  48. if post_comment(PR_ID, comment_body):
  49. print("Success.")
  50. else:
  51. print("Error sending data to tldr-bot!", file=sys.stderr)
  52. ################################################################################
  53. if __name__ == "__main__":
  54. REPO_SLUG = os.environ.get("GITHUB_REPOSITORY")
  55. PR_ID = os.environ.get("PULL_REQUEST_ID")
  56. BUILD_ID = os.environ.get("GITHUB_RUN_ID")
  57. if PR_ID is None or BUILD_ID is None or REPO_SLUG is None:
  58. print("Needed environment variables are not set.", file=sys.stderr)
  59. sys.exit(1)
  60. if PR_ID is None or PR_ID == "false":
  61. print("Not a pull request, refusing to run.", file=sys.stderr)
  62. sys.exit(0)
  63. if len(sys.argv) != 2:
  64. print("Usage:", sys.argv[0], "<ACTION>", file=sys.stderr)
  65. sys.exit(1)
  66. main(sys.argv[1])