SlackAskV2

Sends a message (question) to either user (in a direct message) or to a channel. The message includes predefined reply options. The response can also close a task (might be conditional) in a playbook. Note: a message maximum length is 3000 characters enforced by Slack API.

python · Slack

Source

import dateparser
import demistomock as demisto
from CommonServerPython import *

from CommonServerUserPython import *

STYLES_DICT = {"black": "", "green": "primary", "red": "danger"}

DATE_FORMAT = "%Y-%m-%d %H:%M:%S"


def create_blocks(text: str, entitlement: str, options: list, reply: str) -> list:
    value = json.dumps({"entitlement": entitlement, "reply": reply})
    blocks: list = [{"type": "section", "text": {"type": "mrkdwn", "text": text}}]

    elements = []
    for option in options:
        element = {"type": "button", "text": {"type": "plain_text", "emoji": True, "text": option["text"]}, "value": value}
        if "style" in option:
            element["style"] = option["style"]
        elements.append(element)
    if elements:
        actions = {"type": "actions", "elements": elements}
        blocks.append(actions)

    return blocks


def main():
    res = demisto.executeCommand(
        "addEntitlement",
        {
            "persistent": demisto.get(demisto.args(), "persistent"),
            "replyEntriesTag": demisto.get(demisto.args(), "replyEntriesTag"),
        },
    )
    if isError(res[0]):
        demisto.results(res)
        sys.exit(0)
    entitlement = demisto.get(res[0], "Contents")
    option1 = demisto.get(demisto.args(), "option1")
    option2 = demisto.get(demisto.args(), "option2")
    extra_options = argToList(demisto.args().get("additionalOptions", ""))
    reply = demisto.get(demisto.args(), "reply")
    response_type = demisto.get(demisto.args(), "responseType")
    lifetime = demisto.get(demisto.args(), "lifetime")
    slack_instance = demisto.get(demisto.args(), "slackInstance")
    slack_version = demisto.args().get("slackVersion", "SlackV3")
    try:
        parsed_date = dateparser.parse("in " + lifetime, settings={"TIMEZONE": "UTC"})
        assert parsed_date is not None, f"could not parse in {lifetime}"
        expiry = datetime.strftime(parsed_date, DATE_FORMAT)
    except Exception:
        parsed_date = dateparser.parse("in 1 day", settings={"TIMEZONE": "UTC"})
        assert parsed_date is not None
        expiry = datetime.strftime(parsed_date, DATE_FORMAT)
    default_response = demisto.get(demisto.args(), "defaultResponse")

    entitlement_string = entitlement + "@" + demisto.investigation()["id"]
    if demisto.get(demisto.args(), "task"):
        entitlement_string += "|" + demisto.get(demisto.args(), "task")

    args = {"ignoreAddURL": "true", "using-brand": slack_version}
    if slack_instance:
        args.update({"using": slack_instance})
    user_options = [option1, option2]
    options = []
    if extra_options:
        user_options += extra_options
    if response_type == "thread":
        for option in user_options:
            options.append(option.split("#")[0])
        string_options = " or ".join([f"`{o}`" for o in options])
        message = "{} - Please reply to this thread with {}.".format(demisto.args()["message"], string_options)
        args["message"] = json.dumps(
            {
                "message": message,
                "entitlement": entitlement_string,
                "reply": reply,
                "expiry": expiry,
                "default_response": default_response,
            }
        )
    else:
        for option in user_options:
            option = option.split("#")
            button = {"text": option[0]}
            if len(option) > 1:
                style = STYLES_DICT.get(option[1])
                if style:
                    button["style"] = style
            options.append(button)
        blocks = json.dumps(create_blocks(demisto.args()["message"], entitlement_string, options, reply))
        args["blocks"] = json.dumps(
            {
                "blocks": blocks,
                "entitlement": entitlement_string,
                "reply": reply,
                "expiry": expiry,
                "default_response": default_response,
            }
        )
        args["message"] = demisto.args()["message"]

    to = demisto.get(demisto.args(), "user")
    channel = demisto.get(demisto.args(), "channel")
    channel_id = demisto.get(demisto.args(), "channel_id")

    if to:
        args["to"] = to
    elif channel_id:
        args["channel_id"] = channel_id
    elif channel:
        args["channel"] = channel
    else:
        return_error("Either a user or a channel must be provided.")

    try:
        demisto.results(demisto.executeCommand("send-notification", args))
    except ValueError as e:
        if "Unsupported Command" in str(e):
            return_error("The command is unsupported by this script. If you have SlackV2 enabled, please use SlackAsk instead.")
        else:
            return_error("An error has occurred while executing the send-notification command", error=e)


