def fetchActiveUsers(bot, all_employees): # Check for new members params = {"token": USER_TOKEN_STRING, "channel": bot.channel_id} response = requests.get("https://slack.com/api/channels.info", params=params) print "fetchActiveUsers response: " + response.text parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: user_ids = parsed_message["channel"]["members"] active_users = [] for user_id in user_ids: # Don't add hudl_workout if user_id != bot.user_id: # Add user to the cache if not already if user_id not in bot.user_cache: bot.user_cache[user_id] = User(user_id, all_employees) if not bot.first_run: # Push our new users near the front of the queue! bot.user_queue.insert(2,bot.user_cache[user_id]) if bot.user_cache[user_id].isActive(): active_users.append(bot.user_cache[user_id]) if bot.first_run: bot.first_run = False return active_users
def initiateThrowdown(bot, all_employees, message): text = message['text'].lower() words = text.split() challengerId = message['user'] active_users = fetchActiveUsers(bot, all_employees) challengees = [] challenger = None for user in active_users: if user.id == challengerId: challenger = user break exercise = findExerciseInText(bot, text) exercise_reps = findIntInText(bot, words) if challenger is not None and challenger.has_challenged_today == True: already_challenged_text = 'You can only give out a challenge once a day ' + challenger.real_name requests.post(bot.post_message_URL + "&text=" + already_challenged_text) return if exercise_reps != False and exercise != False and exercise_reps > exercise['maxReps']: too_many_reps_text = 'Please select a number under ' + str(exercise['maxReps']) + ' for that exercise, ' + challenger.real_name requests.post(bot.post_message_URL + "&text=" + too_many_reps_text) return if challenger is not None and exercise != False and exercise_reps != False: for user in active_users: for word in words: if user.id.lower() in word: challengees.append(user) print "Found a challengee" if len(challengees) > 0: for challengee in challengees: challengee.addExercise(exercise, exercise_reps) challenger.has_challenged_today = True challenge_text = "You hear that, " + challengees[0].real_name + "? " + challenger.real_name + " is challenging you, " + str(exercise_reps) + " " + str(exercise["units"]) + " " + exercise['name'] + " now!" response = requests.post(bot.post_message_URL + "&text=" + challenge_text) print "initiateThrowdown response: " + response.text parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: last_message_timestamp = parsed_message["ts"] requests.post("https://slack.com/api/reactions.add?token=" + USER_TOKEN_STRING + "&name=yes&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=no&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=sleeping&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") exercise_obj = Exercises(exercise, exercise_reps, challengees, last_message_timestamp) EXERCISES_FOR_DAY.append(exercise_obj) logExercise(bot,challengees,exercise["name"],exercise_reps,exercise["units"],exercise_obj.time_assigned) print challenge_text
def isActive(self): params = {"token": USER_TOKEN_STRING, "user": self.id} response = requests.get("https://slack.com/api/users.getPresence",params=params) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: status = parsed_message["presence"] return status == "active" else: return False
def fetchNames(self): params = {"token": USER_TOKEN_STRING, "user": self.id} response = requests.get("https://slack.com/api/users.info", params=params) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: user_obj = parsed_message["user"] username = user_obj["name"] real_name = user_obj["profile"]["real_name"] return username, real_name
def announceExercise(bot, minute_interval): exercise = selectExercise(bot) # Announcement String of next lottery time lottery_announcement = "NEXT LOTTERY FOR " + exercise["name"].upper() + " IS IN " + str(minute_interval) + (" MINUTES" if minute_interval != 1 else " MINUTE") # Announce the exercise to the thread if not bot.debug: response = requests.post(bot.post_message_URL + "&text=" + lottery_announcement) print "announceExercise response: " + response.text if bot.last_listen_ts == '0': parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: bot.last_listen_ts = parsed_message["ts"] print lottery_announcement return exercise
def listenForReactions(bot): if not bot.debug: for exercise in EXERCISES_FOR_DAY: timestamp = exercise.timestamp response = requests.get("https://slack.com/api/reactions.get?token=" + USER_TOKEN_STRING + "&channel=" + bot.channel_id + "&full=1×tamp=" + timestamp) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: reactions = parsed_message["message"]["reactions"] for reaction in reactions: if reaction["name"] == "yes": users_who_have_reacted_with_yes = reaction["users"] elif reaction["name"] == "no": users_who_have_reacted_with_no = reaction["users"] elif reaction["name"] == "sleeping": users_who_have_reacted_with_sleeping = reaction["users"] for user in exercise.users: if user.id in users_who_have_reacted_with_yes and user not in exercise.completed_users: exercise_name = exercise.exercise["name"] print user.real_name + " has completed their " + exercise_name + " after " + str((time.time() - exercise.time_assigned)) + " seconds" exercise.count_of_acknowledged += 1 exercise.completed_users.append(user) if bot.database: query = dict(username='******'+user.username, exercise=exercise_name, assigned_at=exercise.time_assigned, completed_at=time.time()) bot.db.complete(query) elif user.id in users_who_have_reacted_with_no and user not in exercise.refused_users and user not in exercise.completed_users: exercise_name = exercise.exercise["name"] print user.real_name + " refuses to complete their " + exercise_name exercise.refused_users.append(user) exercise.count_of_acknowledged += 1 elif not isReminderInReminderList(user.id, exercise) and user.id in users_who_have_reacted_with_sleeping: exercise.snoozed_users.append(Reminder(timestamp, datetime.datetime.now(), user, exercise)) if exercise.count_of_acknowledged == len(exercise.users): EXERCISES_FOR_DAY.remove(exercise) print "Removing Exercise"
def listenForCommands(bot, all_employees): response = requests.get("https://slack.com/api/channels.history?token=" + USER_TOKEN_STRING + "&channel=" + bot.channel_id + "&oldest=" + bot.last_listen_ts) parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: messages = parsed_message["messages"] if not messages: return last_time = messages[-1]['ts'] bot.last_listen_ts = last_time command_start = '<@'+bot.user_id.lower()+'>' for message in messages: text = message['text'].lower() if text.startswith(command_start): if 'challenge' in text: initiateThrowdown(bot, all_employees, message) break exercise = findExerciseInText(bot, text) if exercise != False: requests.post(bot.post_message_URL + "&text=" + exercise['tutorial']) break # Check for help command if 'help' in text: help_message = 'Just send me a name of an exercise, and I will teach you how to do it.' for exercise in bot.exercises: help_message += '\n ' + exercise['name'] help_message += '\n If you want to issue a challenge say `@hudl_workout I challenge @PERSON to 15 EXERCISE`' requests.post(bot.post_message_URL + "&text=" + help_message) break else: prompt_actual_command = "I'm sorry, I can't understand you" requests.post(bot.post_message_URL + "&text=" + prompt_actual_command)
def assignExercise(bot, exercise, all_employees): # Select number of reps exercise_reps = random.randrange(exercise["minReps"], exercise["maxReps"]+1) winner_announcement = str(exercise_reps) + " " + str(exercise["units"]) + " " + exercise["name"] + " RIGHT NOW " active_users = fetchActiveUsers(bot, all_employees) winners = [] # EVERYBODY num_active_users = len(active_users) if num_active_users < 3: num_people_to_callout = 0 elif num_active_users < 6: num_people_to_callout = 1 elif num_active_users < 10: num_people_to_callout = 2 elif num_active_users < 20: num_people_to_callout = 3 else: num_people_to_callout = 5 print "num active users: " + str(num_active_users) + ", choosing " + str(num_people_to_callout) + " people" if num_people_to_callout > 0: if random.random() < bot.group_callout_chance: winner_announcement += "@channel!" # only add active users to the exercise list. This will mean if someone is active later and marks :yes: they won't get credit. for user in active_users: user.addExercise(exercise, exercise_reps) winners.append(user) else: for i in range(num_people_to_callout): winners.append(selectUser(bot, exercise, all_employees, winners, active_users)) for i in range(num_people_to_callout): winner_announcement += str(winners[i].getUserHandle()) if i == num_people_to_callout - 2: winner_announcement += ", and " elif i == num_people_to_callout - 1: winner_announcement += "!" else: winner_announcement += ", " winners[i].addExercise(exercise, exercise_reps) last_message_timestamp = str(datetime.datetime.now()) # Announce the user if not bot.debug: response = requests.post(bot.post_message_URL + "&text=" + winner_announcement) print "assignExercise response: " + response.text parsed_message, isMessageOkay = Http.parseSlackJSON(response) if isMessageOkay: last_message_timestamp = parsed_message["ts"] requests.post("https://slack.com/api/reactions.add?token=" + USER_TOKEN_STRING + "&name=yes&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=no&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") requests.post("https://slack.com/api/reactions.add?token="+ USER_TOKEN_STRING + "&name=sleeping&channel=" + bot.channel_id + "×tamp=" + last_message_timestamp + "&as_user=true") exercise_obj = Exercises(exercise, exercise_reps, winners, last_message_timestamp) EXERCISES_FOR_DAY.append(exercise_obj) logExercise(bot,winners,exercise["name"],exercise_reps,exercise["units"],exercise_obj.time_assigned) print winner_announcement else: are_you_scared = "Not enough of you maggots are active! What are you all scared? GET BACK IN HERE!" requests.post(bot.post_message_URL + "&text=" + are_you_scared)