Skip to content

Commit

Permalink
code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
daabr committed Aug 28, 2024
1 parent fd3b94e commit 2d9c162
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 72 deletions.
34 changes: 13 additions & 21 deletions room_reservation/available_rooms.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,45 +10,37 @@

def on_slack_slash_command(event):
"""Entry point for the "/availablerooms" Slack slash command."""
# user_id = event.data['user_id']
channel_id = event.data["channel_id"]

slack = slack_client("slack_conn")
channel_id = event.data["channel_id"]

rooms = google_sheets.get_room_list()

gcal = google_calendar_client("calendar_conn").events()
now = datetime.now(UTC)
in_30_minutes = now + timedelta(minutes=30)
gcal = google_calendar_client("calendar_conn").events()

# Iterate over the list of rooms, notify the user about
# each room which is available in the next half hour.
available = False

# Iterate through the list of rooms and notify the user if the room is free in the next 30 minutes
for room in rooms:
print(f"Checking events in {room}.")

for room in sorted(google_sheets.get_room_list()):
print(f"Checking upcoming events in: {room}")
try:
events_result = gcal.list(
events = gcal.list(
calendarId=room,
timeMin=now.isoformat(),
timeMax=in_30_minutes.isoformat(),
singleEvents=True,
orderBy="startTime",
).execute()
events = events_result.get("items", [])

if not events:
slack.chat_postMessage(
channel=channel_id, text=f"{room} is free for the next 30 minutes"
)
if not events.get("items"):
msg = f"The room `{room}` is available for the next half hour"
slack.chat_postMessage(channel=channel_id, text=msg)
available = True

except Exception as e:
# TODO: if room in the list if not found as a resource, send a better message to the user
# TODO: Send a better error message if room isn't found as a resource.
slack.chat_postMessage(channel=channel_id, text=f"{e}")
print(f"Error: {e}")

if not available:
slack.chat_postMessage(
channel=channel_id, text="No free rooms found for the next 30 minutes"
)
msg = "No available rooms found for the next half hour"
slack.chat_postMessage(channel=channel_id, text=msg)
45 changes: 22 additions & 23 deletions room_reservation/reserve_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,51 +9,50 @@
import google_sheets


# event.data['text'] contains the text of the slash command.
def on_slack_slash_command(event):
"""Entry point for the "/reserveroom <room> <title>" Slack slash command."""
slack = slack_client("slack_conn")
channel_id = event.data.channel_id

channel_id = event.data["channel_id"]
rooms = google_sheets.get_room_list()

txt = event.data["text"]
words = txt.split(maxsplit=1)
if len(words) != 2:
slack.chat_postMessage(
channel=channel_id,
text="Bad input. Please use the following format: /createmeeting <room> <event>",
)
cmd_text = event.data.text.split(maxsplit=1)
if len(cmd_text) < 2:
error = "Error: please use the following format: `/reserveroom <room> <title>`"
slack.chat_postMessage(channel=channel_id, text=error)
return
if words[0] not in rooms:
slack.chat_postMessage(channel=channel_id, text=f"Room {words[0]} not found")

room, title = cmd_text
if room not in google_sheets.get_room_list():
error = f"Error: `{room}` not found in the list of rooms"
slack.chat_postMessage(channel=channel_id, text=error)
return

user = event.data.user_id # TODO: Convert to name.

now = datetime.now(UTC)
in_5_minutes = now + timedelta(minutes=5)
in_30_minutes = now + timedelta(minutes=30)

event = {
"summary": words[1],
"description": words[1],
"summary": title,
"description": f"Reserved via Slack by {user}",
"start": {"dateTime": in_5_minutes.isoformat()},
"end": {"dateTime": in_30_minutes.isoformat()},
"reminders": {"useDefault": False},
# TODO: Add the requester.
# "attendees": [
# {"email": "[email protected]"},
# {"email": "[email protected]"},
# ],
}
res = _create_calendar_event(words[0], event)

slack.chat_postMessage(
channel=channel_id, text=f"Meeting request to {words[0]} was sent"
)
# TODO: Handle errors.
_create_calendar_event(room, event)
slack.chat_postMessage(channel=channel_id, text=f"Scheduled meeting in `{room}`")


# It better to have this as activity to save the creation of multiple activities when creating a insert event
# It's better to mark this as a single activity, to minimize the creation of
# multiple overly-granular activities during this Google Calendar API call.
@autokitteh.activity
def _create_calendar_event(calendarId, event):
def _create_calendar_event(room, event):
gcal = google_calendar_client("calendar_conn").events()
event = gcal.insert(calendarId=calendarId, body=event).execute()
return event
return gcal.insert(calendarId=room, body=event).execute()
51 changes: 23 additions & 28 deletions room_reservation/room_status.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Check the status of a specific room for the next half hour."""
"""Check the status of a specific room for the next hour."""

from datetime import UTC, datetime, timedelta

import autokitteh
from autokitteh.google import google_calendar_client
from autokitteh.slack import slack_client

Expand All @@ -11,43 +12,37 @@
def on_slack_slash_command(event):
"""Entry point for the "/roomstatus <room>" Slack slash command."""
slack = slack_client("slack_conn")
channel_id = event.data.channel_id

# user_id = event.data['user_id']
rooms = google_sheets.get_room_list()
channel_id = event.data["channel_id"]

room_id = event.data["text"]
rooms = google_sheets.get_room_list()
if room_id not in rooms:
slack.chat_postMessage(
channel=channel_id, text=f"{room_id} not found in list of rooms"
)
return
room = event.data.text
if room not in google_sheets.get_room_list():
error = f"Error: `{room}` not found in the list of rooms"
slack.chat_postMessage(channel=channel_id, text=error)

gcal = google_calendar_client("calendar_conn").events()

# TODO: change the time you would like to check for the room status
now = datetime.now(UTC)
in_5_hours = now + timedelta(hours=24)
in_1_hour = now + timedelta(hours=1)

msg = f"Events in the room `{room}`:"
try:
events_result = gcal.list(
calendarId=room_id,
events = gcal.list(
calendarId=room,
timeMin=now.isoformat(),
timeMax=in_5_hours.isoformat(),
timeMax=in_1_hour.isoformat(),
singleEvents=True,
orderBy="startTime",
).execute()
events = events_result.get("items", [])

msg = f"Events in {room_id}:"
)
events = events.execute().get("items", [])

if not events:
msg = msg + " No upcoming events found."
msg += " no upcoming events found"

for event in events:
start = event["start"].get("dateTime", event["start"].get("date"))
msg = msg + f"\n{start} - {event['summary']}"
slack.chat_postMessage(channel=channel_id, text=msg)
event = autokitteh.AttrDict(event)
start = event.start.get("dateTime") or event.start.get("date")
msg += f"\n{start} - {event.summary}"
except Exception as e:
slack.chat_postMessage(channel_id, f"{e}")
print(f"Error: {e}")
msg = f"Error: {e}"
print(msg)

slack.chat_postMessage(channel=channel_id, text=msg)

0 comments on commit 2d9c162

Please sign in to comment.