Slack API chat.postMessage介绍

本文介绍了SlackAPI的chat.postMessage方法,用于向频道、私有通道或直接消息发送消息,支持包括格式化文本、表情、附件等多种内容。文中详细阐述了请求参数如token、channel、attachments和blocks的用法,并提供了Python代码示例来展示如何设置粗体、斜体、表情、附件链接和回复功能。同时,文章提到了使用注意事项,如消息长度限制和发送频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档链接: chat.postMessage

一、方法功能介绍

官方原译为:该方法将消息发布到公共通道、私有通道或直接消息/IM通道。
个人理解总结:
1.1.可以向指定的channel、用户等发送消息,消息中可以包含高亮标题、表情、图像、url连接、@等。
1.2.可以对某条已经发送过的消息进行回复、评论。
1.3.可以对发送块、附件,并且对块颜色进行设置。

二、用前注意事项

唯一标识:每条已发送的消息,都有它的唯一标识:ts。
消息大小:每条消息的字数限制在4000字。总字符在40000字符。超过则发送失败。
发送频率:允许一个应用程序每秒钟发布一条消息到一个特定的频道。超过这个频率则发送失败。
消息格式:可以设置粗体和斜体,但不能对文本设置颜色。

三、使用介绍

Slack API提供了四种调用该方法的使用方式。官方文档中声明了代码示例

TYPE请求方式请求头请求必填参数
HTTPPOSTapplication/x-www-form-urlencoded、application/jsontoken、channel
JavaScriptXapplication/x-www-form-urlencoded、application/jsontoken、channel
PythonXapplication/x-www-form-urlencoded、application/jsontoken、channel
JavaXapplication/x-www-form-urlencoded、application/jsontoken、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_usertrue:以用户形式发送;false:以BOT形式发送。默认为falsefalse
icon_emoji表情符号。(as_user设置为false时一起使用)📈
icon_url图像url。(as_user设置为false时一起使用)http://lorempixel.com/48/48
link_names查找并链接用户组true
metadatafalsefalse
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 )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值