如何通过Incoming Webhook在Mattermost中添加message-attachments?
可以在Mattermost中通过Incoming Webhook添加message-attachments
完全可以通过HTTP请求结合Incoming Webhook实现你要的附件消息效果,你的代码核心问题是payload的结构不正确——Mattermost的attachments是顶级字段,不需要嵌套在props里。
修正后的Python代码如下:
import requests # 注意要导入requests库,否则代码会报错 def mattermost(): mattermost_webhook_url = "https://matter.com/hooks/some-hook" message = "Hello, Mattermost" # 正确的payload结构:attachments直接作为顶级键 payload = { 'attachments': [ { 'color': '#FF0000', # 消息左侧的侧边栏颜色 'text': message, # 附件区域的文本内容 # 可按需添加更多样式字段,比如标题、自定义字段列表 # 'title': '自定义消息标题', # 'fields': [ # {'title': '字段1', 'value': '对应内容', 'short': True}, # {'title': '字段2', 'value': '对应内容', 'short': True} # ] } ] } response = requests.post(mattermost_webhook_url, json=payload) print(response.text) # 打印响应内容,方便排查格式错误等问题 if response.status_code == 200: return "Message sent successfully to Mattermost channel." else: return f"Failed to send message to Mattermost channel. Status code: {response.status_code}"
关键修改说明:
- 移除了
props嵌套层级,将attachments直接放在payload根目录下,符合Mattermost Webhook的规范 - 补充了
requests库的导入提示(原代码缺失该依赖) - 将
print(response)改为print(response.text),能查看Mattermost返回的具体错误信息,方便调试
如果需要实现更复杂的附件样式,可以参考Mattermost官方文档扩展attachments内的字段,支持标题、按钮、字段分组等多种元素。
内容的提问来源于stack exchange,提问作者Apurva
相关产品推荐
相关产品推荐

