scripts/alert/todo_alert.py
2023-06-05 23:04:30 +08:00

96 lines
3.3 KiB
Python

import requests
import json
import time
import os
def send_alert_msg(alert_msg):
"""
send warning messages to phone via Enterprise WeChat Bot API
:param alert_msg: messages needed to be sent
:return: None
"""
# 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": alert_msg
}
}
# 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(alert_msg + '\n')
def main():
"""
process the file /opt/logs/TODO/todo.txt file, get the items which is to be done within 2 months
:return: None
"""
# run tt ls in advance, to generate correct todo.txt file
os.system("bash /opt/scripts/todo/todo.sh ls > /dev/null")
# initialize alert_msg with empty string
alert_msg = ''
# specify range to be alerted
alert_day = list(range(61))
# pretty index for output
alert_index = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}
# prepare a dict with specified format and contend, to receive valid items
alert_tasks = dict().fromkeys(alert_day, None)
for key in alert_tasks.keys():
alert_tasks[key] = []
with open('/opt/logs/TODO/todo.txt', mode='r', encoding='utf-8') as todo_txt:
# process every line of the file, and get the left time of the task
for line in todo_txt.readlines():
items = line.strip().split('|')
time_left = int(float(items[2].strip().split(':')[1]))
content = items[1].strip() + ' | ' + items[3].strip()
# when the left time smaller than 2 months, put the task needed to be done in the dict
if time_left in alert_day:
alert_tasks[time_left].append(content)
# determine every day to see if there are tasks not done
for time_left, task in alert_tasks.items():
# if no task of some day, then skip it
if task == []:
continue
# pretty and accurate word's format
sp_day = 'days' if time_left > 1 else 'day'
sp_task = 'tasks' if len(task) > 1 else 'task'
# different output of alert message tips
if time_left == 0:
alert_msg += f'Today, you NEED to finish the following {sp_task}:\n'
else:
alert_msg += f'{time_left} {sp_day} left to finish the following {sp_task}:\n'
# for every specified day, output all tasks needing to be done
count = 1
for assignment in task:
alert_msg += f' {alert_index[count]}. {assignment}\n'
count += 1
alert_msg += '\n'
alert_msg += 'So, hurry up!! Go get things done!!'
send_alert_msg(alert_msg)
if __name__ == '__main__':
main()