You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
AutoInfo/remind/remind_auto_remind.py

143 lines
4.8 KiB

# -*- coding: utf-8 -*-
import sys
import os
from utils.utils import LoadConfig
sys.path.append(os.path.join(os.path.abspath(__file__).split('AutoInfo')[0] + 'AutoInfo'))
from utils.utils import *
config_json = LoadConfig().load_config()
base_project = LoadConfig().get_base_path()
DB_USER = config_json.get('DB_USER')
DB_PASSWORD = config_json.get('DB_PASSWORD')
DB_IP = config_json.get('DB_IP')
DB_PORT = config_json.get('DB_PORT')
MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
from pymongo import MongoClient
class AutoRemind:
def __init__(self):
self.logs_handle = LogsHandle()
self.now_day = time.strftime('%Y-%m-%d', time.localtime())
self.db = 'ReMind'
self.collection = 'remind'
self.client = MongoClient(MONGO_LINK)
def send_message(self, task_data):
if task_data['retry'] > 0:
# 如果无填时间, 则一直发送,如果有,则判断当前时间, 是否大于设置的时间, 大于则发送,返回 retry-1 的数据, 小于则不发送,返回 task_data 的数据
if task_data['set_time']:
if datetime.now() < datetime.strptime(task_data['set_time'], '%Y-%m-%d %H:%M:%S'):
return None
else:
title = '消息提醒: {} - {}'.format('提醒消息', task_data['title'])
context = '消息内容: {}\n'.format(task_data['context'])
context += '设置时间: {}\n'.format(task_data['set_time'])
context += '推送时间: {}\n'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
# 组装完标题和正文, 准备发送消息
# 推送到 message
GotifyNotifier(title, context, 'news').send_message()
# 推送到 serverchan
ServerChanNotifier(title, context.replace('\n', '\n\n')).send_message()
# 发送后 retry - 1
task_data = {
'title': task_data['title'],
'context': task_data['context'],
'set_time': task_data['set_time'],
'retry': task_data['retry'] - 1
}
# 然后存回数据库
self.write_config(task_data['title'])
else:
return None
def load_config(self):
db = self.client['ReMind']
collection = db['remind']
cursor = collection.find({})
result = []
# 遍历游标并打印每条数据
for document in cursor:
result.append({
'title': document['title'],
'context': document['context'],
'set_time': document['set_time'],
'retry': document['retry']
})
return result
def write_config(self, task_title):
db = self.client['ReMind']
collection = db['remind']
updated_document = collection.find_one_and_update(
{"title": task_title}, # 查询条件
{"$inc": {"retry": -1}}, # 更新操作,retry减1
upsert=False, # 不插入新文档,如果未找到
return_document=True # 返回更新前的文档
)
if updated_document:
print("找到并更新了文档:", updated_document)
else:
print("未找到匹配的文档")
def check_config(self):
db_name = 'ReMind'
if db_name not in self.client.list_database_names():
self.db = self.client[db_name]
else:
self.db = self.client[db_name]
collection_name = 'remind'
if collection_name not in self.db.list_collection_names():
self.collection = self.db[collection_name]
else:
self.collection = self.db[collection_name]
default = {
"title": "消息标题 1 title",
"context": "消息内容 1 context",
"set_time": "9999-12-31 10:00:00",
"retry": 99
}
if not self.collection.find_one({"title": default["title"]}):
self.collection.insert_one(default)
def create_config(self):
db = self.client['ReMind']
collection = db['remind']
create_list = [
{"title": "消息标题 1 title", "context": "消息内容 1 context", "set_time": "9999-12-31 10:00:00",
"retry": 99},
]
for task in create_list:
if not collection.find_one({"title": task["title"]}):
collection.insert_one(task)
def main(self):
self.check_config()
config_list = self.load_config()
self.create_config()
for task_data in config_list:
result_task = self.send_message(task_data)
if __name__ == '__main__':
AutoRemind().main()
print('消息发送完成,程序退出!')