Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

10k post limit #17

Draft
wants to merge 7 commits into
base: lemmy
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 115 additions & 9 deletions bots/lemmy_mlb_game_threads/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,7 +958,8 @@ def off_thread_update_loop(self):
}
)
# Only sticky when posting the thread
if self.settings.get('Reddit',{}).get('STICKY',False): self.sticky_thread(offDayThread)
if self.settings.get("Reddit", {}).get("STICKY", False):
self.sticky_thread(offDayThread)

if not offDayThread:
(offDayThread, offDayThreadText) = self.prep_and_post(
Expand Down Expand Up @@ -1030,15 +1031,19 @@ def off_thread_update_loop(self):
text = self._truncate_post(text)
self.lemmy.editPost(offDayThread["post"]["id"], text)
self.log.info("Off day thread edits submitted.")
self.count_check_edit(offDayThread["post"]["id"], "NA", edit=True)
self.count_check_edit(
offDayThread["post"]["id"], "NA", edit=True
)
self.log_last_updated_date_in_db(offDayThread["post"]["id"])
elif text == "":
self.log.info(
"Skipping off day thread edit since thread text is blank..."
)
else:
self.log.info("No changes to off day thread.")
self.count_check_edit(offDayThread["post"]["id"], "NA", edit=False)
self.count_check_edit(
offDayThread["post"]["id"], "NA", edit=False
)
except Exception as e:
self.log.error("Error editing off day thread: {}".format(e))
self.error_notification("Error editing off day thread")
Expand Down Expand Up @@ -1255,7 +1260,8 @@ def gameday_thread_update_loop(self, todayGamePks):
}
)
# Only sticky when posting the thread
if self.settings.get('Reddit',{}).get('STICKY',False): self.sticky_thread(gameDayThread)
if self.settings.get("Reddit", {}).get("STICKY", False):
self.sticky_thread(gameDayThread)

# Check if post game thread is already posted, and skip game day thread if so
if (
Expand Down Expand Up @@ -1871,6 +1877,40 @@ def game_thread_update_loop(self, pk):
"Game thread is disabled, so skipping for game {}...".format(pk)
)
else:
# Submit Highlights Thread
# Something is funky in the return logic after the game thread,
# so submit the hightlights thread first
if self.settings.get("Highlight Thread", {}).get("ENABLED", False):
self.log.info("Preparing to post highlight {} thread...".format(pk))
(highlightThread, highlightThreadText) = self.prep_and_post(
"highlight",
pk,
postFooter="""

Posted: """
+ self.convert_timezone(
datetime.utcnow(), self.myTeam["venue"]["timeZone"]["id"]
).strftime("%m/%d/%Y %I:%M:%S %p %Z"),
)
self.activeGames[pk].update(
{
"highlightThread": highlightThread,
"highlightThreadText": highlightThreadText,
"highlightThreadTitle": highlightThread["post"]["name"]
if highlightThread not in [None, False]
else None,
}
)
# Thread is not posted, so don't start an update loop
if not self.activeGames[pk].get(
"highlightThread"
) and self.settings.get("Highlight Thread", {}).get("ENABLED", True):
# Thread is enabled but failed to post
self.log.info(
"Highlight thread not posted. Don't try to update it."
)
self.activeGames[pk].update({"highlightThreadSkip": True})

# Submit Game Thread
self.log.info("Preparing to post game {} thread...".format(pk))
(gameThread, gameThreadText) = self.prep_and_post(
Expand Down Expand Up @@ -2025,6 +2065,62 @@ def game_thread_update_loop(self, pk):
self.commonData[pk]["schedule"]["status"]["statusCode"],
edit=False,
)
if self.settings.get("Highlight Thread", {}).get(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This all looks good but what do you think about splitting the highlight thread code into it's own function or file + function? Use it as sort of a template for future refactoring?

"ENABLED", False
) and not self.activeGames[pk].get("highlightSkip", False):
# Re-generate highlight thread code, compare to current code, edit if different
text = self.render_template(
thread="highlight",
templateType="thread",
data=self.commonData,
gamePk=pk,
settings=self.settings,
)
self.log.debug(
"rendered highlight {} thread text: {}".format(pk, text)
)
if (
text != self.activeGames[pk].get("highlightThreadText")
and text != ""
):
self.activeGames[pk].update({"highlightThreadText": text})
# Add last updated timestamp
text += """

Last Updated: """ + self.convert_timezone(
datetime.utcnow(), self.myTeam["venue"]["timeZone"]["id"]
).strftime(
"%m/%d/%Y %I:%M:%S %p %Z"
)
text = self._truncate_post(text)
self.lemmy.editPost(
self.activeGames[pk]["highlightThread"]["post"]["id"],
body=text,
)
self.log.info(
"Edits submitted for {} highlight thread.".format(pk)
)
self.count_check_edit(
self.activeGames[pk]["highlightThread"]["post"]["id"],
self.commonData[pk]["schedule"]["status"]["statusCode"],
edit=True,
)
self.log_last_updated_date_in_db(
self.activeGames[pk]["highlightThread"]["post"]["id"]
)
elif text == "":
self.log.info(
"Skipping highlight thread {} edit since thread text is blank...".format(
pk
)
)
else:
self.log.info("No changes to {} highlight thread.".format(pk))
self.count_check_edit(
self.activeGames[pk]["highlightThread"]["post"]["id"],
self.commonData[pk]["schedule"]["status"]["statusCode"],
edit=False,
)

