Skip to content

Commit

Permalink
made integrations message consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
uberfastman committed Oct 17, 2024
1 parent 16acb9c commit 1bbebe1
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 55 deletions.
2 changes: 1 addition & 1 deletion compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
22 changes: 19 additions & 3 deletions integrations/base/integration.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
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)


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
Expand All @@ -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
Expand Down
11 changes: 4 additions & 7 deletions integrations/discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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}"
Expand All @@ -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)}")
16 changes: 4 additions & 12 deletions integrations/drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:

Expand Down Expand Up @@ -256,22 +255,15 @@ 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__":
reupload_file = settings.integration_settings.reupload_file_path

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)
11 changes: 4 additions & 7 deletions integrations/groupme.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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)}")
19 changes: 7 additions & 12 deletions integrations/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import json
import logging
from asyncio import Future
from datetime import datetime
from pathlib import Path
from typing import Union

Expand All @@ -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:

Expand Down Expand Up @@ -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"<!here>\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,
Expand All @@ -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)}")
Expand Down
39 changes: 26 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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(
Expand Down

0 comments on commit 1bbebe1

Please sign in to comment.