Skip to content

Commit

Permalink
moved to mutual handler
Browse files Browse the repository at this point in the history
Signed-off-by: Trey <[email protected]>
  • Loading branch information
TreyWW committed Jul 22, 2024
1 parent f17d37b commit 4dd6887
Show file tree
Hide file tree
Showing 6 changed files with 224 additions and 99 deletions.
6 changes: 6 additions & 0 deletions .github/management_bot/pulumi/webhook_handler/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ class Objects:
dict_context: Context
repository: GithubRepository
sender: GithubNamedUser = None
target_discussion: GithubIssue | GithubPullRequest | None = None
target_discussion_type: str | None = None
issue: Optional[GithubIssue] = None
pull_request: Optional[GithubPullRequest] = None
labels: PaginatedList[GithubLabel] = None
Expand All @@ -100,9 +102,13 @@ def __post_init__(self):

if self.dict_context.issue:
self.issue = self.repository.get_issue(self.dict_context.issue.number)
self.target_discussion = self.issue
self.target_discussion_type = "issue"

if self.dict_context.pull_request:
self.pull_request = self.repository.get_pull(self.dict_context.pull_request.number)
self.target_discussion = self.pull_request
self.target_discussion_type = "pull_request"

if self.pull_request:
self.labels = self.pull_request.get_labels()
Expand Down
176 changes: 77 additions & 99 deletions .github/management_bot/pulumi/webhook_handler/issues/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,9 @@
if os.environ.get("AWS_EXECUTION_ENV") is not None:
import _types
import helpers
from .reminders import validate_reminder_command
import boto3_handler
else:
from .. import _types
from .. import helpers
from ..issues.reminders import validate_reminder_command
from .. import boto3_handler


def title_handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
Expand All @@ -44,108 +40,91 @@ def title_handler(context_dicts: _types.Context, context_objs: _types.Objects) -
return []


def delete_reply_handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
match = re.search(r"DELREPLY-(.{8})", context_dicts.comment.body)

if not match or context_objs.sender.type != "User":
return []

logger.info("Deleting comment due to DELREPLY in body")

reference_code = match.group(1)

logger.debug(f"Deleting comment with reference code: {reference_code}")

for comment in context_objs.issue.get_comments():
if f"DELREPLY-{reference_code}" in comment.body.upper():
comment.delete() # delete users reply comment
# context_objs.issue.get_comment(context_dicts.comment.id).delete() # delete bots comment
return ["deleted_issue_comment (DEL REPLY)"]


def command_handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
base_message = context_dicts.comment.body
split = base_message.split()
command = split[0]

logger.info(f"Extracted Command: {command}")

match command:
# <editor-fold desc="/project_info">
case "/project_info":
context_objs.issue.create_comment(
dedent(
f"""
You can view our documentation at\
[docs.myfinances.cloud](https://docs.myfinances.cloud/?utm_source=issue_{context_objs.issue.number}).
There you can find info such as:
- setting up guides
- code styles
- changelogs
- our discord server
- (soon) user usage guide
{f"> Mentioning @{split[1]}" if len(split) > 1 else ""}
{helpers.del_reply_comment()}
"""
)
)
return ["added_issue_comment (project info)"]
# </editor-fold>
# <editor-fold desc="/remind">
case "/remind":
logger.info("Using /remind")
if len(split) < 2:
logger.info("Invalid usage")
context_objs.issue.create_comment(
dedent(
f"""
Invalid usage. Example usage:
- `/remind 2d`
- `/remind 1w revamp this`
{helpers.del_reply_comment()}
"""
)
)
return ["added_issue_comment (invalid /remind args)"]

duration: str = split[1]
message: str = " ".join(split[2:]) if len(split) > 2 else ""

datetime_or_error = validate_reminder_command(split, context_objs)

logger.info(f"datetime_or_error: {datetime_or_error}")

if isinstance(datetime_or_error, list):
return datetime_or_error
# match command:
# # <editor-fold desc="/project_info">
# case "/project_info":
# context_objs.issue.create_comment(
# dedent(
# f"""
# You can view our documentation at\
# [docs.myfinances.cloud](https://docs.myfinances.cloud/?utm_source=issue_{context_objs.issue.number}).
#
# There you can find info such as:
# - setting up guides
# - code styles
# - changelogs
# - our discord server
# - (soon) user usage guide
#
# {f"> Mentioning @{split[1]}" if len(split) > 1 else ""}
#
# {helpers.del_reply_comment()}
# """
# )
# )
# return ["added_issue_comment (project info)"]
# # </editor-fold>
# # <editor-fold desc="/remind">
# case "/remind":
# logger.info("Using /remind")
# if len(split) < 2:
# logger.info("Invalid usage")
# context_objs.issue.create_comment(
# dedent(
# f"""
# Invalid usage. Example usage:
# - `/remind 2d`
# - `/remind 1w revamp this`
#
# {helpers.del_reply_comment()}
# """
# )
# )
# return ["added_issue_comment (invalid /remind args)"]
#
# duration: str = split[1]
# message: str = " ".join(split[2:]) if len(split) > 2 else ""
#
# datetime_or_error = validate_reminder_command(split, context_objs)
#
# logger.info(f"datetime_or_error: {datetime_or_error}")
#
# if isinstance(datetime_or_error, list):
# return datetime_or_error
#
# resp = boto3_handler.create_reminder(
# comment_id=context_objs,
# date_time=datetime_or_error.strftime("%Y-%m-%dT%H:%M:%S"),
# pr_id=None,
# issue_id=context_objs.issue.number,
# message=message,
# user=context_objs.sender.login,
# )
# logger.info(f"resp: {resp}")
#
# context_objs.issue.create_comment(
# dedent(
# f"""
# @{context_objs.sender.login}, ok! I will remind you {datetime_or_error.strftime("on %A, %B %-m, %y at %-H:%M %p")}!
#
# {helpers.del_reply_comment()}
# """
# )
# )
# return ["added_issue_comment (reminder success)"]
# case _:
# logger.info("No issue command")
# return []
# # </editor-fold>

