当我尝试向消息添加附件时,我要么只获取文本,要么如果省略文本,我会收到“错误”:“no_text”,有什么方法可以使用 chat.postMessage 发送附件吗?
这是我用来发送消息的 python 代码:
r = requests.post('https://slack.com/api/chat.postMessage', params=json.loads("""
{
"token": "xoxp-mytokenhere",
"channel": "C4mychannelhere",
"attachments": [
{
"text": "Question?",
"fallback": "Question?",
"callback_id": "callback_id",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "question",
"text": "Yes",
"style": "good",
"type": "button",
"value": "yes"
},
{
"name": "question",
"text": "Nope",
"style": "good",
"type": "button",
"value": "no"
}
]
}
]
}
"""))
Run Code Online (Sandbox Code Playgroud)
根据评论,我采用了以下解决方案:
r = requests.post('https://slack.com/api/chat.postMessage', params=json.loads({
"token": "xoxp-mytokenhere",
"channel": "C4mychannelhere",
"attachments": json.dumps([
{
"text": "Question?",
"fallback": "Question?",
"callback_id": "callback_id",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "question",
"text": "Yes",
"style": "good",
"type": "button",
"value": "yes"
},
{
"name": "question",
"text": "Nope",
"style": "good",
"type": "button",
"value": "no"
}
]
}
])
}))
Run Code Online (Sandbox Code Playgroud)
您似乎正在尝试将 JSON 字符串作为整个参数集发送到chat.postMessage.
chat.postMessage而其他 Web API 方法仅支持 URL 编码的查询或 POST 正文参数,因此您的字段(例如token和channel)attachments将作为 application/x-www-form-urlencoded 键/值对发送。
让事情变得更复杂的是,该attachments参数实际上接受一串 URL 编码的 JSON 数据。您的 JSON 数组需要进行 URL 编码并填充到该参数中。
根据您的目标,您可以跳过使用json.loads,仅将 JSON 字符串作为attachments参数传递,并requests为您处理 URL 编码 - 或者您可以json.dump在使用相同属性构建的本机 Python 数组上使用类似的内容。