添加附件到 Slackbot

Adding attachment to Slackbot

我正在尝试通过他们的 API 向 slack 消息添加附件。我正在使用他们推荐的 python 包装器。我可以发送和接收基本消息,但是当我尝试以 2 个按钮的形式添加附件时,它失败了。我制作了一个 slack 应用程序并按照他们在 API 中的说明链接了机器人。我仔细查看了 API,但无法弄清楚发生了什么。

def process_message(message, channel):
    intro_msg = json.loads('{
                      "text": "What would you like to do?",
                      "attachments": [
                        {
                          "text": "Choose an action",
                          "fallback": "You are unable to choose an option",
                          "callback_id": "lunch_intro",
                          "color": "#3AA3E3",
                          "attachment_type": "default",
                          "actions": [
                            {
                              "name": "enroll",
                              "text": "Enroll",
                              "type": "button",
                              "value": "enroll"
                            },
                            {
                              "name": "leave",
                              "text": "Leave",
                              "type": "button",
                              "value": "leave"
                            }
                          ]
                        }
                      ]
                    }')
    r = sc.api_call("chat.postMessage", channel=channel, attachments=intro_msg)

回复只有{u'ok': False, u'error': u'no_text'}

我猜这个基本的简单示例可行。

示例:

from slackclient import SlackClient

slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)

sc.api_call(
  "chat.postMessage",
  channel="#python",
  text="Hello from Python! :tada:"
)

根据https://api.slack.com/methods/chat.postMessage and https://api.slack.com/docs/message-buttons#readying_your_application_for_message_buttons,附件必须是一个数组。如何将其作为数组发送:

json.loads('[{"text":"What would you like to do?","attachments":[{"text":"Choose an action","fallback":"You are unable to choose an option","callback_id":"lunch_intro","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"enroll","text":"Enroll","type":"button","value":"enroll"},{"name":"leave","text":"Leave","type":"button","value":"leave"}]}]}]')

因为除了请求模块之外没有进一步的魔法 https://github.com/slackapi/python-slackclient/blob/ddf9d8f5803040f0397d68439d3217d1e1340d0a/slackclient/_slackrequest.py 我会尝试使用数组发送。

我想通了。

python 包装器分离出负载。

intro_msg  = json.dumps([{"text":"Choose an action","fallback":"You are unable to choose an option","callback_id":"lunch_intro","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"enroll","text":"Enroll","type":"button","value":"enroll"},{"name":"leave","text":"Leave","type":"button","value":"leave"}]}])

sc.api_call("chat.postMessage", channel=channel, text="What would you like to do?", attachments=intro_msg, as_user=True)

我的有效载荷都在附件中,因为他们在 API 文档中就是这样格式化的。附件只需是附件键后的数组。