if __name__ in ("__builtin__", "builtins", "__main__"):
    main()

README

Sends a message (question) to either user (in a direct message) or to a channel. The message includes predefined reply options. The response can also close a task (might be conditional) in a playbook.

SlackAskV2 was added to support the release of SlackV3 is only compatible with SlackV3.

Script Data


Name Description
Script Type python3
Tags slack
Demisto Version 5.5.0

Use Case


This automation allows you to ask users in Slack (including external to Cortex XSOAR) questions, have them respond and
reflect the answer back to Cortex XSOAR.

Dependencies


Requires an instance of the SlackV3 integration.

This script uses the following commands and scripts.

  • send-notification

Inputs


Argument Name Description
user The Slack user to which to send the message. Can be either an email address or a Slack user name.
channel The Slack channel to which to send the message.
message The message to send to the user or channel.
option1 The first reply option. The default is “Yes” with a green button. To change the color of the button, add the pound sign (#) followed by the name of the new color (green, red, or black). The default color is “green”. For example, “Yes#green”. Options cannot contain whitespaces.
option2 The second reply option. The default is “No” with a red button. To change the button color, add the pound sign (#) followed by the name of the new color (green, red, or black). The default color is “red”. For example, “No#red”. Options cannot contain whitespaces.
task The task to close with the reply. If empty, then no playbook tasks will be closed.
replyEntriesTag Tag to add to email reply entries.
persistent Indicates whether to use one-time entitlement or persistent entitlement.
responseType How the user should respond to the question.
additionalOptions A comma-separated list of additional options in the format of “option#color”, for example, “maybe#red”. The default color is “black”. Options cannot contain whitespaces.
reply The reply to send to the user. Use the templates {user} and {response} to incorporate these in the reply. (i.e. “Thank you {user}. You have answered {response}.”)
lifetime Time until the question expires. For example - 1 day. When it expires, a default response is sent.
defaultResponse Default response in case the question expires.
slackInstance The instance of SlackV3 this script should use.
slackVersion The version of Slack to use. SlackV3 is configured by default.

Outputs


There are no outputs for this script.

Guide


The automation is most useful in a playbook to determine the outcome of a conditional task - which will be one of the provided options.
It uses a mechanism that allows external users to respond in Cortex XSOAR (per investigation) with entitlement strings embedded within the message contents.
SlackAsk

The automation can utilize the interactive capabilities of Slack to send a form with buttons -
this requires the external endpoint for interactive responses to be available for connection (See the SlackV3 integration documentation for more information).
You can also utilize threads instead, simply by specifying the responseType argument.

To use SlackAskV2 via playbook:

  1. Add the SlackAskV2 script to a playbook as a task.
  2. In the message argument, specify the message to be sent.
  3. Configure the response options by filling out the option1 and option2 arguments (default values are ‘Yes’ and ‘No’).
  4. Either a user or a channel_id or channel_name must be specified.
  5. In the SlackAskV2 task, pass a tag value to the task argument.

All other inputs are optional.
At some point at the playbook, after running SlackAskV2, add a manual conditional task, which holds up the playbook execution until the response is received from Slack.
The condition names must match the response options you passed in to SlackAskV2.
In order to tie the conditional task back to SlackAskV2, add the same tag from the fifth step to the conditional task (under the “Details” tab of the task). The conditional task will be marked as completed when a user responds to the SlackAskV2 form.

Notes


  • When using the replyEntriesTag argument, the persistent argument must be set to True.
  • SlackAskV2 will not work when run in the playbook debugger. This is because the debugger does not generate entitlements, since they must be tied to an investigation. Entitlements are needed to track the response.
  • Whitespaces are not supported in custom options and will not work. (i.e. setting a button to I Agree)