• python实现飞书创建机器人发送消息


    一、前提

    1.创建一个自己的机器人应用,获取appid,appsecret,使用这两个获取token

    2.创建一个聊天群,将机器人添加到群内:https://open.feishu.cn/document/uYjL24iN/uYTMuYTMuYTM

    二、代码

    import requests
    
    class FeishuApi():
        def __init__(self,app_id,app_secret,chat_name):
            self.app_id=app_id
            self.app_secret=app_secret
            self.chat_name=chat_name
            self.access_token=self.get_access_token()
            self.headers={
                "Authorization": "Bearer {}".format(self.access_token),
                "Content-Type": "application/json"
            }
    
        # 获取token
        def get_access_token(self):
            data = {
                "app_id": self.app_id,
                "app_secret": self.app_secret
            }
            try:
                res = requests.post("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/", json=data)
                if res.status_code == 200:
                    res_json = res.json()
                    access_token = res_json.get("tenant_access_token")
                    return access_token
            except Exception as e:
                return {"error": e}
    
        # 获取群列表
        def get_chat_list(self):
            params = {
                "page_size": 100,
                "page_token": ""
            }
            try:
                res = requests.get("https://open.feishu.cn/open-apis/chat/v4/list", params=params, headers=self.headers)
                if res.status_code == 200:
                    res_json = res.json()
                    data = res_json.get("data")
                    groups = data.get("groups")
                    for i in groups:
                        if i.get("name") == self.chat_name:
                            return i
            except Exception as e:
                return {"error": e}
    
        def send_msg(self,text):
            res = self.get_chat_list()
            chat_id = res.get("chat_id")
    
            data = {
                "chat_id": chat_id,
                "msg_type": "text",
                "content": {
                    "text": text
                }
            }
            try:
                res=requests.post("https://open.feishu.cn/open-apis/message/v4/send/", headers=self.headers,json=data)
                return res.json()
            except Exception as e:
                return {"error":e}
    
    if __name__ == '__main__':
        app_id="*******"
        app_secret="********"
        chat_name="群名称"
        fei=FeishuApi(app_id,app_secret,chat_name)
        res=fei.send_msg("I am coming")
        print(res)
  • 相关阅读:
    线程安全与可重入编写方法
    新手MySQL工程师必备命令速查手册
    分布式之数据库和缓存双写一致性方案解析
    在java代码中用xslt处理xml文件
    Java并发编程之并发代码设计
    Java多线程和并发基础
    Java多线程面试大全
    springboot获取URL请求参数的多种方式
    JAVA文件转换为Base64
    Silver Cow Party
  • 原文地址:https://www.cnblogs.com/angelyan/p/12390027.html
Copyright © 2020-2023  润新知