resp = boto3_handler.create_reminder(
comment_id=context_objs,
date_time=datetime_or_error.strftime("%Y-%m-%dT%H:%M:%S"),
pr_id=None,
issue_id=context_objs.issue.number,
message=message,
user=context_objs.sender.login,
)
logger.info(f"resp: {resp}")

context_objs.issue.create_comment(
dedent(
f"""
@{context_objs.sender.login}, ok! I will remind you {datetime_or_error.strftime("on %A, %B %-m, %y at %-H:%M %p")}!
{helpers.del_reply_comment()}
"""
)
)
return ["added_issue_comment (reminder success)"]
case _:
logger.info("No issue command")
return []
# </editor-fold>
return []


def handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
Expand All @@ -160,6 +139,5 @@ def handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list
responses.extend(title_handler(context_dicts, context_objs))
case "created":
if context_dicts.comment:
responses.extend(delete_reply_handler(context_dicts, context_objs))
responses.extend(command_handler(context_dicts, context_objs))
return responses
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import github.GithubException
from prs import handler as pr_handler
from issues import handler as issue_handler
from pr_and_issues import handler as pr_and_issue_handler
from helpers import decode_private_key
import _types
from github import Github, Issue, GithubIntegration
Expand Down Expand Up @@ -101,6 +102,10 @@ def lambda_handler(event: dict, lambda_context):

actions_taken = []

if context_objs.target_discussion:
logger.debug("Using discussion handler")
actions_taken.extend(pr_and_issue_handler.handler(context_dicts, context_objs))

if context_dicts.pull_request:
logger.debug("Using PR handler")
actions_taken.extend(pr_handler.handler(context_dicts, context_objs))
Expand Down
Empty file.
136 changes: 136 additions & 0 deletions .github/management_bot/pulumi/webhook_handler/pr_and_issues/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import os
import re
from textwrap import dedent
import logging

logger = logging.getLogger(__name__)
if os.environ.get("AWS_EXECUTION_ENV") is not None:
import _types
import helpers
from .reminders import validate_reminder_command
import boto3_handler
else:
from .. import _types
from .. import helpers
from ..pr_and_issues.reminders import validate_reminder_command
from .. import boto3_handler


def delete_reply_handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
match = re.search(r"DELREPLY-(.{8})", context_dicts.comment.body)

if not match or context_objs.sender.type != "User":
return []

logger.info("Deleting comment due to DELREPLY in body")

reference_code = match.group(1)

logger.debug(f"Deleting comment with reference code: {reference_code}")

for comment in context_objs.target_discussion.get_comments():
if f"DELREPLY-{reference_code}" in comment.body.upper():
comment.delete() # delete users reply comment
# context_objs.target_discussion.get_comment(context_dicts.comment.id).delete() # delete bots comment
return ["deleted_issue_comment (DEL REPLY)"]


def command_handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
base_message = context_dicts.comment.body
split = base_message.split()
command = split[0]

logger.info(f"Extracted Command: {command}")

match command:
# <editor-fold desc="/project_info">
case "/project_info":
context_objs.target_discussion.create_comment(
dedent(
f"""
You can view our documentation at\
[docs.myfinances.cloud](https://docs.myfinances.cloud/\
?utm_source={context_objs.target_discussion_type}_{context_objs.target_discussion.number}).
There you can find info such as:
- setting up guides
- code styles
- changelogs
- our discord server
- (soon) user usage guide
{f"> Mentioning @{split[1]}" if len(split) > 1 else ""}
{helpers.del_reply_comment()}
"""
)
)
return ["added_issue_comment (project info)"]
# </editor-fold>
# <editor-fold desc="/remind">
case "/remind":
logger.info("Using /remind")
if len(split) < 2:
logger.info("Invalid usage")
context_objs.target_discussion.create_comment(
dedent(
f"""
Invalid usage. Example usage:
- `/remind 2d`
- `/remind 1w revamp this`
{helpers.del_reply_comment()}
"""
)
)
return ["added_issue_comment (invalid /remind args)"]

duration: str = split[1]
message: str = " ".join(split[2:]) if len(split) > 2 else ""

datetime_or_error = validate_reminder_command(split, context_objs)

logger.info(f"datetime_or_error: {datetime_or_error}")

if isinstance(datetime_or_error, list):
return datetime_or_error

resp = boto3_handler.create_reminder(
comment_id=context_objs,
date_time=datetime_or_error.strftime("%Y-%m-%dT%H:%M:%S"),
pr_id=None,
issue_id=context_objs.target_discussion.number,
message=message,
user=context_objs.sender.login,
)
logger.info(f"resp: {resp}")

context_objs.target_discussion.create_comment(
dedent(
f"""
@{context_objs.sender.login}, ok! I will remind you {datetime_or_error.strftime("on %A, %B %-m, %y at %-H:%M %p")}!
{helpers.del_reply_comment()}
"""
)
)
return ["added_issue_comment (reminder success)"]
case _:
logger.info("No issue command")
return []
# </editor-fold>


def handler(context_dicts: _types.Context, context_objs: _types.Objects) -> list[str]:
logger.info(f"action: {context_dicts.action}")
responses = []
match context_dicts.action:
case "opened":
...
case "edited":
...
case "created":
if context_dicts.comment:
responses.extend(delete_reply_handler(context_dicts, context_objs))
responses.extend(command_handler(context_dicts, context_objs))
return responses

0 comments on commit 4dd6887

Please sign in to comment.