我正在尝试通过API为松弛消息添加附件。我正在使用他们推荐的python包装器。我可以发送和接收基本消息但是当我尝试以2个按钮的形式添加附件时,它会失败。我已经做了一个松散的应用程序,并将他们在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'}
答案 0 :(得分:10)
我明白了。
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文档中对其进行格式化的方式。附件需要只是附件键后的数组。
答案 1 :(得分:1)
我想基本的简单示例有效。
示例:
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和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我尝试使用发送为数组。