#!/usr/bin/env python3 import json import time import datetime import requests def send_msg_tip(msg_tip): # get the datetime, which is using at a failed situation alert_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # Enterprise WeChat Bot API and the format of body to send hook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef' body = { "msgtype": "text", "text": { "content": msg_tip } } # get the result of API call res = requests.post(hook_url, data=json.dumps(body, ensure_ascii=False).encode('utf-8')) # when failed, log it in /opt/logs/alert.log file if res.status_code != 200: with open('/opt/logs/alert.log', 'a', encoding='utf-8') as alert_log: alert_log.write(alert_datetime + ' >>>> ') alert_log.write('Failed sending message: ') alert_log.write(msg_tip + '\n') # 查询当天的节假日情况 def love_sentence(app_id, app_secret): api_url = f'https://www.mxnzp.com/api/daily_word/recommend?count=10&app_id={app_id}&app_secret={app_secret}' res = requests.get(api_url) res_http_code = res.status_code res_text = json.loads(res.text) res_code = res_text['code'] res_msg = res_text['msg'] if res_http_code != 200 or res_code == 0: msg_tip = res_msg else: res_data = res_text['data'] msg_tip = '' for item in res_data: msg_tip += f'{item["content"]}\n' # print('*' * 20) # print(msg_tip) send_msg_tip(msg_tip) def main(): app_id = "nrsngdkvknqkrwko" app_secret = "SFFmQWo2dnNBRjdNYkVSclZxa2ZvUT09" love_sentence(app_id, app_secret) if __name__ == '__main__': main()