Skip to content

Commit

Permalink
Merge pull request #12 from toddrob99/alpha
Browse files Browse the repository at this point in the history
Platform:
VER: v0.0.7
NEW: Add docker-compose.yml
ENH: Update docker image to python-3.8.3

Game Thread Bot:
VER: v0.0.7
NEW: Telegram-compatible webhook templates
FIX: Thread update process crashes on game with team that has no Division ("Intrasquad")
FIX: Support for some new data permutations during weird season
FIX: Data issues with seasonState and game_thread template
  • Loading branch information
toddrob99 authored Jul 18, 2020
2 parents b55a71e + 593c726 commit 3fe8ce4
Show file tree
Hide file tree
Showing 14 changed files with 71 additions and 36 deletions.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
FROM python:alpine3.8
FROM python:3.8.3-alpine

LABEL Name=redball Version=0.0.6
LABEL Name=redball Version=0.0.7

WORKDIR /app
ADD . /app
Expand Down
62 changes: 34 additions & 28 deletions bots/game_threads/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

import praw

__version__ = "0.0.6"
__version__ = "0.0.7"


def run(bot, settings):
Expand Down Expand Up @@ -126,7 +126,8 @@ def run(self):
break

self.myTeam = self.get_team(
self.settings.get("MLB", {}).get("TEAM", "").split("|")[1]
self.settings.get("MLB", {}).get("TEAM", "").split("|")[1],
s=datetime.now().strftime("%Y") # band-aid due to MLB defaulting team page to 2021 season in July 2020
)
self.log.info("Configured team: {}".format(self.myTeam["name"]))

Expand All @@ -150,7 +151,7 @@ def run(self):
)
)
self.error_notification(
f"Error overriding game date. Falling back to today's date"
"Error overriding game date. Falling back to today's date"
)
todayObj = datetime.today()
else:
Expand Down Expand Up @@ -674,7 +675,7 @@ def run(self):
)
)
self.error_notification(
f"Game day thread update process is not running"
"Game day thread update process is not running"
)
self.THREADS.update(
{
Expand Down Expand Up @@ -815,7 +816,7 @@ def off_day(self):
e
)
)
self.error_notification(f"Off day thread update process is not running")
self.error_notification("Off day thread update process is not running")
self.THREADS.update(
{
"OFFDAY_THREAD": threading.Thread(
Expand Down Expand Up @@ -1260,7 +1261,7 @@ def off_thread_update_loop(self):
self.count_check_edit(offDayThread.id, "NA", edit=False)
except Exception as e:
self.log.error("Error editing off day thread: {}".format(e))
self.error_notification(f"Error editing off day thread")
self.error_notification("Error editing off day thread")

update_off_thread_until = self.settings.get("Off Day Thread", {}).get(
"UPDATE_UNTIL", "All MLB games are final"
Expand Down Expand Up @@ -1289,8 +1290,8 @@ def off_thread_update_loop(self):
and x["status"]["codedGameState"] not in ["C", "D", "U", "T"]
and self.myTeam["division"]["id"]
in [
x["teams"]["away"]["team"]["division"]["id"],
x["teams"]["home"]["team"]["division"]["id"],
x["teams"]["away"]["team"].get("division", {}).get("id"),
x["teams"]["home"]["team"].get("division", {}).get("id"),
]
),
False,
Expand Down Expand Up @@ -1569,7 +1570,7 @@ def gameday_thread_update_loop(self, todayGamePks):
)
except Exception as e:
self.log.error("Error editing game day thread: {}".format(e))
self.error_notification(f"Error editing game day thread")
self.error_notification("Error editing game day thread")

update_gameday_thread_until = self.settings.get("Game Day Thread", {}).get(
"UPDATE_UNTIL", "Game thread is posted"
Expand Down Expand Up @@ -1636,8 +1637,8 @@ def gameday_thread_update_loop(self, todayGamePks):
and x["status"]["codedGameState"] not in ["C", "D", "U", "T"]
and self.myTeam["division"]["id"]
in [
x["teams"]["away"]["team"]["division"]["id"],
x["teams"]["home"]["team"]["division"]["id"],
x["teams"]["away"]["team"].get("division", {}).get("id"),
x["teams"]["home"]["team"].get("division", {}).get("id"),
]
),
False,
Expand Down Expand Up @@ -2187,8 +2188,8 @@ def game_thread_update_loop(self, pk):
and x["status"]["codedGameState"] not in ["C", "D", "U", "T"]
and self.myTeam["division"]["id"]
in [
x["teams"]["away"]["team"]["division"]["id"],
x["teams"]["home"]["team"]["division"]["id"],
x["teams"]["away"]["team"].get("division", {}).get("id"),
x["teams"]["home"]["team"].get("division", {}).get("id"),
]
),
False,
Expand Down Expand Up @@ -2374,7 +2375,7 @@ def postgame_thread_update_loop(self, pk):
)
postGameThread = self.reddit.submission(pgThread[0]["id"])
if not postGameThread.author:
self.log.warning("Game day thread appears to have been deleted.")
self.log.warning("Post game thread appears to have been deleted.")
q = "update {}threads set deleted=1 where id='{}';".format(
self.dbTablePrefix, postGameThread.id
)
Expand Down Expand Up @@ -2544,8 +2545,8 @@ def postgame_thread_update_loop(self, pk):
and x["status"]["codedGameState"] not in ["C", "D", "U", "T"]
and self.myTeam["division"]["id"]
in [
x["teams"]["away"]["team"]["division"]["id"],
x["teams"]["home"]["team"]["division"]["id"],
x["teams"]["away"]["team"].get("division", {}).get("id"),
x["teams"]["home"]["team"].get("division", {}).get("id"),
]
),
False,
Expand Down Expand Up @@ -3361,7 +3362,7 @@ def patch_dict(self, theDict, patch):
# do nothing, because it will be handled on the next loop
if redball.DEV:
self.log.debug(
f"missing key, but not a problem because op=add; continuing..."
"missing key, but not a problem because op=add; continuing..."
)
continue
else:
Expand Down Expand Up @@ -3442,6 +3443,7 @@ def get_gamePks(self, t=None, o=None, d=None, sd=None, ed=None):
return pks

