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

Discord Event Announcements Finished #129

Merged
merged 13 commits into from
Jun 4, 2021
Merged

Discord Event Announcements Finished #129

merged 13 commits into from
Jun 4, 2021

Conversation

royh02
Copy link
Member

@royh02 royh02 commented Apr 25, 2021

Announcements:

  • Weekly
  • 1 Day in advance
  • Day of
  • Hour before
  • Now

Example:
image

@royh02 royh02 requested a review from aninrusimha April 25, 2021 07:49
@royh02 royh02 self-assigned this Apr 25, 2021
@royh02 royh02 linked an issue Apr 25, 2021 that may be closed by this pull request
@royh02
Copy link
Member Author

royh02 commented Apr 25, 2021

Also, I made a change to the Event Model to use TimeField instead of CharField.

@royh02 royh02 requested a review from dlzou April 26, 2021 03:50
Copy link
Member

@robertquitt robertquitt left a comment

Choose a reason for hiding this comment

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

Good work so far!

Be sure to install pre-commit so that the autoformatter, black, runs.

Be sure to make the database migration with manage.py makemigrations

I like the fact that we're finally using the events table for something useful!

apps/db_data/models.py Show resolved Hide resolved
@@ -187,6 +187,9 @@ def __str__(self):
def is_passed(self):
return self.date < datetime.date.today()

def get_time_string(self):
return self.time.strftime("%I:%M %p PST")
Copy link
Member

@robertquitt robertquitt Apr 27, 2021

Choose a reason for hiding this comment

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

We won't always be in daylight savings time, so PT would be more correct in this case

Copy link
Member Author

Choose a reason for hiding this comment

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

Used DateTimeField and made it TZ aware. Everything is stored as UTC and the getters will convert it to Pacific Time

"""
today = datetime.date.today()
now = datetime.datetime.now()
upcoming_events = Event.objects.filter(date__gte=today).filter(time__gte=now)
Copy link
Member

Choose a reason for hiding this comment

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

As I mentioned earlier, if we remove date and only use time, then we could simplify this to just one filter

Copy link
Member Author

Choose a reason for hiding this comment

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

Made this fix in announcements.py

@@ -162,11 +170,12 @@ class CSUABot:
def __init__(self):
self.loop = asyncio.new_event_loop()
self.thread = threading.Thread(target=self._start, daemon=True)
self.running = True
self.thread.start()
Copy link
Member

Choose a reason for hiding this comment

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

Is this intentional? Take a look at 201c5bf

Copy link
Member Author

Choose a reason for hiding this comment

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

MB I think I messed up when resolving the merge conflict

events = Event.objects \
.filter(date=today, time__lte=times[requested_tdelta]) \
.filter(time__gte=now) \
.order_by("time")
Copy link
Member

Choose a reason for hiding this comment

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

Maybe we could consider using https://docs.djangoproject.com/en/2.2/ref/models/options/#django.db.models.Options.ordering

To avoid re-writing the order_by each time we query

Copy link
Member Author

Choose a reason for hiding this comment

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

Added into the Events model so that everything is already ordered in the DB


def event_checker(requested_tdelta):
"""
Checks events in db to see if any match the day
Copy link
Member

Choose a reason for hiding this comment

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

Could you consider renaming this function to something like get_events_in_date_or_time_delta? The fact that this has 3 branches plus a dict lookup makes it hard to understand. Maybe you could have a helper function, get_events_in_time_range, that took a time range (start and end time) and returned events, and then have another function that translates "week", "day" etc to the correct time ranges to pass to get_events_in_time_range

Copy link
Member Author

Choose a reason for hiding this comment

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

I have split the function into 3, namely get_events_in_date_or_time_delta(requested_tdelta), and 2 helpers: get_events_in_time_range(range), timeify(requested_tdelta). I added docstrings in for added clarity.

Copy link
Member

Choose a reason for hiding this comment

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

I regret saying to call it get_events_in_date_or_time_delta. Maybe you should think of a better name yourself, like get_events_in_period

).result(TIMEOUT_SECS)


schedule.every().sunday.at("17:00").do(partial(announcer, "week"))
Copy link
Member

Choose a reason for hiding this comment

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

I don't like the fact that we're using magic strings here. If "week" or "tomorrow" or "today" get accidentally misspelled, we might end up with a bug that we won't notice until the time comes around. My suggestion would be to define some constants like TODAY = "today" and just use those instead.

Copy link
Member Author

Choose a reason for hiding this comment

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

Added the constants

@@ -0,0 +1,52 @@
import datetime

import pytz
Copy link
Member

Choose a reason for hiding this comment

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

Either use the builtin django timezone interface or add this to requirements.txt

@@ -9,7 +9,7 @@

@register.simple_tag
def get_upcoming_events():
return Event.objects.filter(date__gte=datetime.date.today())
return Event.objects.filter(date_time__gte=datetime.datetime.today())
Copy link
Member

Choose a reason for hiding this comment

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

Prefer to use datetime.now()

Comment on lines -183 to -184
def __str__(self):
return f"{self.name} ({self.date})"
Copy link
Member

Choose a reason for hiding this comment

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

Is there a reason to delete this? It's used by the admin interface

Copy link
Member Author

Choose a reason for hiding this comment

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

I made a change to that to be consistent with the DateTimeField. I made a null check because of an issue that came up after migrating and all events had null date_time, which messed up the admin interface.

