獲取釘釘機器人
- 創建釘釘群組(要求至少三個成員)
- 進入群組 設置>機器人>添加機器人
- 選擇自定義機器人 按照要求填寫完獲取到 Webhook的鏈接
實現代碼
from time import sleep
import requests
import json
from datetime import datetime
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
target_url = 'http://XXXX'
target_args = {'question': 'XXX'}
start_time = "08:30"
end_time = "19:00"
sleep_time = 60 * 60 * 2def chat_service_check(url, body):try:response = requests.post(url, json=body)if response.status_code != 200:logging.info(f'響應結果異常:響應值={response.text}')return Falseif json.loads(response.text)['code'] != 200:logging.info(f'調用接口失敗:{response.text}')return Falseelse:return Trueexcept requests.RequestException as e1:logging.error(f'響應結果異常', e1)return Falsedef dingmessage(msg):webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=XXXXX'data = {'msgtype': 'text','text': {'content': '監控通知:' + msg}}res = requests.post(webhook_url , json=data)logging.info(f'通知返回結果:{res.text}')def task():logging.info(f'當前時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")},調用目標接口')chat_check = chat_service_check(target_url, body=target_args)logging.info(f'當前時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")},調用目標接口結束')if not chat_check:logging.info(f'當前時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")},調用目標接口失敗')dingmessage('chat 接口異常請即使處理')if __name__ == '__main__':while True:current_time = datetime.now()start_time1 = datetime.strptime(str(datetime.now().date()) + start_time, "%Y-%m-%d%H:%M")end_time1 = datetime.strptime(str(datetime.now().date()) + end_time, "%Y-%m-%d%H:%M")if start_time1 <= current_time < end_time1:logging.info("當前時間在早上八點三十到下午七點之間,執行task任務")try:task()except Exception as e:logging.info('執行任務失敗....', e)else:logging.info("當前時間不在早上八點三十到下午七點之間,不執行task任務")logging.info(f'程序睡眠時間{sleep_time}秒')sleep(sleep_time)
linux 服務器啟動腳本
vim start.sh
nohup python3 service_monitor.py > monitor.log &
sh start.sh