def get_seasonState(self, t=None):
self.log.debug(f"myteam league seasondateinfo: {self.myTeam['league']['seasonDateInfo']}")
if (
datetime.strptime(
self.myTeam["league"]["seasonDateInfo"]["preSeasonStartDate"],
Expand Down Expand Up @@ -4802,9 +4804,13 @@ def get_schedule_data(
s = self.api_call("schedule", params)
return s

def get_team(self, t, h="league,division,venue(timezone)"):
# t = teamId, h = hydrate
return self.api_call("team", {"teamId": t, "hydrate": h})["teams"][0]
def get_team(self, t, h="league,division,venue(timezone)", s=None):
# t = teamId, h = hydrate, s = season
params = {"teamId": t, "hydrate": h}
if s:
params.update({"season": s})

return self.api_call("team", params)["teams"][0]

def log_last_updated_date_in_db(self, threadId, t=None):
# threadId = Reddit thread id that was edited, t = timestamp of edit
Expand Down Expand Up @@ -4988,7 +4994,7 @@ def prep_and_post(self, thread, pk=None, postFooter=None):
break
except Exception as e:
self.log.error("Error checking subreddit for existing posts: {}".format(e))
self.error_notification(f"Error checking subreddit for existing posts")
self.error_notification("Error checking subreddit for existing posts")

if not theThread:
try:
Expand Down Expand Up @@ -5170,7 +5176,7 @@ def prep_and_post(self, thread, pk=None, postFooter=None):
accessSecret=tAccessSecret,
)
if tweetResult:
self.log.info(f"Tweet submitted successfully!")
self.log.info("Tweet submitted successfully!")
else:
self.log.warning("No thread object present. Something went wrong!")

Expand Down Expand Up @@ -5253,7 +5259,7 @@ def post_webhook(self, url, body):
)
)
self.error_notification(
f"Failed to convert webhook template from json format. Ensure there are no line breaks or other special characters in the rendered template"
"Failed to convert webhook template from json format. Ensure there are no line breaks or other special characters in the rendered template"
)
return "Failed to convert webhook template from json format. Ensure there are no line breaks or other special characters in the rendered template. Error: {}".format(
e
Expand Down Expand Up @@ -5329,7 +5335,7 @@ def submit_reddit_post(
"Failed to set flair on thread {post.id} (check mod privileges or change FLAIR_MODE to submitter), continuing..."
)
self.error_notification(
f"Failed to set flair (check mod privileges or change FLAIR_MODE to submitter)"
"Failed to set flair (check mod privileges or change FLAIR_MODE to submitter)"
)

if sort not in [None, ""]:
Expand Down Expand Up @@ -5585,7 +5591,7 @@ def init_reddit(self):
self.log.error(
"Error encountered attempting to initialize Reddit: {}".format(e)
)
self.error_notification(f"Error initializing Reddit")
self.error_notification("Error initializing Reddit")
raise

scopes = [
Expand All @@ -5607,7 +5613,7 @@ def init_reddit(self):
)
)
self.error_notification(
f"Error encountered attempting to look up authorized Reddit scopes"
"Error encountered attempting to look up authorized Reddit scopes"
)
raise

