def parse_next_msg(): """Parse next message posted on slack for actions to do by bot""" msg = SLACK_CLIENT.rtm_read() if not msg: return None msg = msg[0] user_id = msg.get("user") channel_id = msg.get("channel") text = msg.get("text") # handle events first event_type = msg.get("type") # 1. if new channel auto-join bot if event_type == "channel_created": bot_joins_new_channel(msg["channel"]["id"]) return None # 2. if a new user joins send a welcome msg if event_type == "team_join": # return the message to apply the karma change # https://api.slack.com/methods/users.info welcome_msg = AUTOMATED_COMMANDS["welcome"]( user_id["id"]) # new user joining post_msg(user_id["id"], welcome_msg) # return Message object to handle karma in main return Message(user_id=KARMABOT_ID, channel_id=GENERAL_CHANNEL, text=welcome_msg) # end events # not sure but sometimes we get dicts? if (not isinstance(channel_id, str) or not isinstance(user_id, str) or not isinstance(text, str)): return None # ignore anything karma bot says! if user_id == KARMABOT_ID: return None # text replacements on first matching word in text # TODO: maybe this should replace all instances in text message ... text_replace_output = text and perform_text_replacements(text) if text_replace_output: post_msg(channel_id, text_replace_output) # if we recognize a valid bot command post its output, done # DM's = channels start with a 'D' / channel can be dict?! private = channel_id and channel_id.startswith("D") cmd_output = perform_bot_cmd(msg, private) if cmd_output: post_msg(channel_id, cmd_output) return None if not channel_id or not text: return None # Returns a message for karma processing return Message(user_id=user_id, channel_id=channel_id, text=text)
def test_slack_team_join(mock_slack_rtm_read_team_join, mock_slack_api_call): user_id = SLACK_CLIENT.rtm_read()[0].get("user")["id"] welcome_user(user_id) actual = parse_next_msg() assert actual.user_id == KARMABOT_ID assert actual.channel_id == GENERAL_CHANNEL assert user_id in actual.text assert "Introduce yourself in #general if you like" in actual.text
def test_slack_rtm_read(mock_slack_rtm_read_msg): event = SLACK_CLIENT.rtm_read() assert event[0]["type"] == "message" assert event[0]["user"] == "ABC123" assert event[0]["text"] == "Hi everybody"