update_game_thread_until = self.settings.get("Game Thread", {}).get(
"UPDATE_UNTIL", ""
Expand Down Expand Up @@ -2191,6 +2287,9 @@ def game_thread_update_loop(self, pk):
# Mark game thread as stale
if self.activeGames[pk].get("gameThread"):
self.staleThreads.append(self.activeGames[pk]["gameThread"])
# If there is a highlight thread, unsticky it as well
if self.activeGames[pk].get("highlightThread", None):
self.staleThreads.append(self.activeGames[pk]["highlightThread"])

self.log.debug("Ending game update thread...")
return
Expand Down Expand Up @@ -2314,7 +2413,8 @@ def postgame_thread_update_loop(self, pk):
}
)
# Only sticky when posting the thread
if self.settings.get('Reddit',{}).get('STICKY',False): self.sticky_thread(self.activeGames[pk]['postGameThread'])
if self.settings.get("Reddit", {}).get("STICKY", False):
self.sticky_thread(self.activeGames[pk]["postGameThread"])

game_result = (
"EXCEPTION"
Expand Down Expand Up @@ -3927,7 +4027,7 @@ def collect_data(self, gamePk):
if len(gamePks) == 0:
self.log.warning("No gamePks to collect data for.")
return False

for pk in gamePks[:]:
if self.commonData.get(pk) and self.commonData[pk].get(
"lastUpdate", datetime.today() - timedelta(hours=1)
Expand Down Expand Up @@ -5195,7 +5295,7 @@ def count_check_edit(self, threadId, status, edit=False):
return True

def prep_and_post(self, thread, pk=None, postFooter=None):
# thread = ['weekly', 'off', 'gameday', 'game', 'post']
# thread = ['weekly', 'off', 'gameday', 'game', 'post', 'highlight']
# pk = gamePk or list of gamePks
# postFooter = text to append to post body, but not to include in return text value
# (normally contains a timestamp that would prevent comparison next time to check for changes)
Expand Down Expand Up @@ -5230,6 +5330,8 @@ def prep_and_post(self, thread, pk=None, postFooter=None):
if thread == "game"
else self.settings.get("Post Game Thread", {}).get("TITLE_MOD", "")
if thread == "post"
else self.settings.get("Highlight Thread", {}).get("TITLE_MOD", "")
if thread == "highlight"
else ""
)
if "upper" in title_mod.lower():
Expand Down Expand Up @@ -5446,6 +5548,8 @@ def render_template(self, thread, templateType, **kwargs):
if thread == "post"
else self.settings.get("Comments", {}).get(setting, "")
if thread == "comment"
else self.settings.get("Highlight Thread", {}).get(setting, "")
if thread == "highlight"
else ""
)
try:
Expand Down Expand Up @@ -6331,9 +6435,11 @@ def bot_state(self):

def _truncate_post(self, text):
warning_text = " \ # Truncated, post length limit reached."
max_length = self.settings.get("Lemmy", {}).get("POST_CHARACTER_LIMIT", 10000) - len(warning_text)
max_length = self.settings.get("Lemmy", {}).get(
"POST_CHARACTER_LIMIT", 10000
) - len(warning_text)
if len(text) >= max_length:
new_text = text[0:max_length - 1]
new_text = text[0 : max_length - 1]
new_text += warning_text
else:
new_text = text
Expand Down
2 changes: 2 additions & 0 deletions bots/lemmy_mlb_game_threads/templates/game_thread.mako
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,10 @@ ${ondeck} is on deck\
<%include file="scoring_plays.mako" />