Expand All @@ -5622,7 +5628,7 @@ def init_reddit(self):
)
)
self.error_notification(
f"Error encountered attempting to identify authorized Reddit user (identity scope may not be authorized)"
"Error encountered attempting to identify authorized Reddit user (identity scope may not be authorized)"
)

for scope in scopes:
Expand Down Expand Up @@ -6272,7 +6278,7 @@ def bot_state(self):
"markdown": "Error retrieving bot state: {}".format(e),
},
}
self.error_notification(f"Error retrieving bot state")
self.error_notification("Error retrieving bot state")

self.log.debug("Bot Status: {}".format(botStatus)) # debug
self.bot.detailedState = botStatus
3 changes: 3 additions & 0 deletions bots/game_threads/templates/comment_webhook_telegram.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## This template produces data in JSON format suitable for Telegram webhooks
## Be sure to include \n for line breaks, because actual linebreaks will be stripped out!
{"text": "${commentText.replace('"','\"').replace('\r','').replace('\n','\\n')}"}
2 changes: 1 addition & 1 deletion bots/game_threads/templates/game_thread.mako
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ ${'- ' + str(data[gamePk]['schedule']['linescore']['outs']) + ' out' + ('s' if d

## Game status is not final or live (except warmup), include standings, probable pitchers, lineups if posted
% if (data[gamePk]['schedule']['status']['abstractGameCode'] != 'L' or data[gamePk]['schedule']['status']['statusCode'] == 'PW') and data[gamePk]['schedule']['status']['abstractGameCode'] != 'F':
% if data[0]['myTeam']['seasonState'] == 'regular':
% if data[0]['myTeam']['seasonState'] == 'regular' and data[gamePk]['schedule']['gameType'] == "R":
<%include file="standings.mako" />
% endif

Expand Down
2 changes: 2 additions & 0 deletions bots/game_threads/templates/game_webhook_telegram.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## This template produces data in JSON format suitable for Telegram webhooks
{"text":"Game Thread Posted!\n${theThread.title}\n${theThread.shortlink}"}
2 changes: 1 addition & 1 deletion bots/game_threads/templates/gameday_thread.mako
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ ${'###'}\
## probable pitchers vs. teams
% endfor

% if data[0]['myTeam']['seasonState'] == 'regular':
% if data[0]['myTeam']['seasonState'] == 'regular' and data[pk]['schedule']['gameType'] == "R":
<%include file="standings.mako" />
% endif

Expand Down
2 changes: 2 additions & 0 deletions bots/game_threads/templates/gameday_webhook_telegram.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## This template produces data in JSON format suitable for Telegram webhooks
{"text":"Game Day Thread Posted!\n${theThread.title}\n${theThread.shortlink}"}
2 changes: 1 addition & 1 deletion bots/game_threads/templates/matchup.mako
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<%page args="gamePk,dateFormat='%a, %b %d @ %I:%M %p %Z'" />\
## Matchup header: Team names with links to team subs and matchup image, followed by game date
[${data[gamePk]['schedule']['teams']['away']['team']['teamName']}](${data[0]['teamSubs'][data[gamePk]['schedule']['teams']['away']['team']['id']]}) [@](http://mlb.mlb.com/images/2017_ipad/684/${data[gamePk]['schedule']['teams']['away']['team']['fileCode'] + data[gamePk]['schedule']['teams']['home']['team']['fileCode']}_684.jpg) [${data[gamePk]['schedule']['teams']['home']['team']['teamName']}](${data[0]['teamSubs'][data[gamePk]['schedule']['teams']['home']['team']['id']]}) - ${data[gamePk]['gameTime']['myTeam'].strftime(dateFormat)}
[${data[gamePk]['schedule']['teams']['away']['team']['teamName']}](${data[0]['teamSubs'].get(data[gamePk]['schedule']['teams']['away']['team']['id'], data[0]['teamSubs'][0])}) [@](http://mlb.mlb.com/images/2017_ipad/684/${data[gamePk]['schedule']['teams']['away']['team']['fileCode'] + data[gamePk]['schedule']['teams']['home']['team']['fileCode']}_684.jpg) [${data[gamePk]['schedule']['teams']['home']['team']['teamName']}](${data[0]['teamSubs'].get(data[gamePk]['schedule']['teams']['home']['team']['id'], data[0]['teamSubs'][0])}) - ${data[gamePk]['gameTime']['myTeam'].strftime(dateFormat)}
2 changes: 2 additions & 0 deletions bots/game_threads/templates/off_webhook_telegram.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## This template produces data in JSON format suitable for Telegram webhooks
{"text":"Off Day Thread Posted!\n${theThread.title}\n${theThread.shortlink}"}
2 changes: 2 additions & 0 deletions bots/game_threads/templates/post_webhook_telegram.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## This template produces data in JSON format suitable for Telegram webhooks
{"text":"Post Game Thread Posted!\n${theThread.title}\n${theThread.shortlink}"}
4 changes: 2 additions & 2 deletions bots/game_threads/templates/probable_pitchers.mako
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
%>\
||Probable Pitcher (Season Stats)|Report|
|:--|:--|:--|
|[${data[gamePk]['gumbo']["gameData"]["teams"]['away']['teamName']}](${data[0]['teamSubs'][data[gamePk]['gumbo']["gameData"]["teams"]['away']['id']]})|\
|[${data[gamePk]['gumbo']["gameData"]["teams"]['away']['teamName']}](${data[0]['teamSubs'].get(data[gamePk]['gumbo']["gameData"]["teams"]['away']['id'], data[0]['teamSubs'][0])})|\
${playerLink(awayPitcherData['person']['fullName'],awayPitcherData['person']['id']) if awayPitcherData['person']['fullName'] != 'TBD' else 'TBD'}\
% if awayPitcherData['person']['fullName'] != 'TBD':
(${awayPitcherData['seasonStats']['pitching'].get('wins',0)}-${awayPitcherData['seasonStats']['pitching'].get('losses',0)}, ${awayPitcherData['seasonStats']['pitching'].get('era','0')} ERA, ${awayPitcherData['seasonStats']['pitching'].get('inningsPitched',0)} IP)|\
Expand All @@ -20,7 +20,7 @@ ${playerLink(awayPitcherData['person']['fullName'],awayPitcherData['person']['id
% endif
${awayPitcher.get('note','No report posted.')}|
\
|[${data[gamePk]['gumbo']["gameData"]["teams"]['home']['teamName']}](${data[0]['teamSubs'][data[gamePk]['gumbo']["gameData"]["teams"]['home']['id']]})|\
|[${data[gamePk]['gumbo']["gameData"]["teams"]['home']['teamName']}](${data[0]['teamSubs'].get(data[gamePk]['gumbo']["gameData"]["teams"]['home']['id'], data[0]['teamSubs'][0])})|\
${playerLink(homePitcherData['person']['fullName'],homePitcherData['person']['id']) if homePitcherData['person']['fullName'] != 'TBD' else 'TBD'}\
% if homePitcherData['person']['fullName'] != 'TBD':
(${homePitcherData['seasonStats']['pitching'].get('wins',0)}-${homePitcherData['seasonStats']['pitching'].get('losses',0)}, ${homePitcherData['seasonStats']['pitching'].get('era','-')} ERA, ${homePitcherData['seasonStats']['pitching'].get('inningsPitched',0)} IP)|\
Expand Down
2 changes: 2 additions & 0 deletions bots/game_threads/templates/weekly_webhook_telegram.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## This template produces data in JSON format suitable for Telegram webhooks
{"text":"Weekly Thread Posted!\n${theThread.title}\n${theThread.shortlink}"}
16 changes: 16 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: '3.0'
services:
redball:
container_name: redball
image: toddrob/redball:latest
volumes:
- ./data:/app/data
- ./logs:/app/logs
- ./custom_templates:/app/custom_templates
- ./certs:/app/certs
environment:
- TZ=America/New_York
restart: unless-stopped
network_mode: bridge
ports:
- 8087:8087
2 changes: 1 addition & 1 deletion redball/version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/usr/bin/env python

VERSION = "0.0.6"
VERSION = "0.0.7"

0 comments on commit 3fe8ce4

Please sign in to comment.