飛書-消息推送

配置:

1.

 

 

2.

 

 

3.生成webhook-圖省略-加密

code:

# -*- coding:utf-8 -*-
'''
飛書消息通知-用於報告通知
'''

import requests
import json
import logging
import time
import urllib
import urllib3
urllib3.disable_warnings()


try:
JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError:
JSONDecodeError = ValueError


def is_not_null_and_blank_str(content):

if content and content.strip():
return True
else:
return False


class FeiShutalkChatbot(object):

def __init__(self, webhook, secret=None, pc_slide=False, fail_notice=False):

super(FeiShutalkChatbot, self).__init__()
self.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.webhook = webhook
self.secret = secret
self.pc_slide = pc_slide
self.fail_notice = fail_notice

def send_text(self, msg, open_id=[]):

data = {"msg_type": "text", "at": {}}
if is_not_null_and_blank_str(msg): # 傳入msg非空
data["content"] = {"text": msg}
else:
logging.error("text類型,消息內容不能爲空!")
raise ValueError("text類型,消息內容不能爲空!")

logging.debug('text類型:%s' % data)
return self.post(data)

def post(self, data):

try:
post_data = json.dumps(data)
response = requests.post(self.webhook, headers=self.headers, data=post_data, verify=False)
except requests.exceptions.HTTPError as exc:
logging.error("消息發送失敗, HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
raise
except requests.exceptions.ConnectionError:
logging.error("消息發送失敗,HTTP connection error!")
raise
except requests.exceptions.Timeout:
logging.error("消息發送失敗,Timeout error!")
raise
except requests.exceptions.RequestException:
logging.error("消息發送失敗, Request Exception!")
raise
else:
try:
result = response.json()
except JSONDecodeError:
logging.error("服務器響應異常,狀態碼:%s,響應內容:%s" % (response.status_code, response.text))
return {'errcode': 500, 'errmsg': '服務器響應異常'}
else:
logging.debug('發送結果:%s' % result)
# 消息發送失敗提醒(errcode 不爲 0,表示消息發送異常),默認不提醒,開發者可以根據返回的消息發送結果自行判斷和處理
if self.fail_notice and result.get('errcode', True):
time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
error_data = {
"msgtype": "text",
"text": {
"content": "[注意-自動通知]飛書機器人消息發送失敗,時間:%s,原因:%s,請及時跟進,謝謝!" % (
time_now, result['errmsg'] if result.get('errmsg', False) else '未知異常')
},
"at": {
"isAtAll": False
}
}
logging.error("消息發送失敗,自動通知:%s" % error_data)
requests.post(self.webhook, headers=self.headers, data=json.dumps(error_data))
return result
#調用
webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxx" #不能對外
feishu = FeiShutalkChatbot(webhook)
feishu.send_text("這是一條消息測試,能收到嗎")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章