def __str__(self):
    if not self.date_time:
        return f"{self.name}"
    return f"{self.name} ({self.get_date_string()})"

Copy link
Member

Choose a reason for hiding this comment

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

Maybe we can keep the old date and time fields for backward compatibility?

Copy link
Member

@robertquitt robertquitt May 19, 2021

Choose a reason for hiding this comment

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

We could configure the migration to convert from the existing date field to the new datetime field

https://docs.djangoproject.com/en/2.2/topics/migrations/#data-migrations

Copy link
Member Author

@royh02 royh02 May 21, 2021

Choose a reason for hiding this comment

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

Just the date right, because the current CharField for time is harder to parse since there isn't a consistent pattern

Copy link
Member

@robertquitt robertquitt Jun 2, 2021

Choose a reason for hiding this comment

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

That's right, the CharField was just there as a hack to display a time range. You can just ignore it, since the CharField is only for events in the past.

return events


def get_events_in_time_range(range):
Copy link
Member

Choose a reason for hiding this comment

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

Might be worth annotating this with types to make it more clear

Suggested change
def get_events_in_time_range(range):
from typing import Tuple
def get_events_in_time_range(range: Tuple[datetime, datetime]):

Copy link
Member

Choose a reason for hiding this comment

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

@robertquitt is your policy to use annotations only when things are unclear without them? Also in this case could have two args start_time, end_time instead, and use * to unpack when passing in timeify().

Copy link
Member

Choose a reason for hiding this comment

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

Great suggestion, that's a much better solution

Copy link
Member Author

Choose a reason for hiding this comment

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

I totally forgot about this Python functionality, thanks!


def event_checker(requested_tdelta):
"""
Checks events in db to see if any match the day
Copy link
Member

Choose a reason for hiding this comment

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

I regret saying to call it get_events_in_date_or_time_delta. Maybe you should think of a better name yourself, like get_events_in_period

hour=23, minute=59, second=59
),
"today": now.replace(hour=23, minute=59, second=59),
"hour": (now + datetime.timedelta(hours=1)).replace(minute=59, second=59),
Copy link
Member

Choose a reason for hiding this comment

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

Why do you need these replacements?

Comment on lines 34 to 50
end_times = {
"week": now + datetime.timedelta(weeks=1),
"tomorrow": (now + datetime.timedelta(days=1)).replace(
hour=23, minute=59, second=59
),
"today": now.replace(hour=23, minute=59, second=59),
"hour": (now + datetime.timedelta(hours=1)).replace(minute=59, second=59),
"now": now + datetime.timedelta(minutes=10),
}
start_times = {
"week": now,
"tomorrow": (now + datetime.timedelta(days=1)).replace(
hour=0, minute=0, second=0
),
"today": now,
"hour": (now + datetime.timedelta(hours=1)).replace(minute=0, second=0),
"now": now,
Copy link
Member

Choose a reason for hiding this comment

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

I am really confused by this. Why do you need to replace minutes and seconds? Why does now only go 10 minutes in advance if you only report every 30 minutes?

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure how to get events happening 1 day in advance. Currently, I'm also running into an issue that seems to be that the replace messes up the timezones. This is because 00:00:00 in UTC is not the same as midnight in PT, and this causes some events to be announced wrongly. I did a lot of digging on SO but there wasn't much besides using replace, which is buggy.

@@ -14,6 +14,7 @@ slack_bolt

# apps.discordbot
discord.py
schedule
Copy link
Member

Choose a reason for hiding this comment

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

Add pytz here or remove pytz from the code

@@ -15,6 +15,8 @@
"""
import os

from apps.discordbot.bot import csua_bot
Copy link
Member

Choose a reason for hiding this comment

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

delete

TOMORROW = "tomorrow"
TODAY = "today"
HOUR = "hour"
NOW = "now"
Copy link
Member

Choose a reason for hiding this comment

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

Rename NOW

csua_bot.announcements_thread = threading.Thread(
target=csua_bot.event_announcement, daemon=True
)
csua_bot.announcements_thread.start()
Copy link
Member

Choose a reason for hiding this comment

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

The circular dependency makes me a bit uneasy. Haven't completely thought it through, but could announcements_thread and event_announcement be moved into this class?

Copy link
Member Author

Choose a reason for hiding this comment

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

I originally put this here because we need to wait for on_ready to trigger before the announcement_thread starts, or else the thread would start too early with no client ready. Do you have something else in mind?

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, so I'm wondering why event_announcement is a method in CSUABot rather than in CSUAClient, or even a stand-alone function, considering there's an instance of CSUAClient in CSUABot. I suppose there isn't really an impact on functionality and it's more about design. My understanding is that CSUAClient holds the core parts running the bot, while CSUABot is sort of an internal API. Could we get a third opinion?

@@ -168,8 +169,7 @@ class Sponsorship(models.Model):
class Event(models.Model):
name = models.CharField(max_length=70)
location = models.CharField(max_length=70)
date = models.DateField(null=True)
time = models.CharField(max_length=70)
date_time = models.DateTimeField(null=False)
Copy link
Member

Choose a reason for hiding this comment

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

We need to have some way to store the start and end datetimes, not just the start

@royh02 royh02 merged commit 2e2f937 into CSUA:master Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Public CSUA calendar + Event integration
3 participants