Python: Send notification messages through the Feishu API interface

Send application messages through Feishu and receive online abnormal messages in time

In general, the foreplay of Feishu message sending is slightly more complicated than that of Enterprise WeChat and DingTalk

related link

Parameter preparation

  1. First , create an application on the Feishu Open Platform and submit it for approval
  2. Then go to the Feishu management background to approve the application
  3. Go back to Feishu Open Platform Add Application Capabilities/Robots, Obtain Application Credentials App_IDandApp_Secret
  4. On the Feishu open platform , through interface debugging, obtainopen_id

code example

# -*- 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)

send screenshot
insert image description here

Guess you like

Origin blog.csdn.net/mouday/article/details/131343127