2025年6月4日 星期三 乙巳(蛇)年 三月初八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python:通过飞书API接口发送通知消息

时间:05-24来源:作者:点击数:36

通过飞书发送应用消息,及时收到线上异常消息

总的来说,飞书消息发送的前戏,要比企业微信和钉钉稍复杂

相关连接

参数准备

  1. 首先,在 飞书开放平台 创建应用,提交审批
  2. 再到 飞书管理后台 审批应用
  3. 回到 飞书开放平台 添加应用能力 / 机器人,获取应用凭证 App_ID 和 App_Secret
  4. 在 飞书开放平台 ,通过接口调试,获取open_id

代码示例

  • # -*- coding: utf-8 -*-
  • """
  • @File : demo.py
  • @Date : 2023-06-22
  • """
  • import json
  • import requests
  • def get_access_token(app_id, app_secret):
  • """
  • 自建应用获取 tenant_access_token
  • https://open.feishu.cn/document/server-docs/authentication-management/access-token/tenant_access_token_internal
  • :param app_id: 应用唯一标识
  • :param app_secret: 应用秘钥
  • :return:
  • {
  • "code": 0,
  • "msg": "success",
  • "tenant_access_token": "t-xxx",
  • "expire": 7140
  • }
  • """
  • url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'
  • params = {
  • 'app_id': app_id,
  • 'app_secret': app_secret
  • }
  • res = requests.post(url, params=params)
  • return res.json()
  • def send_message(access_token, body, params):
  • """
  • 发送消息
  • https://open.feishu.cn/document/server-docs/im-v1/message/create
  • :param access_token:
  • :param body: 消息体
  • :param params: 查询参数 {"receive_id_type":"open_id"}
  • :return:
  • """
  • url = 'https://open.feishu.cn/open-apis/im/v1/messages'
  • headers = {
  • 'Authorization': 'Bearer ' + access_token
  • }
  • res = requests.post(url, params=params, headers=headers, json=body)
  • return res.json()
  • if __name__ == '__main__':
  • # App ID
  • app_id = '<App ID>'
  • # App Secret
  • app_secret = '<App Secret>'
  • # OpenId
  • open_id = '<OpenId>'
  • token = get_access_token(app_id, app_secret)
  • print(token)
  • params = {"receive_id_type": "open_id"}
  • payload = {
  • "receive_id": open_id,
  • "msg_type": "text",
  • "content": json.dumps({
  • "text": "你好,飞书!"
  • })
  • }
  • res = send_message(token['tenant_access_token'], payload, params)
  • print(res)

发送截图

在这里插入图片描述
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门