Slack API chat.postMessage介绍
官方文档链接: chat.postMessage
一、方法功能介绍
官方原译为:该方法将消息发布到公共通道、私有通道或直接消息/IM通道。
个人理解总结:
1.1.可以向指定的channel、用户等发送消息,消息中可以包含高亮标题、表情、图像、url连接、@等。
1.2.可以对某条已经发送过的消息进行回复、评论。
1.3.可以对发送块、附件,并且对块颜色进行设置。
二、用前注意事项
唯一标识:每条已发送的消息,都有它的唯一标识:ts。
消息大小:每条消息的字数限制在4000字。总字符在40000字符。超过则发送失败。
发送频率:允许一个应用程序每秒钟发布一条消息到一个特定的频道。超过这个频率则发送失败。
消息格式:可以设置粗体和斜体,但不能对文本设置颜色。
三、使用介绍
Slack API提供了四种调用该方法的使用方式。官方文档中声明了代码示例
TYPE | 请求方式 | 请求头 | 请求必填参数 |
---|---|---|---|
HTTP | POST | application/x-www-form-urlencoded、application/json | token、channel |
JavaScript | X | application/x-www-form-urlencoded、application/json | token、channel |
Python | X | application/x-www-form-urlencoded、application/json | token、channel |
Java | X | application/x-www-form-urlencoded、application/json | token、channel |
3.1.请求参数介绍
请求参数名 | 含义 | 示例 |
---|---|---|
token(必填) | token令牌 | xxxx-xxxxxxxxx-xxxx |
channel(必填) | 通道的ID或者名称 | C1234567890 |
attachments | 附件 | [{“pretext”: “pre-hello”, “text”: “text-world”}] |
blocks | 块 | [{“type”: “section”, “text”: {“type”: “plain_text”, “text”: “Hello world”}}] |
text | 格式化文本 | Hello world |
as_user | true:以用户形式发送;false:以BOT形式发送。默认为false | false |
icon_emoji | 表情符号。(as_user设置为false时一起使用) | 📈 |
icon_url | 图像url。(as_user设置为false时一起使用) | http://lorempixel.com/48/48 |
link_names | 查找并链接用户组 | true |
metadata | false | false |
mrkdwn | 是否禁用Slack标记解析,默认为启用 | false |
parse | 更改处理消息的方式 | full |
reply_broadcast | 与thread_ts一起使用,指示回复是否应该对通道或对话中的所有人可见。默认为false。 | true |
thread_ts | 另一条消息的唯一标识ts值 | 166993.133 |
unfurl_links | 是否展开文本的内容 | true |
unfurl_media | 是否禁用媒体内容的展开 | false |
username | 设置机器人的用户名。必须与as_user设置为false一起使用,否则将被忽略。 | My Bot |
3.2.返回参数介绍
一般情况下只需关注"ok"、"ts"即可。“ts”=请求参数中的thread_ts
#成功示例
{
"ok": true,
"channel": "C123456",
"ts": "1503435956.000247",
"message": {
"text": "Here's a message for you",
"username": "ecto1",
"bot_id": "B123456",
"attachments": [
{
"text": "This is an attachment",
"id": 1,
"fallback": "This is an attachment's fallback"
}
],
"type": "message",
"subtype": "bot_message",
"ts": "1503435956.000247"
}
}
#失败示例,在error中有明确的错误提示,可以在官方文档中查找到对应的详细原因
{
"ok": false,
"error": "too_many_attachments"
}
四、场景示例
4.1.消息设置为粗体、斜体,加表情
目标:将部分文本消息设置为粗体,部分设置为斜体,且在最末尾加上微笑表情。
效果:
实现方式:通过pycharm使用http方式实现效果。
import json
import requests
def sendMessage2Slack(token,channel):
#加粗用* * 斜体用_ _ 表情用: :
blocks = [{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "将部分文本消息设置为 *粗体* ,部分设置为 _斜体_ ,且在最末尾加上微笑表情 :smile:"
},"block_id": "text1"
}
]
payload = {"blocks": blocks,"channel": channel}
data = json.dumps(payload).encode("utf8")
url = 'https://slack.com/api/chat.postMessage'
header = {"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + token}
response = requests.post(url, data=data, headers=header)
print(response.text)
if __name__ == "__main__":
token ="****-*********-*********-*********" #Bot的Token
channel = 'C0*********' #频道ID
sendMessage2Slack(token, channel)
4.2.消息增加附件链接,给附件添加颜色
目标:消息增加附件链接,并且为附件设置左侧垂直颜色条为绿色
效果:
实现方式:通过pycharm使用http方式实现效果。
import json
import requests
def sendMessage2Slack(token,channel):
attachments =[
{
"title": "附件的链接", #给url设置一个名字,对应蓝色字体
"title_link": "https://img0.baidu.com/it/u=3278409307,2082501724&fm=253&fmt=auto?w=130&h=170",
"text": "附件说明:我是一个图片", #对附件进行解释,对应黑色字体
"color": "#7CD197" #给整个附件左侧垂直条添加为绿色
}
]
payload = {"attachments": attachments,"channel": channel}
data = json.dumps(payload).encode("utf8")
url = 'https://slack.com/api/chat.postMessage'
header = {"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + token}
response = requests.post(url, data=data, headers=header)
print(response.text)
if __name__ == "__main__":
token ="****-*********-*********-*********" #Bot的Token
channel = 'C0*********' #频道ID
sendMessage2Slack(token, channel)
此时在slack中点击蓝色字体即可跳转到对应的url地址。
4.3.对消息添加回复功能,并且在其中@某个用户
目标:在消息中添加回复消息"我已经阅读了这条消息,请@test001 您仔细查看",在回复的消息中@某个用户
效果:
前提条件:
4.3.1.需要拿到某条消息的thread_ts也就是ts也就是这条消息的唯一标识,例如我们在4.2步骤中成功发送消息后,slack会返回我们一串消息:
其中"ts":"1675388766.695329"就是代表已发送这条消息的唯一标识
4.3.2.需要拿到所要@用户的ID,slack api 暂时不支持@用户名。两种方式获取用户的ID,一种直接通过slack页面个人信息获取: slack 查看各种信息;另外一种是通过slack api中的users.list方法获取:链接: Slack API users.list介绍
实现方式:通过pycharm使用http方式实现效果。
import json
import requests
def replyMsg(channel, slackToken, thread_ts, text):
attachments = [{"text": text}]
payload = {"channel": channel, "thread_ts": thread_ts, "attachments": attachments}
data = json.dumps(payload).encode("utf8")
url = 'https://slack.com/api/chat.postMessage'
header = {"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + slackToken}
response = requests.post(url, data=data, headers=header)
ApplyReposen = json.loads(response.text)
print("Slack API ApplyReposen ={}".format(ApplyReposen))
if ApplyReposen["ok"]:
print("[info] Slack API Reply Message 成功!")
else:
print("[info] Slack API Reply Message 失败! detailMessage:{}".format(ApplyReposen))
if __name__ == "__main__":
token ="****-******-******-******" #Bot的Token
channel = 'C******' #频道ID
thread_ts = "1675388766.695329" #4.2步骤发送消息,slack返回后ts
text = "我已经阅读了这条消息,请<@U04H******> 您仔细查看" #回复的消息 其中的”<@U04H******>“为@用户的格式,U04H******为用户的ID
replyMsg(channel, token, thread_ts , text )