diff --git a/compose.yaml b/compose.yaml index d70eb49..d9fe889 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,7 +2,7 @@ services: app: - image: ghcr.io/uberfastman/fantasy-football-metrics-weekly-report:19.2.1 + image: ghcr.io/uberfastman/fantasy-football-metrics-weekly-report:19.2.2 platform: linux/amd64 ports: - "5001:5000" diff --git a/integrations/base/integration.py b/integrations/base/integration.py index 9790b64..61a0733 100644 --- a/integrations/base/integration.py +++ b/integrations/base/integration.py @@ -1,7 +1,7 @@ from abc import ABC, abstractmethod from pathlib import Path -from typing import Any - +from typing import Any, Optional +from datetime import datetime from utilities.logger import get_logger logger = get_logger(__name__, propagate=False) @@ -9,10 +9,12 @@ class BaseIntegration(ABC): - def __init__(self, integration_type: str): + def __init__(self, integration_type: str, week: int): self.integration_type_str: str = integration_type.replace(" ", "_").lower() self.integration_type_title: str = integration_type.replace("_", " ").title() + self.week = week + logger.debug(f"Initializing {self.integration_type_title} integration.") self.client: Any = None @@ -21,6 +23,20 @@ def __init__(self, integration_type: str): self._authenticate() logger.debug(f"...{self.integration_type_title} authenticated.") + def _upload_success_message(self, file_name: str, drive_link: Optional[str] = None): + message = ( + f"\nFantasy Football Metrics Report for Week {self.week}: *{file_name}*\n" + f"Generated {datetime.now():%Y-%b-%d %H:%M:%S}" + ) + + if drive_link: + message += ( + f"\n\n_Google Drive Link:_\n" + f"{drive_link}" + ) + + return message + @abstractmethod def _authenticate(self) -> None: raise NotImplementedError diff --git a/integrations/discord.py b/integrations/discord.py index a3995f3..f8b43b4 100644 --- a/integrations/discord.py +++ b/integrations/discord.py @@ -16,10 +16,10 @@ class DiscordIntegration(BaseIntegration): - def __init__(self): + def __init__(self, week): self.root_dir = Path(__file__).parent.parent self.base_url = f"https://discord.com/api/webhooks" - super().__init__("discord") + super().__init__("discord", week) def _authenticate(self) -> None: @@ -46,10 +46,7 @@ def post_message(self, message: str) -> Dict: def upload_file(self, file_path: Path) -> Response: logger.debug(f"Uploading file to Discord: \n{file_path}") - message = ( - f"\nFantasy Football Report for {file_path.name}\n" - f"Generated {datetime.now():%Y-%b-%d %H:%M:%S}\n" - ) + message = self._upload_success_message(file_path.name) if settings.integration_settings.discord_channel_notify_bool: message = f"@everyone\n{message}" @@ -70,7 +67,7 @@ def upload_file(self, file_path: Path) -> Response: logger.info(f"Re-uploading {reupload_file.name} ({reupload_file}) to Discord...") - discord_integration = DiscordIntegration() + discord_integration = DiscordIntegration(settings.week_for_report) # logger.info(f"{json.dumps(discord_integration.post_message('test message'), indent=2)}") logger.info(f"{json.dumps(discord_integration.upload_file(reupload_file), indent=2)}") diff --git a/integrations/drive.py b/integrations/drive.py index 2989130..1c79dd3 100644 --- a/integrations/drive.py +++ b/integrations/drive.py @@ -5,7 +5,6 @@ import json import logging -from datetime import datetime from pathlib import Path from time import sleep from typing import List, Union @@ -30,9 +29,9 @@ class GoogleDriveIntegration(BaseIntegration): - def __init__(self): + def __init__(self, week): self.root_dir = Path(__file__).parent.parent - super().__init__("google_drive") + super().__init__("google_drive", week) def _authenticate(self) -> None: @@ -256,14 +255,7 @@ def upload_file(self, file_path: Union[str, Path], test: bool = False) -> str: } ) - return ( - f"\n" - f"Fantasy Football Report\n" - f"Generated {datetime.now():%Y-%b-%d %H:%M:%S}\n" - f"*{upload_file['title']}*\n\n" - f"_Google Drive Link:_\n" - f"{upload_file['alternateLink']}" - ) + return self._upload_success_message(upload_file["title"], drive_link=upload_file["alternateLink"]) if __name__ == "__main__": @@ -271,7 +263,7 @@ def upload_file(self, file_path: Union[str, Path], test: bool = False) -> str: logger.info(f"Re-uploading {reupload_file.name} ({reupload_file}) to Google Drive...") - google_drive_integration = GoogleDriveIntegration() + google_drive_integration = GoogleDriveIntegration(settings.week_for_report) upload_message = google_drive_integration.upload_file(reupload_file) logger.info(upload_message) diff --git a/integrations/groupme.py b/integrations/groupme.py index 50b6ba6..19bee7a 100644 --- a/integrations/groupme.py +++ b/integrations/groupme.py @@ -18,9 +18,9 @@ class GroupMeIntegration(BaseIntegration): - def __init__(self): + def __init__(self, week): self.root_dir = Path(__file__).parent.parent - super().__init__("groupme") + super().__init__("groupme", week) self.base_url = "https://api.groupme.com/v3" self.file_service_base_url = "https://file.groupme.com/v1" @@ -159,10 +159,7 @@ def post_message(self, message: str) -> Union[int, Dict]: def upload_file(self, file_path: Path) -> Union[int, Dict]: logger.debug(f"Uploading file to GroupMe: \n{file_path}") - message = ( - f"\nFantasy Football Report for {file_path.name}\n" - f"Generated {datetime.now():%Y-%b-%d %H:%M:%S}\n" - ) + message = self._upload_success_message(file_path.name) if settings.integration_settings.groupme_bot_or_user == "bot": return self._post_as_bot(message, file_path) @@ -182,7 +179,7 @@ def upload_file(self, file_path: Path) -> Union[int, Dict]: logger.info(f"Re-uploading {reupload_file.name} ({reupload_file}) to GroupMe...") - groupme_integration = GroupMeIntegration() + groupme_integration = GroupMeIntegration(settings.week_for_report) # logger.info(f"{json.dumps(groupme_integration.post_message('test message'), indent=2)}") logger.info(f"{json.dumps(groupme_integration.upload_file(reupload_file), indent=2)}") diff --git a/integrations/slack.py b/integrations/slack.py index ac573d6..bea1dda 100644 --- a/integrations/slack.py +++ b/integrations/slack.py @@ -4,7 +4,6 @@ import json import logging from asyncio import Future -from datetime import datetime from pathlib import Path from typing import Union @@ -26,9 +25,9 @@ class SlackIntegration(BaseIntegration): - def __init__(self): + def __init__(self, week): self.root_dir = Path(__file__).parent.parent - super().__init__("slack") + super().__init__("slack", week) def _authenticate(self) -> None: @@ -81,18 +80,14 @@ def upload_file(self, file_path: Path) -> Union[Future, SlackResponse]: logger.debug(f"Uploading file to Slack: \n{file_path}") try: - message = ( - f"\nFantasy Football Report for {file_path.name}\n" - f"Generated {datetime.now():%Y-%b-%d %H:%M:%S}\n" - ) + message = self._upload_success_message(file_path.name) + + if settings.integration_settings.slack_channel_notify_bool: + message = f"\n{message}" file_for_upload: Path = self.root_dir / file_path with open(file_for_upload, "rb") as uf: - if settings.integration_settings.slack_channel_notify_bool: - # post message with no additional content to trigger @here - self.post_message("") - response = self.client.files_upload_v2( channel=self._get_channel_id(settings.integration_settings.slack_channel), filename=file_for_upload.name, @@ -110,7 +105,7 @@ def upload_file(self, file_path: Path) -> Union[Future, SlackResponse]: logger.info(f"Re-uploading {reupload_file.name} ({reupload_file}) to Slack...") - slack_integration = SlackIntegration() + slack_integration = SlackIntegration(settings.week_for_report) # logger.info(f"\n{json.dumps(slack_integration.api_test().data, indent=2)}") # logger.info(f"{json.dumps(slack_integration.post_message('test message').data, indent=2)}") diff --git a/main.py b/main.py index eab355c..fc21ef1 100644 --- a/main.py +++ b/main.py @@ -310,7 +310,7 @@ def select_week(use_default: bool = False) -> Union[int, None]: upload_message = "" if settings.integration_settings.google_drive_upload_bool: if not options.get("test", False): - google_drive_integration = GoogleDriveIntegration() + google_drive_integration = GoogleDriveIntegration(report.league.week_for_report) # upload PDF to Google Drive upload_message = google_drive_integration.upload_file(report_pdf) @@ -320,13 +320,17 @@ def select_week(use_default: bool = False) -> Union[int, None]: if settings.integration_settings.slack_post_bool: if not options.get("test", False): - slack_integration = SlackIntegration() + slack_integration = SlackIntegration(report.league.week_for_report) # post PDF or link to PDF to Slack + slack_response = None post_or_file = settings.integration_settings.slack_post_or_file if post_or_file == "post": - # post shareable link to uploaded Google Drive PDF on Slack - slack_response = slack_integration.post_message(upload_message) + if settings.integration_settings.google_drive_upload_bool: + # post shareable link to uploaded Google Drive PDF on Slack + slack_response = slack_integration.post_message(upload_message) + else: + logger.warning("Unable to post Google Drive link to Slack when GOOGLE_DRIVE_UPLOAD_BOOL=False.") elif post_or_file == "file": # upload PDF report directly to Slack slack_response = slack_integration.upload_file(report_pdf) @@ -337,24 +341,28 @@ def select_week(use_default: bool = False) -> Union[int, None]: ) sys.exit(1) - if slack_response.get("ok"): + if slack_response and slack_response.get("ok"): logger.info(f"Report {str(report_pdf)} successfully posted to Slack!") else: logger.error( - f"Report {str(report_pdf)} was NOT posted to Slack with error: {slack_response.get('error')}" + f"Report {str(report_pdf)} was NOT posted to Slack with error: {slack_response}" ) else: logger.info("Test report NOT posted to Slack.") if settings.integration_settings.groupme_post_bool: if not options.get("test", False): - groupme_integration = GroupMeIntegration() + groupme_integration = GroupMeIntegration(report.league.week_for_report) # post PDF or link to PDF to GroupMe + groupme_response = None post_or_file = settings.integration_settings.groupme_post_or_file if post_or_file == "post": - # post shareable link to uploaded Google Drive PDF on GroupMe - groupme_response = groupme_integration.post_message(upload_message) + if settings.integration_settings.google_drive_upload_bool: + # post shareable link to uploaded Google Drive PDF on GroupMe + groupme_response = groupme_integration.post_message(upload_message) + else: + logger.warning("Unable to post Google Drive link to GroupMe when GOOGLE_DRIVE_UPLOAD_BOOL=False.") elif post_or_file == "file": # upload PDF report directly to GroupMe groupme_response = groupme_integration.upload_file(report_pdf) @@ -376,13 +384,18 @@ def select_week(use_default: bool = False) -> Union[int, None]: if settings.integration_settings.discord_post_bool: if not options.get("test", False): - discord_integration = DiscordIntegration() + discord_integration = DiscordIntegration(report.league.week_for_report) # post PDF or link to PDF to Discord + discord_response = None post_or_file = settings.integration_settings.discord_post_or_file if post_or_file == "post": - # post shareable link to uploaded Google Drive PDF on Discord - discord_response = discord_integration.post_message(upload_message) + if settings.integration_settings.google_drive_upload_bool: + # post shareable link to uploaded Google Drive PDF on Discord + discord_response = discord_integration.post_message(upload_message) + else: + logger.warning("Unable to post Google Drive link to Discord when GOOGLE_DRIVE_UPLOAD_BOOL=False.") + elif post_or_file == "file": # upload PDF report directly to Discord discord_response = discord_integration.upload_file(report_pdf) @@ -393,7 +406,7 @@ def select_week(use_default: bool = False) -> Union[int, None]: ) sys.exit(1) - if discord_response["type"] == 0: + if discord_response and discord_response.get("type") == 0: logger.info(f"Report {str(report_pdf)} successfully posted to Discord!") else: logger.error(