Skip to content

Commit

Permalink
Timezone fix
Browse files Browse the repository at this point in the history
  • Loading branch information
dngo13 committed Oct 10, 2024
1 parent c774ee3 commit 46f1d29
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 17 deletions.
45 changes: 34 additions & 11 deletions backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,43 +33,57 @@ def get_upcoming_events():
# Get all available calendars
calendar_list = service.calendarList().list().execute()
calendars = calendar_list.get('items', [])

# Get events starting from now to the next day
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
# now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
now = datetime.datetime.now(pytz.timezone('America/New_York')).isoformat() # Current time in America/New_York
all_events = []
print("Getting the upcoming 5 events")
for calendar in calendars:
# Fetch the calendar time zone
calendar_timezone = calendar.get('timeZone', 'UTC') # Default to UTC if no time zone is set
calendar_id = calendar['id']
is_work_calendar = '[email protected]' in calendar_id
events_result = (
service.events()
.list(
calendarId=calendar_id,
timeMin=now,
maxResults=5,
singleEvents=True, orderBy='startTime'
singleEvents=True,
orderBy='startTime',
timeZone=calendar_timezone # Specify the time zone
)
.execute()
)
events = events_result.get('items', [])


print(f"Calendar: {calendar_id}, Time Zone: {calendar_timezone}")
if not events:
print(f"No upcoming events for calendar: {calendar_id}")
continue
all_events.extend(events)



for event in events:
print("Printing events")
summary = event.get('summary', 'No Title') # Get the event summary or provide a fallback
start_time = event['start'].get('dateTime', event['start'].get('date'))
# Log start_time to ensure the format is correct
print(f"Raw start_time from event: {start_time}. {summary}")
# formatted_start_time = format_date(start_time) # Format the date in 12-hour format

if is_work_calendar:
utc_start_time = datetime.datetime.fromisoformat(start_time.replace('Z', '+00:00'))
start_time = utc_start_time.astimezone(pytz.timezone('America/New_York'))
print(f"Converted start_time for work calendar: {start_time}, {summary}")
else:
# Handle other calendars (ensure they're in the correct timezone)
start_time = datetime.datetime.fromisoformat(start_time.replace('Z', '+00:00')).astimezone(pytz.timezone(calendar_timezone))
description = event.get('description', 'No description provided') # Get the event description or provide a fallback
if len(description) > 100:
description = "Project Meeting with Team"
event_list.append({
'summary': summary,
'start_time': start_time,
'start_time': start_time.isoformat(),
'description' : description
})
# Sort events by start time and take the top 5
Expand Down Expand Up @@ -127,8 +141,17 @@ def schedule_event_notifications(summary, start_time, description):
# Parse the event start_time, which is in ISO format (UTC-aware)
# event_time = datetime.datetime.fromisoformat(start_time.replace('Z', ''))
# event_time = datetime.datetime.fromisoformat(start_time.replace('Z', '+00:00')) # Ensure UTC offset is handled
event_time = datetime.datetime.fromisoformat(start_time)

# event_time = datetime.datetime.fromisoformat(start_time)
print(f"event: {summary}, time:, {start_time}")
# Parse the event start_time, ensuring that time zone info is handled
if 'Z' in start_time:
# UTC event times
print("replacing z in time")
event_time = datetime.datetime.fromisoformat(start_time.replace('Z', '+00:00'))
else:
print("offset")
# If there's a time zone offset in start_time, it will be handled automatically
event_time = datetime.datetime.fromisoformat(start_time)
# Check if event_time is naive (lacking timezone info)
if event_time.tzinfo is None:
print(f"event_time is naive: {event_time}")
Expand All @@ -138,7 +161,7 @@ def schedule_event_notifications(summary, start_time, description):

# Get the current time in UTC (make now offset-aware)
now = datetime.datetime.now(pytz.UTC)
print(f"now is aware: {now} with tzinfo {now.tzinfo}")
# print(f"now is aware: {now} with tzinfo {now.tzinfo}")
# now = datetime.datetime.now(pytz.timezone('America/New_York'))
# Schedule a 15-minute-before reminder for the event
reminder_time = event_time - datetime.timedelta(minutes=15)
Expand Down
4 changes: 0 additions & 4 deletions bot_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ async def sync():
await tree.sync()

# Slash command to manually pull Google Calendar events and send them to the Discord channel
# @bot.command(name='get_events')
@tree.command(name="get_events", description="List upcoming Google Calendar events")
# async def get_events(message):
async def get_events(interaction: discord.Interaction):
await interaction.response.defer() # Acknowledge the interaction
try:
Expand Down Expand Up @@ -69,7 +67,6 @@ def format_date(date_str):
date = datetime.datetime.fromisoformat(date_str.replace('Z', ''))
# Return formatted as MM-DD-YYYY with 12-hour time format and AM/PM
edited_date = date.strftime('%m-%d-%Y %I:%M %p')
# print(edited_date)
return edited_date
except ValueError:
return date_str # Return as-is if parsing fails
Expand All @@ -78,7 +75,6 @@ def format_date(date_str):
@bot.event
async def send_reminder_to_discord(reminder):
# Ensure the bot's cache is ready
# await bot.wait_until_ready()
discord_webhook_url = 'https://discord.com/api/webhooks/1284279940858249256/v3TzTaTGNMm7aiRhlUuqeCx0L6FnJsa1_CyBGo2VZTmdeHhmFbJMV6f08v2gtlhY6xHq'
webhook = discord_webhook.DiscordWebhook(url=discord_webhook_url)
ping_me = "<@119137826158673921>"
Expand Down
3 changes: 1 addition & 2 deletions calendar_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
from google.auth.transport.requests import Request

# The scope we want to request from Google Calendar
SCOPES = ['https://www.googleapis.com/auth/calendar.events']

SCOPES = ['https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar']
def get_calendar_service():
creds = None
# The token file will hold the OAuth access token
Expand Down

0 comments on commit 46f1d29

Please sign in to comment.