remind_auto_remind.py 4.8 KB

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