小白手把手搭建Python版飞书机器人

2,922 阅读2分钟
  1. 使用飞书电脑版客户端进行三人聊天群的创建 111.png
  2. 在群设置-群机器人-自定义添加机器人!

22.png

  1. 对机器人进行配置,其中签名下方的字符串就是Secret,Robot_id为webhook地址的最后一串字符串,加粗部分,如#webhook open.feishu.cn/open-apis/b…](p3-juejin.byteimg.com/tos-cn-i-k3… "51992")

  2. 机器人创建成功,如下图所示!

333.png

  1. python代码实现

       import json
       import requests
       import time
       import hmac
       import hashlib
       import base64
       from urllib import parse
       from datetime import datetime
       import telegram # pip install python-telegram-bot
    
    
       class FeiShuRobot:
    
    
           def __init__(self, robot_id, secret) -> None:
               self.robot_id = robot_id
               self.secret = secret
    
           def gen_sign(self):
               # 拼接timestamp和secret
               timestamp = int(round(time.time() * 1000))
               string_to_sign = '{}\n{}'.format(timestamp, self.secret)
               hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    
               # 对结果进行base64处理
               sign = base64.b64encode(hmac_code).decode('utf-8')
               print(timestamp,sign)
               return str(timestamp), str(sign)
           def get_token(self):
               """获取应用token,需要用app_id和app_secret,主要是上传图片需要用到token"""
               url = r"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
               headers = {"Content-Type": "text/plain"}
               Body = {
               "app_id": self.robot_id,
               "app_secret": self.secret
               }
               r = requests.post(url, headers=headers, json=Body)
               return json.loads(r.text)['tenant_access_token']
    
           def upload_image(self, image_path):
               """上传图片"""
               with open(image_path, 'rb') as f:
                   image = f.read()
               resp = requests.post(
                   url='https://open.feishu.cn/open-apis/image/v4/put/',
                   headers={'Authorization': "Bearer "+ self.get_token()},
                   files={
                       "image": image
                   },
                   data={
                       "image_type": "message"
                   },
                   stream=True)
               resp.raise_for_status()
               content = resp.json()
               if content.get("code") == 0:
                   return content['data']['image_key']
               else:
                   return Exception("Call Api Error, errorCode is %s" % content["code"])
    
           def send_text(self, text):
               """发送普通消息"""
               try:
                   url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{self.robot_id}"
                   headers = {"Content-Type": "text/plain"}
    
                   timestamp, sign = self.gen_sign()
                   data = {
                                   "timestamp": timestamp,
                                   "sign": sign,
                                   "msg_type": "text",
                                   "content": {
                                           "text": text
                                   }
                           }
                   r = requests.post(url, headers=headers, json=data)
                   print("发送飞书成功")
    
                   return r.text
               except Exception as e:
                   print("发送飞书失败:", e)
    
           def send_img(path,bot):
               """发送图片消息"""
               url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{bot}"
               headers = {"Content-Type": "text/plain"}
               data = {
                   "msg_type":"image",
                   "content":{
                       "image_key": upload_image(path)
                   }
               }
               r = requests.post(url, headers=headers, json=data)
               return r.text
    
           def send_markdown(text,bot):
               """发送富文本消息"""
               url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{bot}"
               headers = {"Content-Type": "text/plain"}
               data = {
               "msg_type": "interactive",
               "card": {
               "config": {
                   "wide_screen_mode": True
               },
               "header": {
                   "title": {
                       "tag": "plain_text",
                       "content": "注意咯!!注意咯!!!"
                   },
                   "template":"red"
               },
               "elements": [{"tag": "div",
                                 "text": {"content":text,
                                 "tag": "lark_md"}}]}
               }
               r = requests.post(url, headers=headers, json=data)
               return r.text
    
           def send_card(Text,bot):
               """发送卡片消息"""
               try:
                   url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{bot}"
                   headers = {"Content-Type": "text/plain"}
                   data = {
                   "msg_type": "interactive",
                   "card": Text
                   }
                   r = requests.post(url, headers=headers, json=data)
                   return r.text
    
               except Exception as e:
                   print("发送飞书失败:", e)
    
       def feishu_test():
           #webhook https://open.feishu.cn/open-apis/bot/v2/hook/bd0e6b04-59a4-4587-ade0-874c19a0898d
           robot_id = 'xxxxxxxxxxxxxxxxxx'
           secret = 'xxxxxxxxxxxxxxxx'
    
           feishu = FeiShuRobot(robot_id, secret)
           now = datetime.now()
           # print(type(now.second))
           if now.second % 10 == 0:
               feishu.send_text('哎,行行好!')
               feishu.send_text('哎,行,行,好!')
    
       if __name__ == '__main__':
           while True:
               feishu_test()
    
    1. 测试结果

444.png

# 结语

附件代码同时集成了钉钉和Telegram的机器人,欢迎大家使用!