Search code examples
pythonpython-3.xpython-requestsslack

Handle Slack button action POST request data in python


I'm trying to make confirmation slack button while running slash command. e.g. I run slash-command (/test) it sends the POST request to my python app which sends back 2 buttons (Confirm, Cancel). User presses one of the buttons slack triggers an action and sends another POST request to my app. All is working fine before this step - I cannot handle the data from 2nd POST request correctly.

In the Slack documentation I found this:

When an action is invoked, a request will be sent to the app's Request URL as configured above; the request body will contain a payload parameter that your app should parse for JSON.

When I do

data=json.loads(request.form["payload"])
return jsonify(data)

I get

{
 "action_ts": "XXXX",
 "actions": [
   {
     "name": "confirm",
     "type": "button",
     "value": "confirm"
   }
 ],
 "attachment_id": "X",
 "callback_id": "XXXX",
 "channel": {
   "id": "XXXX",
   "name": "XXXX"
 },
 "is_app_unfurl": false,
 "message_ts": "XXXX",
 "response_url": "XXXX",
 "team": {
   "domain": "XXXX",
   "id": "XXXX"
 },
 "token": "XXXX",
 "trigger_id": "XXXX",
 "type": "interactive_message",
 "user": {
   "id": "XXXX",
   "name": "XXXX"
 }
}

After when I call

data=json.loads(request.form["payload"]) 
action=data["actions"]
return jsonify(action)

I get

[
    {
        "name": "confirm",
        "type": "button",
        "value": "confirm"
    }
]

Now when I'm trying to get value of "name" with action["name"] I receive the error

TypeError: list indices must be integers or slices, not str

I tried json.dumps(action) and json.dumps(action["name"]) neither of them worked. How to read that values? I need to check value of name and then do the rest with it.


Solution

  • [
    {
    "name": "confirm",
    "type": "button",
    "value": "confirm"
    }
    ]
    

    is a list containing one element - the dictionary. Access the name like data["actions"][0]["name"]