|
| 1 | +from collections import namedtuple |
| 2 | +from functools import lru_cache |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import re |
| 6 | + |
| 7 | +from github import Github, GithubException, UnknownObjectException |
| 8 | + |
| 9 | +from .github_tools import ( |
| 10 | + exception_to_github, |
| 11 | +) |
| 12 | + |
| 13 | +_LOGGER = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def order(function): |
| 17 | + function.bot_order = True |
| 18 | + return function |
| 19 | + |
| 20 | +WebhookMetadata = namedtuple( |
| 21 | + 'WebhookMetadata', |
| 22 | + ['repo', 'issue', 'text', 'comment'] |
| 23 | +) |
| 24 | + |
| 25 | +def build_from_issue_comment(gh_token, body): |
| 26 | + """Create a WebhookMetadata from a comment added to an issue. |
| 27 | + """ |
| 28 | + if body["action"] in ["created", "edited"]: |
| 29 | + github_con = Github(gh_token) |
| 30 | + repo = github_con.get_repo(body['repository']['full_name']) |
| 31 | + issue = repo.get_issue(body['issue']['number']) |
| 32 | + text = body['comment']['body'] |
| 33 | + try: |
| 34 | + comment = issue.get_comment(body['comment']['id']) |
| 35 | + except UnknownObjectException: |
| 36 | + # If the comment has already disapeared, skip the command |
| 37 | + return None |
| 38 | + return WebhookMetadata(repo, issue, text, comment) |
| 39 | + return None |
| 40 | + |
| 41 | +def build_from_issues(gh_token, body): |
| 42 | + """Create a WebhookMetadata from an opening issue text. |
| 43 | + """ |
| 44 | + if body["action"] in ["opened", "edited"]: |
| 45 | + github_con = Github(gh_token) |
| 46 | + repo = github_con.get_repo(body['repository']['full_name']) |
| 47 | + issue = repo.get_issue(body['issue']['number']) |
| 48 | + text = body['issue']['body'] |
| 49 | + comment = issue # It's where we update the comment: in the issue itself |
| 50 | + return WebhookMetadata(repo, issue, text, comment) |
| 51 | + return None |
| 52 | + |
| 53 | +@lru_cache() |
| 54 | +def robot_name_from_env_variable(): |
| 55 | + github_con = Github(os.environ["GH_TOKEN"]) |
| 56 | + return github_con.get_user().login |
| 57 | + |
| 58 | + |
| 59 | +class BotHandler: |
| 60 | + def __init__(self, handler, robot_name=None, gh_token=None): |
| 61 | + self.handler = handler |
| 62 | + self.gh_token = gh_token or os.environ["GH_TOKEN"] |
| 63 | + self.robot_name = robot_name or robot_name_from_env_variable() |
| 64 | + |
| 65 | + def _is_myself(self, body): |
| 66 | + return body['sender']['login'].lower() == self.robot_name.lower() |
| 67 | + |
| 68 | + def issue_comment(self, body): |
| 69 | + if self._is_myself(body): |
| 70 | + return {'message': 'I don\'t talk to myself, I\'m not schizo'} |
| 71 | + webhook_data = build_from_issue_comment(self.gh_token, body) |
| 72 | + return self.manage_comment(webhook_data) |
| 73 | + |
| 74 | + def issues(self, body): |
| 75 | + if self._is_myself(body): |
| 76 | + return {'message': 'I don\'t talk to myself, I\'m not schizo'} |
| 77 | + webhook_data = build_from_issues(self.gh_token, body) |
| 78 | + return self.manage_comment(webhook_data) |
| 79 | + |
| 80 | + def orders(self): |
| 81 | + """Return method tagged "order" in the handler. |
| 82 | + """ |
| 83 | + return [order_cmd for order_cmd in dir(self.handler) |
| 84 | + if getattr(getattr(self.handler, order_cmd), "bot_order", False)] |
| 85 | + |
| 86 | + def manage_comment(self, webhook_data): |
| 87 | + if webhook_data is None: |
| 88 | + return {'message': 'Nothing for me'} |
| 89 | + # Is someone talking to me: |
| 90 | + message = re.search("@{} (.*)".format(self.robot_name), webhook_data.text, re.I) |
| 91 | + response = None |
| 92 | + if message: |
| 93 | + command = message.group(1) |
| 94 | + split_text = command.lower().split() |
| 95 | + orderstr = split_text.pop(0) |
| 96 | + if orderstr == "help": |
| 97 | + response = self.help_order() |
| 98 | + elif orderstr in self.orders(): |
| 99 | + try: # Reaction is fun, but it's preview not prod. |
| 100 | + # Be careful, don't fail the command if we can't thumbs up... |
| 101 | + webhook_data.comment.create_reaction("+1") |
| 102 | + except GithubException: |
| 103 | + pass |
| 104 | + with exception_to_github(webhook_data.issue): # Just in case |
| 105 | + response = getattr(self.handler, orderstr)(webhook_data.issue, *split_text) |
| 106 | + else: |
| 107 | + response = "I didn't understand your command:\n```bash\n{}\n```\nin this context, sorry :(\n".format( |
| 108 | + command |
| 109 | + ) |
| 110 | + response += self.help_order() |
| 111 | + if response: |
| 112 | + webhook_data.issue.create_comment(response) |
| 113 | + return {'message': response} |
| 114 | + return {'message': 'Nothing for me or exception'} |
| 115 | + |
| 116 | + def help_order(self): |
| 117 | + orders = ["This is what I can do:"] |
| 118 | + for orderstr in self.orders(): |
| 119 | + orders.append("- `{}`".format(orderstr)) |
| 120 | + orders.append("- `help` : this help message") |
| 121 | + return "\n".join(orders) |
0 commit comments