auto_remind.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # -*- coding: utf-8 -*-
  2. import time
  3. import json
  4. import sys
  5. import os
  6. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto')[0] + 'auto'))
  7. from datetime import datetime
  8. from utils.utils_send_gotify import GotifyNotifier
  9. from utils.utils_send_serverchan import ServerChanNotifier
  10. from base.base_load_config import load_config, get_base_path
  11. config_json = load_config()
  12. base_project = get_base_path()
  13. DB_USER = config_json.get('DB_USER')
  14. DB_PASSWORD = config_json.get('DB_PASSWORD')
  15. DB_IP = config_json.get('DB_IP')
  16. DB_PORT = config_json.get('DB_PORT')
  17. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  18. from utils.utils_logs_handle import LogsHandle
  19. from pymongo import MongoClient
  20. class AutoRemind:
  21. def __init__(self):
  22. self.logs_handle = LogsHandle()
  23. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  24. self.db = 'ReMind'
  25. self.collection = 'remind'
  26. self.client = MongoClient(MONGO_LINK)
  27. def send_message(self, task_data):
  28. if task_data['retry'] > 0:
  29. # 如果无填时间, 则一直发送,如果有,则判断当前时间, 是否大于设置的时间, 大于则发送,返回 retry-1 的数据, 小于则不发送,返回 task_data 的数据
  30. if task_data['set_time']:
  31. if datetime.now() < datetime.strptime(task_data['set_time'], '%Y-%m-%d %H:%M:%S'):
  32. return None
  33. else:
  34. title = '消息提醒: {} - {}'.format('提醒消息', task_data['title'])
  35. context = '消息内容: {}\n'.format(task_data['context'])
  36. context += '设置时间: {}\n'.format(task_data['set_time'])
  37. context += '推送时间: {}\n'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
  38. # 组装完标题和正文, 准备发送消息
  39. # 推送到 message
  40. GotifyNotifier(title, context).send_message()
  41. # 推送到 serverchan
  42. ServerChanNotifier(title, context.replace('\n', '\n\n')).send_message()
  43. # 发送后 retry - 1
  44. task_data = {
  45. 'title': task_data['title'],
  46. 'context': task_data['context'],
  47. 'set_time': task_data['set_time'],
  48. 'retry': task_data['retry'] - 1
  49. }
  50. # 然后存回数据库
  51. self.write_config(task_data['title'])
  52. else:
  53. return None
  54. def load_config(self):
  55. db = self.client['ReMind']
  56. collection = db['remind']
  57. cursor = collection.find({})
  58. result = []
  59. # 遍历游标并打印每条数据
  60. for document in cursor:
  61. result.append({
  62. 'title': document['title'],
  63. 'context': document['context'],
  64. 'set_time': document['set_time'],
  65. 'retry': document['retry']
  66. })
  67. return result
  68. def write_config(self, task_title):
  69. db = self.client['ReMind']
  70. collection = db['remind']
  71. updated_document = collection.find_one_and_update(
  72. {"title": task_title}, # 查询条件
  73. {"$inc": {"retry": -1}}, # 更新操作,retry减1
  74. upsert=False, # 不插入新文档,如果未找到
  75. return_document=True # 返回更新前的文档
  76. )
  77. if updated_document:
  78. print("找到并更新了文档:", updated_document)
  79. else:
  80. print("未找到匹配的文档")
  81. def check_config(self):
  82. db_name = 'ReMind'
  83. if db_name not in self.client.list_database_names():
  84. self.db = self.client[db_name]
  85. else:
  86. self.db = self.client[db_name]
  87. collection_name = 'remind'
  88. if collection_name not in self.db.list_collection_names():
  89. self.collection = self.db[collection_name]
  90. else:
  91. self.collection = self.db[collection_name]
  92. default = {
  93. "title": "消息标题 1 title",
  94. "context": "消息内容 1 context",
  95. "set_time": "9999-12-31 10:00:00",
  96. "retry": 99
  97. }
  98. if not self.collection.find_one({"title": default["title"]}):
  99. self.collection.insert_one(default)
  100. def create_config(self):
  101. db = self.client['ReMind']
  102. collection = db['remind']
  103. create_list = [
  104. {"title": "消息标题 1 title", "context": "消息内容 1 context", "set_time": "9999-12-31 10:00:00",
  105. "retry": 99},
  106. ]
  107. for task in create_list:
  108. if not collection.find_one({"title": task["title"]}):
  109. collection.insert_one(task)
  110. def main(self):
  111. self.check_config()
  112. config_list = self.load_config()
  113. self.create_config()
  114. for task_data in config_list:
  115. result_task = self.send_message(task_data)
  116. if __name__ == '__main__':
  117. AutoRemind().main()
  118. print('消息发送完成,程序退出!')