[init] initial commit
This commit is contained in:
BIN
alert/__pycache__/calendar.cpython-39.pyc
Normal file
BIN
alert/__pycache__/calendar.cpython-39.pyc
Normal file
Binary file not shown.
72
alert/calendar_tips.py
Normal file
72
alert/calendar_tips.py
Normal file
@ -0,0 +1,72 @@
|
||||
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 holiday_today(app_id, app_secret):
|
||||
week_index = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '天', }
|
||||
today = datetime.date.today()
|
||||
today_fmt = str(today).replace('-', '')
|
||||
api_url = f'https://www.mxnzp.com/api/holiday/single/{today_fmt}?ignoreHoliday=false&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_weekday = res_text['data']['weekDay']
|
||||
res_yeartips = res_text['data']['yearTips']
|
||||
res_chinesezodiac = res_text['data']['chineseZodiac']
|
||||
res_typedes = res_text['data']['typeDes']
|
||||
res_type = res_text['data']['type']
|
||||
res_dayofyear = res_text['data']['dayOfYear']
|
||||
res_weekofyear = res_text['data']['weekOfYear']
|
||||
res_constellation = res_text['data']['constellation']
|
||||
msg_tip = f'{today},{res_yeartips}{res_chinesezodiac}年,星期{week_index[res_weekday]},{res_constellation}。本周是今年的第{res_weekofyear}周,今天是今年的第{res_dayofyear}天,是{res_typedes},'
|
||||
if res_type == 2 or res_type == 1:
|
||||
msg_tip += f"请好好休息,享用美好的一天。"
|
||||
else:
|
||||
msg_tip += f"请努力工作,保持良好的心态。"
|
||||
|
||||
send_msg_tip(msg_tip)
|
||||
|
||||
def main():
|
||||
app_id = "nrsngdkvknqkrwko"
|
||||
app_secret = "SFFmQWo2dnNBRjdNYkVSclZxa2ZvUT09"
|
||||
holiday_today(app_id, app_secret)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
|
||||
|
||||
|
12
alert/docker_alarm.sh
Normal file
12
alert/docker_alarm.sh
Normal file
@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
|
||||
docker ps -a --format "table {{.Names}}\t{{.Status}}" > /opt/logs/docker_status.log
|
||||
while read line; do
|
||||
echo $line | grep -q 'Exited'
|
||||
if [[ $? -eq 0 ]]; then
|
||||
name=`echo $line | awk '{print $1}'`
|
||||
alarm="Docker Alarm - $name:\nContainer $name has been off line, please check ASAP."
|
||||
bash /opt/scripts/alert/sendmsg.sh "$alarm"
|
||||
fi
|
||||
done < /opt/logs/docker_status.log
|
||||
|
64
alert/love_words.py
Normal file
64
alert/love_words.py
Normal file
@ -0,0 +1,64 @@
|
||||
#!/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()
|
||||
|
||||
|
120
alert/poem_send.py
Normal file
120
alert/poem_send.py
Normal file
@ -0,0 +1,120 @@
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import sys
|
||||
|
||||
|
||||
def send_alert_msg(alert_msg):
|
||||
"""
|
||||
sending messages via Enterprise WeChat Bot with the content of a poem from Jinrishici API.
|
||||
今日诗词:名句
|
||||
|
||||
【title】-【author】-【dynasty】
|
||||
poem of complete
|
||||
:param alert_msg:content with a specified format
|
||||
: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 poem():
|
||||
"""
|
||||
get the poem with Jinrishici API
|
||||
:return: None
|
||||
"""
|
||||
# specify token in headers
|
||||
headers = {'X-User-Token': 'dNigXSFtjhLbP5nf49piUPzmD7NoNHVz'}
|
||||
api_url = 'https://v2.jinrishici.com/sentence'
|
||||
# will try for 3 times, in case there are failed situations to get the poem
|
||||
for i in range(3):
|
||||
res = requests.get(api_url, headers=headers)
|
||||
# translate json data to dict format
|
||||
dict_substance = json.loads(res.content)
|
||||
|
||||
# when failed to get the content, try again
|
||||
if res.status_code != 200 or dict_substance['status'] != 'success':
|
||||
continue
|
||||
|
||||
# put necessary content to specific variables
|
||||
# print(dict_substance)
|
||||
poem_content = dict_substance['data']['content']
|
||||
poem_title = dict_substance['data']['origin']['title']
|
||||
poem_dynasty = dict_substance['data']['origin']['dynasty']
|
||||
poem_author = dict_substance['data']['origin']['author']
|
||||
poem_content_all = dict_substance['data']['origin']['content']
|
||||
poem_translation = dict_substance['data']['origin']['translate']
|
||||
# put poem translation in to the file /opt/scripts/alert/poem_trans.txt, if exists
|
||||
with open('/opt/scripts/alert/poem_trans.txt', 'w', encoding='utf-8') as obj_poem_trans:
|
||||
if poem_translation:
|
||||
for item in poem_translation:
|
||||
obj_poem_trans.write(item + '\n')
|
||||
# if the translation part does not exist, put a '' into the file
|
||||
else:
|
||||
obj_poem_trans.write('')
|
||||
|
||||
# create the format of content which is intended to be send via EWB, aka Enterprise Wechat Bot
|
||||
alert_msg = f"今日诗词:{poem_content}\n\n"
|
||||
alert_msg += f"【{poem_title}】-【{poem_author}】-【{poem_dynasty}】\n"
|
||||
for line in poem_content_all:
|
||||
alert_msg += f"{line}\n"
|
||||
|
||||
# when successfully get the needed content, jump out of the for-loop
|
||||
break
|
||||
# after 3 times re-tries, still cannot get the content, then send the following warning message
|
||||
else:
|
||||
alert_msg = '当前无法获取今日诗词,请手动检查如下请求返回是否正确!\n'
|
||||
alert_msg += 'curl "https://v2.jinrishici.com/sentence" -H "X-User-Token:dNigXSFtjhLbP5nf49piUPzmD7NoNHVz"'
|
||||
|
||||
# send it
|
||||
send_alert_msg(alert_msg)
|
||||
|
||||
|
||||
def trans():
|
||||
"""
|
||||
send the translation of the poem which is showed this morning, if exists
|
||||
:return: None
|
||||
"""
|
||||
with open('/opt/scripts/alert/poem_trans.txt', 'r', encoding='utf-8') as obj_poem_trans:
|
||||
alert_msg = obj_poem_trans.read()
|
||||
# print(alert_msg)
|
||||
if alert_msg:
|
||||
alert_msg = f'今日诗词的译文:\n{alert_msg}'
|
||||
send_alert_msg(alert_msg)
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
do the actions according to different parameters
|
||||
:return: None
|
||||
"""
|
||||
if sys.argv[1] == 'poem':
|
||||
poem()
|
||||
elif sys.argv[1] == 'trans':
|
||||
trans()
|
||||
else:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
0
alert/poem_trans.txt
Normal file
0
alert/poem_trans.txt
Normal file
16
alert/sendmsg.sh
Normal file
16
alert/sendmsg.sh
Normal file
@ -0,0 +1,16 @@
|
||||
#!/bin/bash
|
||||
|
||||
alarm="$1"
|
||||
|
||||
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '
|
||||
{
|
||||
"msgtype": "text",
|
||||
"text": {
|
||||
"content": "'"$alarm"'"
|
||||
}
|
||||
}' > /dev/null 2>&1
|
||||
|
||||
|
||||
|
95
alert/todo_alert.py
Normal file
95
alert/todo_alert.py
Normal file
@ -0,0 +1,95 @@
|
||||
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()
|
||||
|
98
alert/weather_tips.py
Normal file
98
alert/weather_tips.py
Normal file
@ -0,0 +1,98 @@
|
||||
import sys
|
||||
import json
|
||||
import datetime
|
||||
import requests
|
||||
import time
|
||||
|
||||
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 weather_forcast(app_id, app_secret, city):
|
||||
api_url = f"https://www.mxnzp.com/api/weather/forecast/{city}?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']
|
||||
# print(res.text)
|
||||
if res_http_code != 200 or res_code == 0:
|
||||
print(f"接口查询失败:{res_msg}")
|
||||
else:
|
||||
# print(res_text['data']['forecasts'])
|
||||
today = datetime.date.today()
|
||||
hour = datetime.datetime.now().hour
|
||||
msg_tip = f"{today} {hour}时,查询到{city}最近四天的天气情况如下:\n"
|
||||
msg_tip += ('*' * 30 + '\n')
|
||||
when = {1: '今天', 2: '明天', 3: '后天', 4: '大后天', }
|
||||
week_index = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '天', }
|
||||
count = 1
|
||||
for item in res_text['data']['forecasts']:
|
||||
item_date = item['date']
|
||||
item_dayofweek = week_index[int(item['dayOfWeek'])]
|
||||
if item['dayWeather'] == item['nightWeather']:
|
||||
msg_tip += f"{when[count]}({item_date} 星期{item_dayofweek})全天天气是{item['dayWeather']},"
|
||||
else:
|
||||
msg_tip += f"{when[count]}({item_date} 星期{item_dayofweek})白天天气是{item['dayWeather']},夜间会转为{item['nightWeather']},"
|
||||
|
||||
msg_tip += f"最高温{item['dayTemp']},最低温{item['nightTemp']},"
|
||||
|
||||
difftemp = int(item['dayTemp'].removesuffix('℃')) - int(item['nightTemp'].removesuffix('℃'))
|
||||
if difftemp > 10:
|
||||
msg_tip += f"昼夜温差{difftemp}℃,请注意增减衣物,切勿感冒;"
|
||||
|
||||
if item['dayWindDirection'] == item['nightWindDirection']:
|
||||
msg_tip += f"{when[count]}全天是{item['dayWindDirection']}风,"
|
||||
if item['dayWindPower'] == item['nightWindPower']:
|
||||
msg_tip += f"风力为{item['dayWindPower']}。\n"
|
||||
else:
|
||||
msg_tip += f"白天风力为{item['dayWindPower']},夜间风力为{item['nightWindPower']}。\n"
|
||||
else:
|
||||
msg_tip += f"{when[count]}白天是{item['dayWeather']}风,夜间会转为{item['nightWeather']}风,"
|
||||
if item['dayWindPower'] == item['nightWindPower']:
|
||||
msg_tip += f"风力为{item['dayWindPower']}。\n"
|
||||
else:
|
||||
msg_tip += f"白天风力为{item['dayWindPower']},夜间风力为{item['nightWindPower']}。\n"
|
||||
count += 1
|
||||
msg_tip += ('*' * 30 + '\n')
|
||||
|
||||
# print(msg_tip)
|
||||
send_msg_tip(msg_tip)
|
||||
|
||||
|
||||
def main():
|
||||
app_id = "nrsngdkvknqkrwko"
|
||||
app_secret = "SFFmQWo2dnNBRjdNYkVSclZxa2ZvUT09"
|
||||
# holiday_today(app_id, app_secret)
|
||||
# ip_self(app_id, app_secret)
|
||||
try:
|
||||
city = sys.argv[1]
|
||||
except Exception as Err:
|
||||
print(f"Error Desc: {Err}. Maybe you need to supply correct city next time.")
|
||||
exit(2)
|
||||
|
||||
weather_forcast(app_id, app_secret, city)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
Reference in New Issue
Block a user