예제 #1
0
def trivia_response_notify(user, channel, player, response):
    player_info = client.users_info(user=player)['user']
    player_name = player_info['profile']['display_name_normalized'] if (
        player_info['profile']['display_name_normalized'] != ""
    ) else player_info['profile']['real_name_normalized']
    if response:
        client.chat_postEphemeral(
            user=user,
            channel=channel,
            text=f"{player_name} accepted your trivia invite")
    else:
        client.chat_postEphemeral(
            user=user,
            channel=channel,
            text=f"{player_name} rejected your trivia invite")
예제 #2
0
def trivia_custom_questions_prompt(user_id, channel):
    client.chat_postEphemeral(user=user_id,
                              channel=channel,
                              text="Fill in custom questions",
                              blocks=triviaCustomMessage(user_id))
예제 #3
0
def start_trivia_message(user, channel, game_id):
    client.chat_postEphemeral(user=user,
                              channel=channel,
                              text="Trivia Time",
                              blocks=triviaInviteMessage(game_id))
예제 #4
0
def interactions(payload):
    """
    The main function for enabling interactions with shortcuts, modals, or
    interactive components (such as buttons, select menus, and datepickers).
    See https://api.slack.com/reference/interaction-payloads for more details
    on how to handle interaction payloads.
    """

    # Extract data
    trigger_id = payload["trigger_id"]
    user = payload["user"]["id"]
    # Received when a user clicks a Block Kit interactive component.
    if payload["type"] == "shortcut":

        callback_id = payload["callback_id"]

        # Opens the "edit_profile" view with prefilled information
        if callback_id == "anonymous_messaging":
            client.views_open(trigger_id=trigger_id,
                              view=get_anonymous_modal())
        elif callback_id == "trivia":
            init_trivia(trigger_id, user)

    # Received when a modal is submitted.
    if payload["type"] == "view_submission":
        # if 'trivia_start_' in payload['view']['callback_id']:
        #     try:
        #         game_id = payload['view']['callback_id'].replace('trivia_start_', '')
        #         trivia_q_number(game_id, int(payload['view']['state']['values']['number_questions']['number_questions']['value']))
        #         trivia_player_list(game_id, payload['view']['state']['values']['users_playing']['users_playing']['selected_users'])
        #         if trivia_finalise(game_id, trigger_id):
        #             try:
        #                 with a.app_context():
        #                     resp = jsonify({'response_action': 'push', 'view': trivia_customs(game_id, trigger_id)})
        #                     resp.headers['Authorization'] = Config.SLACK_BOT_TOKEN
        #                     return resp
        #             except Exception as err:
        #                 print(err)
        #     except:
        #         trivia_failure(game_id, trigger_id)
        # if 'custom_questions_' in payload['view']['callback_id']:
        #     trivia_custom_questions(payload['view']['callback_id'].replace('custom_questions_', ''), payload['view']['state']['values'])
        if 'course_review_' in payload['view']['callback_id']:
            u_id = payload['view']['callback_id'].replace("course_review_", "")
            course = review_submit(u_id, payload['view']['state']['values'])
            review_confirm(u_id, course)

        view = payload["view"]
        callback_id = view["callback_id"]
        state = view["state"]

        # Store submitted profile data
        if callback_id == "edit_profile_modal":
            values = view["state"]["values"]
            for key in ["favourite_course", "favourite_programming_language", "favourite_netflix_show",
                        "favourite_food", \
                        "overrated", "underrated", "biggest_flex", "enrolled_courses", "completed_courses",
                        "general_interests"]:
                value = utils.extract_value(values, key, key)
                utils.add_profile_details(user, key, value)
            app_home({"user": user})

        # Purge messages
        if callback_id == "purge_confirmation":
            # Extract metadata
            metadata = blocks.json.loads(view["private_metadata"])

            # Signal the purge is starting
            client.chat_postEphemeral(channel=metadata["channel_id"],
                                      user=user,
                                      text="Purging messages...")

            # Retrieve data from metadata
            number_of_messages = metadata["number_of_messages"]
            target_user_id = metadata["user"][2:13]
            oldest = int(
                utils.time.time()
            ) - metadata["time_period"] if metadata["time_period"] != -1 else 0
            channel_id = metadata["channel_id"]
            text_snippet = metadata["text_snippet"]

            # Get messages from channel
            conversations_history = client.conversations_history(
                channel=channel_id, oldest=oldest).data

            # Iterate through messages and delete messages until we run out of messages to delete or reach our target
            count_deleted = 0
            while count_deleted < number_of_messages:

                # Iterate through messages
                for msg in conversations_history["messages"]:

                    # Skip messages that are not actual messages (e.g event messages)
                    if msg["type"] != "message":
                        continue

                    # Delete if no user specified or user of message matches target
                    if (target_user_id == "" or target_user_id == msg["user"]
                        ) and (text_snippet == ""
                               or text_snippet in blocks.json.dumps(msg)):
                        try:
                            user_client.chat_delete(channel=channel_id,
                                                    ts=msg["ts"])
                            count_deleted += 1
                        except Exception as e:
                            # Serve error back to user for debugging
                            client.chat_postEphemeral(
                                channel=metadata["channel_id"],
                                user=user,
                                text=str(e))
                            quit()

                    # Break loop if target number of messages is reached
                    if count_deleted >= number_of_messages:
                        break

                # Check that there are more messages to retrieve
                if conversations_history["has_more"] is False:
                    break

                # Retrieve next set of messages
                cursor = conversations_history["response_metadata"][
                    "next_cursor"]
                conversations_history = client.conversations_history(
                    channel=channel_id, oldest=oldest, cursor=cursor)

            # Signal the purge is complete
            client.chat_postEphemeral(channel=metadata["channel_id"],
                                      user=user,
                                      text="Purge complete")

        # Store submitted profile data
        if callback_id == "anonymous_messaging_modal":
            print(view["state"])
            controls = []
            # Unwrap control
            for control in list(state["values"].items()):
                control = control[1]
                control = list(control.items())[0][1]
                print(control)
                controls.append(control)

            users = controls[0]["selected_users"]
            message = controls[1]["value"]
            msg_ids = utils.create_anon_message(user, users, message)
            for i, selected_user in enumerate(users):
                block = get_anonymous_message(message, msg_ids[i])
                client.chat_postMessage(channel=selected_user, blocks=block)
        elif callback_id.startswith("anonymous_messaging_modal_reply"):
            view = payload["view"]
            state = view["state"]
            message_id = callback_id.split("=")[1]
            # Unwrap control
            control = list(state["values"].items())
            control = control[0][1]
            control = list(control.items())[0][1]
            reply_msg = control["value"]
            print(reply_msg)
            reply = utils.reply_anon_message(user, message_id, reply_msg)
            block = get_anonymous_message(reply_msg, reply.id)
            client.chat_postMessage(channel=reply.target_id, blocks=block)
        elif callback_id.startswith("report_messaging_modal_reply"):
            view = payload["view"]
            state = view["state"]
            message_id = callback_id.split("=")[1]
            # Unwrap control
            control = list(state["values"].items())
            control = control[0][1]
            control = list(control.items())[0][1]
            report_msg = control["value"]
            print(report_msg)
            report_id = utils.report_message(message_id, report_msg)
            client.chat_postMessage(
                channel=payload["user"]["id"],
                text="Message Reported, to follow up "
                "provide the following report id: R{}".format(report_id))

    if payload["type"] == "block_actions":
        print(payload)
        if "trivia_custom_" in payload['actions'][0]['action_id']:
            trivia_customs(
                payload['actions'][0]['action_id'].replace(
                    "trivia_custom_", ""), payload['trigger_id'])
            return
        elif "accept_trivia_" in payload['actions'][0]['action_id']:
            trivia_reply(
                payload['user']['id'], True,
                payload['actions'][0]['action_id'].replace(
                    "accept_trivia_", ""), payload['trigger_id'])
            return
        elif "forfeit_trivia_" in payload['actions'][0]['action_id']:
            trivia_reply(
                payload['user']['id'], False,
                payload['actions'][0]['action_id'].replace(
                    "forfeit_trivia_", ""), payload['trigger_id'])
            return
        elif 'view' in payload and "trivia_start_" in payload['view'][
                'callback_id']:
            if "default_trivia_" in payload['actions'][0]['action_id']:
                trivia_set_qs(
                    payload['actions'][0]['action_id'].replace(
                        "default_trivia_", ""), payload['actions'][0]
                    ['selected_option']['value'] == "true")
                return
            elif 'view' in payload and "trivia_channel_" in payload['actions'][
                    0]['action_id']:
                trivia_set_channel(
                    payload['actions'][0]['action_id'].replace(
                        "trivia_channel_", ""),
                    payload['actions'][0]['selected_channel'])
                return
        elif 'view' in payload and "trivia_question_" in payload['view'][
                'callback_id']:
            trivia_response(payload['user']['id'],
                            payload['actions'][0]['value'] == 'correct',
                            payload['trigger_id'])
            return
        elif "course_overall_" in payload['actions'][0]['action_id']:
            review_overall(
                payload['actions'][0]['action_id'].replace(
                    "course_overall_", ""),
                payload['actions'][0]['selected_option']['value'])
        elif "course_difficulty_" in payload['actions'][0]['action_id']:
            review_difficulty(
                payload['actions'][0]['action_id'].replace(
                    "course_difficulty_", ""),
                payload['actions'][0]['selected_option']['value'])
        elif "course_time_" in payload['actions'][0]['action_id']:
            review_time(
                payload['actions'][0]['action_id'].replace("course_time_", ""),
                payload['actions'][0]['selected_option']['value'])

        # Received when a user clicks a Block Kit interactive component.
        actions = payload["actions"]
        value = actions[0]["value"]

        # Opens the "report" view
        if value == "click_report":
            message_id = payload["message"]["blocks"][0]["block_id"]
            client.views_open(trigger_id=trigger_id,
                              view=get_report_modal(message_id))

        # Opens the "anonymous_reply" modal
        if value == "click_reply":
            message_id = payload["message"]["blocks"][0]["block_id"]
            client.views_open(trigger_id=trigger_id,
                              view=get_anonymous_reply_modal(message_id))

        # Close Report
        if value.startswith("remove_report_"):
            report_id = value.split("_")[-1]
            utils.close_report(report_id)
            client.chat_postMessage(
                channel=payload["user"]["id"],
                text="Successfully removed report R{}".format(report_id))

        # No modal is expected
        if value == "pass":
            pass

        # Opens the "commands_help" view
        if value == "commands_help":
            client.views_open(trigger_id=trigger_id,
                              view=blocks.commands_help())

        # Opens the "edit_profile" view with prefilled information
        if value == "edit_profile":
            values = utils.retrieve_profile_details(user)
            client.views_open(trigger_id=trigger_id,
                              view=blocks.edit_profile(values))