This repository has been archived by the owner on Aug 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
check_attendance.py
executable file
·179 lines (157 loc) · 6.54 KB
/
check_attendance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python
"""
Bagelbot script for checking for attendance for an upcoming bagelbot meeting.
"""
import logging
import sys
import time
from datetime import datetime, timedelta
from config import ATTENDANCE_TIME_LIMIT
from utils import YES, NO, initialize, nostdout, download_shelve_from_s3, upload_shelve_to_s3
def check_attendance(store, sc, users=None):
"""Pings all slack users with the email address stored in config.py.
It asks if they are available for today's meeting, and waits for a pre-determined amount of time.
If all users respond, or if the time limit is reached, the script exits
and writes today's upcoming meeting to the store.
Args:
store (instance): A persistent, dictionary-like object used to keep information about past/future meetings
sc (SlackClient): An instance of SlackClient
users (list): A list of users to ping for role call (overrides store['everyone'])
"""
start = datetime.now()
todays_meeting = {"date": start.date(), "available": [], "out": []}
if not users:
users = store["everyone"]
user_len = len(users)
messages_sent = {}
if sc.rtm_connect():
for user in users:
logging.info("Pinging %s...", user)
message = sc.api_call(
"chat.postMessage",
channel="@" + user,
as_user=True,
text="Will you be available for today's ({:%m/%d/%Y}) :coffee: and :bagel: meeting? (yes/no)".format(
todays_meeting["date"]
),
)
message["user"] = user
messages_sent[message["channel"]] = message
logging.info("Waiting for responses...")
while True:
try:
events = sc.rtm_read()
for event in events:
logging.debug(event)
if (
event["type"] == "message"
and event["channel"] in messages_sent
and float(event["ts"]) > float(messages_sent[event["channel"]]["ts"])
):
lower_txt = event["text"].lower().strip()
user = messages_sent[event["channel"]]["user"]
logging.info(
"%s responded with '%s'", user, event["text"].encode("ascii", "ignore")
)
user_responded = False
if lower_txt in YES:
user_responded = True
todays_meeting["available"].append(user)
sc.api_call(
"chat.postMessage",
channel=event["channel"],
as_user=True,
text="Your presence has been acknowledged! Thank you! :tada:",
)
elif lower_txt in NO:
user_responded = True
todays_meeting["out"].append(user)
sc.api_call(
"chat.postMessage",
channel=event["channel"],
as_user=True,
text="Your absence has been acknowledged! You will be missed! :cry:",
)
if user_responded:
# User has responded to bagelbot, don't listen to this channel anymore.
messages_sent.pop(event["channel"])
except:
logging.exception("Something went wrong reading Slack RTM Events.")
all_accounted_for = (
len(todays_meeting["available"]) + len(todays_meeting["out"]) == user_len
)
if (
datetime.now() > (start + timedelta(seconds=ATTENDANCE_TIME_LIMIT))
or all_accounted_for
):
if not all_accounted_for:
# Move any remaining users over to 'out' at the end of the time limit - assuming they aren't available
todays_meeting["out"] += [
u
for u in users
if u not in todays_meeting["available"] and u not in todays_meeting["out"]
]
logging.info(
"Finished! These people aren't available today: %s",
", ".join(todays_meeting["out"]),
)
# Store this upcoming meeting under a separate key for use by generate_meeting.py upon actual meeting generation.
store["upcoming"] = todays_meeting
break
else:
time.sleep(1)
else:
logging.info("Connection Failed, invalid token?")
def main(args):
"""
Initialize the shelf, possibly sync to s3, then check attendance, close
the shelf and maybe sync the shelf again.
Args:
args (ArgumentParser args): Parsed arguments that impact how the check_attandance runs
"""
if args.s3_sync:
download_shelve_from_s3()
if args.debug:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format="%(message)s")
else:
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
store, sc = initialize(update_everyone=True)
try:
check_attendance(store, sc, users=args.users)
finally:
store.close()
if args.s3_sync:
upload_shelve_to_s3()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Check to see if any Slack members will be missing today's meeting."
)
parser.add_argument(
"--users",
"-u",
dest="users",
metavar="P",
nargs="+",
required=False,
default=[],
help="list of people to check in with (usernames only)",
)
parser.add_argument(
"--from-cron", "-c", action="store_true", help="Silence all logging statements (stdout)."
)
parser.add_argument(
"--debug", "-d", action="store_true", help="Log all events bagelbot can see."
)
parser.add_argument(
"--s3-sync",
"-s",
action="store_true",
help="Synchronize SHELVE_FILE with AWS S3 before and after checking attendance.",
)
parsed_args = parser.parse_args()
if parsed_args.from_cron:
with nostdout():
main(parsed_args)
else:
main(parsed_args)