飛書提供了豐富的api來實現消息的通知,包括文本消息、圖片消息、富文本消息,本次介紹使用飛書api發送文本消息,如下是實現思路
飛書API地址:https://open.feishu.cn/document/ukTMukTMukTM/uITNz4iM1MjLyUzMpython
1.須要獲取三個受權憑證git
2.根據zabbix報警的收信人手機號獲取user_id,用於後面在羣裏@相關負責人,或者直接發給某個責任人
3.chat_id用於發送給指定的羣,這裏我提供兩種方法獲取chat_id,後面會介紹
4.傳入zabbix報警消息,並艾特相關負責人發送到飛書羣裏或者我的github
登陸開發者後臺,在「個人應用」頁面建立企業自建應用。進入企業自建應用詳情頁,獲取App ID和App Secret。 json
一種方法是經過企業自建應用方式獲取,另外一種是經過應用商店應用獲取,這裏我使用第一種方法,直接建立應用便可 windows
def gettenant_access_token(): tokenurl="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/" headers={"Content-Type":"application/json"} data={ "app_id":"cli_9ec625abcdefg", "app_secret":"f716Gi27Yi25n5K0Wbafgwghhstv" } request=requests.post(url=tokenurl,headers=headers,json=data) response=json.loads(request.content)['tenant_access_token'] return response
user_id能夠根據註冊的手機號或郵箱獲取,能夠在zabbix中定義用戶的手機號,而後傳入參數獲取user_id api
def getuserid(tenant_access_token): #mobiles="15101234584" userurl="https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles=%s"%mobiles headers={"Authorization":"Bearer %s"%tenant_access_token} request=requests.get(url=userurl,headers=headers) response=json.loads(request.content)['data']['mobile_users'][mobiles][0]['user_id'] return response
這裏我提供兩種方法獲取chat_id,一種是將機器人加入到羣裏,獲取羣信息中的chat_id;另外一種是經過機器人建立羣聊獲取羣信息,固然還有其餘的方法,這裏我就不過多介紹了,我將使用第一種方法來獲取chat_idapp
def getchatid(tenant_access_token): #獲取chatid chaturl="https://open.feishu.cn/open-apis/chat/v4/list?page_size=20" headers={"Authorization":"Bearer %s"%tenant_access_token,"Content-Type":"application/json"} request=requests.get(url=chaturl,headers=headers) response=json.loads(request.content)['data']['groups'][0]['chat_id'] return response
這裏須要三個參數,一個是user_id,一個是chat_id,另外一個是tenant_access_token,並傳入報警信息便可發送 ide
def sendmes(user_id,chat_id,tenant_access_token): #向羣裏發送消息 sendurl="https://open.feishu.cn/open-apis/message/v4/send/" headers={"Authorization":"Bearer %s"%tenant_access_token,"Content-Type":"application/json"} data={"chat_id":chat_id, "msg_type":"text", "content":{ "text":"%s<at user_id=\"%s\">test</at>"%(messages,user_id) } } #給我的發送消息 # data={"user_id":user_id, # "msg_type":"text", # "content":{ # "text":"%s<at user_id=\"%s\">test</at>"%(messages,user_id) # } # } request=requests.post(url=sendurl,headers=headers,json=data) print(request.content)
注意參數順序不能亂 post
也就是用戶註冊飛書的手機號 測試
後續會添加帶有圖片信息的報警,完整代碼請訪問github組織遮陽筆記
https://github.com/sunsharing-note/zabbix/blob/master/feishu.py
歡迎關注我的公號「沒有故事的陳師傅」