當前飛書webhook機器人還不支持發送文件類型的群消息,它目前僅支持文本,富文本,卡片等文字類型的數據。
我們可以申請創建一個機器人應用來實現群發送文件消息。
創建飛書應用
創建飛書應用、配置權限、添加機器人
- 來到飛書開發者后臺
創建企業自建應用
輸入名稱、描述
-
創建應用后,需要開通一系列權限,然后發布。由管理員審核通過后,才可使用
在上述位置下添加下述權限并開通
-
創建機器人
在上述位置添加好機器人 -
在你要發送的群里中添加剛剛創建的機器人(我這的機器人取名為“推送報表”)
-
最后提交發布, 在憑證和基礎信息這里獲取
app id
app secret
調用API上傳文件
流程順序如下:通過app_id,app_secret獲取token -> 上傳文件(獲取文件id)-> 獲取群聊chat_id -> 通過文件id將文件上傳到指定chat_id
- 獲取token
def get_token():""" 獲取飛書 access_token """url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"headers = {"Content-Type": "application/json"}data = {"app_id": APP_ID,"app_secret": APP_SECRET}response = requests.post(url, headers=headers, json=data)if response.status_code == 200:return response.json()["tenant_access_token"]else:return ""
- 上傳文件到飛書,并獲取文件id
def upload_file(file_name, file_path):""" 上傳文件到飛書 """url = "https://open.feishu.cn/open-apis/im/v1/files"headers = {"Authorization": "Bearer "+get_token()}form = {"file_type": "stream","file_name": file_name,"file": (file_name, open(file_path, "rb"), "text/plain")}multi_form = MultipartEncoder(form)headers["Content-Type"] = multi_form.content_typeresponse = requests.post(url, headers=headers, data=multi_form)if response.status_code == 200 and response.json().get("code") == 0:# print(f"上傳文件到飛書成功,msg={response.json()},{file_path=}")media_id = response.json().get("data", {}).get("file_key")return media_idelse:return ""
- 獲取群chat_id
有兩種方式,通過api,或者直接通過平臺粘貼對應群聊id,這里使用后者,因為是發送到固定群聊
去到api調試頁面,按照如下操作獲取對應群聊chat_id
- 發送文件到群里
def send_file(file_path, media_id=None):"""機器人應用上傳文件"""if not media_id:media_id = upload_file(file_name=file_path, file_path=file_path)time.sleep(1)url = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id'msgContent = {"file_key": media_id}form = {"content": json.dumps(msgContent),"msg_type": "file","receive_id": CHAT_ID}headers = {'Authorization': 'Bearer ' + get_token()}response = requests.post(url=url, data=json.dumps(form), headers=headers)print(response.json())
完成文件發送