% endif
% if not settings.get('Game Thread',{}).get('SUPPRESS_HIGHLIGHTS', False):
<%include file="highlights.mako" />

%endif
<%include file="linescore.mako" />
% endif
% if data[gamePk]['schedule']['status']['abstractGameCode'] == 'F' and not settings.get('Game Thread',{}).get('SUPPRESS_DECISIONS', False):
Expand Down
16 changes: 16 additions & 0 deletions bots/lemmy_mlb_game_threads/templates/highlight_thread.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<%
from datetime import datetime
import pytz
%>\
## Header: Team names with links to team subs and matchup image, followed by game date
${'# '}<%include file="matchup.mako" args="dateFormat='%a, %b %d'" />

## If game status is final, or live and not warmup, include boxscore, scoring plays, highlights, and linescore
% if (data[gamePk]['schedule']['status']['abstractGameCode'] == 'L' and data[gamePk]['schedule']['status']['statusCode'] != 'PW') or data[gamePk]['schedule']['status']['abstractGameCode'] == 'F':
<%include file="scoring_plays.mako" />

<%include file="highlights.mako" />
% endif

## configurable footer text
${settings.get('Highlight Thread',{}).get('FOOTER','')}
25 changes: 25 additions & 0 deletions bots/lemmy_mlb_game_threads/templates/highlight_title.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<%
from datetime import datetime
prefix = settings.get("Highlight Thread", {}).get("TITLE_PREFIX","Highlight Thread:")
dateFormat = settings.get("Highlight Thread", {}).get("DATE_FORMAT","%a, %b %d @ %I:%M %p %Z")
dhDateFormat = settings.get("Highlight Thread", {}).get("DATE_FORMAT_DH","%a, %b %d")
%>\
${prefix + (" " if len(prefix) and not prefix.endswith(" ") else "")}\
%if data[gamePk]['schedule'].get('seriesDescription') and data[gamePk]['schedule'].get('gameType') not in ['R','I','S','E']:
${data[gamePk]['schedule']['seriesDescription'] + ' '}\
${'Game ' + str(data[gamePk]['schedule']['seriesGameNumber']) + ' - ' if data[gamePk]['schedule'].get('seriesGameNumber') and data[gamePk]['schedule'].get('gamesInSeries',1) > 1 else '- '}\
%endif
%if data[0]["myTeam"].get("allStarStatus"):
${data[gamePk]['schedule']['teams']['away']['team']['teamName']} @ ${data[gamePk]['schedule']['teams']['home']['team']['teamName']}\
%else:
${data[gamePk]['schedule']['teams']['away']['team']['teamName']} (${data[gamePk]['schedule']['teams']['away']['leagueRecord']['wins']}-${data[gamePk]['schedule']['teams']['away']['leagueRecord']['losses']})\
@ ${data[gamePk]['schedule']['teams']['home']['team']['teamName']} (${data[gamePk]['schedule']['teams']['home']['leagueRecord']['wins']}-${data[gamePk]['schedule']['teams']['home']['leagueRecord']['losses']})\
%endif
%if data[gamePk]['schedule']['doubleHeader'] == 'Y' and data[gamePk]['schedule']['gameNumber'] == 2:
- ${data[gamePk]['gameTime']['myTeam'].strftime(dhDateFormat)} - Doubleheader Game 2
%else:
- ${data[gamePk]['gameTime']['myTeam'].strftime(dateFormat)}
%endif
%if data[gamePk]['schedule']['doubleHeader'] == 'S':
- Doubleheader Game ${data[gamePk]['schedule']['gameNumber']}
%endif
7 changes: 6 additions & 1 deletion bots/lemmy_mlb_game_threads/templates/post_thread.mako
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@ due to ${data[gamePk]['schedule']['status']['reason']} \
<%include file="scoring_plays.mako" />

% endif
% if not settings.get('Post Game Thread',{}).get('SUPPRESS_SCORING_PLAYS', False):
<%include file="scoring_plays.mako" />

% endif
% if not settings.get('Post Game Thread',{}).get('SUPPRESS_HIGHLIGHTS', False):
<%include file="highlights.mako" />

%endif
<%include file="linescore.mako" />

% if not settings.get('Post Game Thread',{}).get('SUPPRESS_DECISIONS', False):
<%include file="decisions.mako" />

Expand Down
Loading