Slack API - 来自自定义机器人 post 的纯文本附件

Slack API - Attatchments from custom bot post as plain text

我正在使用 Python 2.7 和 python-slackclient。我有这样的附件结构:

self.msg = {
    "attachments": [
        {
            "fallback": "%s, %s" % (self.jiraIssueObj.fields.summary, self.link),
            "pretext": "Detail summary for %s" % self.jiraIssueObj,
            "title": self.jiraIssueObj.fields.summary,
            "title_link": self.link,
            "text": self.jiraIssueObj.fields.description[0:self.maxSummary],
            "color": "#7CD197",
            "mrkdwn_in": ["text", "pretext", "fields"]
        }
    ]
}

那么,

def Send(self):
        if (self.msg):
            slack_client.api_call("chat.postMessage", channel=self.channel, text=self.msg, as_user=True)
            self.msg = None

然而,当这个发布时,它只是发布明文,没有格式化:

{"attachments": [{"title": "Upgrade Grafana to 3.0", "color": "#7CD197 ", "text": "I\u2019ve added the JIRA maillist so this email will create a ticket we can queue it up in support.\u00a0 Eric if you wouldn\u2019t mind just replying to this email with the additional info?\n\n\u00a0\n\n\u00a0\n\nSent: Thursday, August 25, 2016 11:41 AM\n", "title_link": "https://jira.jr.com/browse/ops-164", "mrkdwn_in": ["text", "pretext", "fields"], "pretext": "Detail summary for ops-164", "fallback": "Upgrade Grafana to 3.0, https://jira.jr.com/browse/ops-164"}]}

我做错了什么?我也尝试过在 Send() 调用中执行 attachments=self.msg,但这样做时我的松弛通道根本没有输出。

chat.postMessage 方法有几个怪癖——像大多数 Slack 的网络 APIs,它只支持 application/x-www-form-urlencoded content-types,不支持 JSON。更古怪的方面是 attachments 参数采用 JSON 的 URL-encoded 数组。现在,您似乎正在向 text 参数发送原生 Python 数组。

为了让 Slack 理解该结构,您首先需要将其转换为 JSON 字符串。您正在使用的 API 包装器可能会处理下一步转换为 URL-encoded 表示形式。

最后,附件本身不会放在邮件的 text 中——那是一个单独的字段。在将 JSON 字符串定义为 self.attachments:

之后,您需要指定更多类似的内容

slack_client.api_call("chat.postMessage", channel=self.channel, attachments=self.attachments, as_user=True)

包含附件后,text 字段变为可选。

事实证明,对

的调用
slack_client.api_call("chat.postMessage", channel=self.channel, attachments=self.msg, as_user=True)

似乎可以为您添加顶层 { "attachments": ... }。因此,通过将我的 self.msg 更改为:

self.format = [{
    "fallback": "%s, %s" % (self.jiraIssueObj.fields.summary, self.link),
    "pretext": "Detail summary for %s" % self.jiraIssueObj,
    "title": self.jiraIssueObj.fields.summary,
    "title_link": self.link,
    "text": self.jiraIssueObj.fields.description[0:self.maxSummary],
    #"color": "#7CD197",
    "mrkdwn_in": ["text", "pretext", "fields"]
}]

没有这个外部 { "attachments": ... } 包装器,api 能够 post 按预期发送邮件附件。