base_news_data_collation.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. '''
  2. 每日从 mongo 数据库, 做新闻汇总,发送到邮箱
  3. '''
  4. import os
  5. import sys
  6. sys.path.append(os.path.join(os.path.abspath(__file__).split('AutoInfo')[0] + 'AutoInfo'))
  7. from pymongo import MongoClient
  8. from datetime import timedelta
  9. import re
  10. from utils.utils import *
  11. config_json = LoadConfig().load_config()
  12. base_project = LoadConfig().get_base_path()
  13. PROJECT_NAME = config_json.get('PROJECT_NAME')
  14. DB_USER = config_json.get('DB_USER')
  15. DB_PASSWORD = config_json.get('DB_PASSWORD')
  16. DB_IP = config_json.get('DB_IP')
  17. DB_PORT = config_json.get('DB_PORT')
  18. MAIL_HOST = config_json.get('MAIL_HOST')
  19. MAIL_USER = config_json.get('MAIL_USER')
  20. MAIL_PASS = config_json.get('MAIL_PASS')
  21. MAIL_SENDER = config_json.get('MAIL_SENDER')
  22. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  23. DB_NAME = config_json.get('DB_NAME') # 确保配置文件中有这个键
  24. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'.format(**config_json)
  25. now_day = datetime.now().strftime('%Y-%m-%d') # 获取今天的日期
  26. filter_days = config_json.get('FILTER_DAYS')
  27. filter_keys = config_json.get('FILTER_KEYS')
  28. filter_switch = True
  29. class NewsDataCollation(object):
  30. def __init__(self):
  31. # 第三方 SMTP 服务
  32. self.mail_host = MAIL_HOST # 设置服务器
  33. self.mail_user = MAIL_USER # 用户名
  34. self.mail_pass = MAIL_PASS # 口令
  35. self.sender = MAIL_SENDER
  36. self.receivers = [MAIL_RECEIVERS]
  37. self.processed_data = []
  38. def load_data(self):
  39. processed_data = []
  40. # 读取数据
  41. print('程序正在读取数据')
  42. client = MongoClient(MONGO_LINK)
  43. db = client['NEWS']
  44. # 根据 self.days 获取日期范围
  45. start_date = (datetime.now() - timedelta(days=filter_days - 1)).strftime('%Y-%m-%d')
  46. end_date = datetime.now().strftime('%Y-%m-%d')
  47. # 构造查询条件,匹配日期范围内的日期
  48. query = {
  49. "create_datetime": {
  50. "$regex": f"^{start_date}|{end_date}",
  51. "$options": "i" # 使用不区分大小写的匹配
  52. }
  53. }
  54. # 遍历数据库中的所有集合
  55. for collection_name in db.list_collection_names():
  56. print(collection_name)
  57. collection = db[collection_name]
  58. cursor = collection.find(query)
  59. for document in cursor:
  60. if not document.get('title'):
  61. continue
  62. # 检查 'repush_times' 字段是否存在,如果不存在则默认为 5
  63. repush_times = document.get('repush_times', 5)
  64. # 减少 repush_times 的值
  65. new_repush_times = repush_times - 1
  66. # 更新数据库中的 repush_times 字段
  67. collection.update_one(
  68. {"_id": document['_id']}, # 假设文档中有 _id 字段作为唯一标识
  69. {"$set": {"repush_times": new_repush_times}}
  70. )
  71. data = self.process_data(document)
  72. if data:
  73. processed_data.append(data)
  74. # 关闭MongoDB连接
  75. client.close()
  76. return processed_data
  77. def process_data(self, document):
  78. # 处理数据
  79. data = {
  80. "title": document.get('title') or '',
  81. "context": document.get('context') or '',
  82. "source_url": document.get('source_url') or '',
  83. 'link': document.get('link') or '',
  84. "article_type": document.get('article_type') or '',
  85. "article_source": document.get('article_source') or '',
  86. "img_url": document.get('img_url') or '',
  87. 'keyword': document.get('keyword') or '',
  88. "posted_date": document.get('posted_date') or '',
  89. "create_time": document.get('create_time') or '',
  90. "create_datetime": document.get('create_datetime') or '',
  91. "repush_times": document.get('repush_times', 5) - 1
  92. }
  93. data['title'] = self.clean_string(data['title'], 'title')
  94. data['context'] = self.clean_string(data['context'], 'context')
  95. return data
  96. def clean_string(self, input_string, text_type):
  97. # 清除 title 和 context 中的换行符和制表符
  98. if not isinstance(input_string, str):
  99. return ''
  100. # 清除所有空白字符(包括空格、制表符、换行符等)
  101. cleaned_string = re.sub(r'\s+', '', input_string)
  102. if len(cleaned_string) > 100:
  103. cleaned_string = cleaned_string[:100] + '...'
  104. if text_type == 'context':
  105. pass
  106. return cleaned_string
  107. def send_email(self, processed_data):
  108. # 发送邮件
  109. print('准备发送邮件')
  110. subject = '新闻汇总sub'
  111. title = '新闻汇总title'
  112. text = '********************************************************\n'
  113. for data in processed_data:
  114. text += '标题: {}\n'.format(data['title'])
  115. text += '正文: {}\n'.format(data['context'])
  116. text += '文章地址: {}\n'.format(data['link'])
  117. text += '类型: {}\n'.format(data['article_type'])
  118. text += '板块: {}\n'.format(data['article_source'])
  119. text += '文章时间: {}\n'.format(data['posted_date'])
  120. text += '获取时间: {}\n'.format(data['create_datetime'])
  121. text += '********************************************************\n\n'
  122. message = MIMEText(text, 'plain', 'utf-8')
  123. message['From'] = Header(title, 'utf-8')
  124. message['To'] = Header("auto", 'utf-8')
  125. message['Subject'] = Header(subject, 'utf-8')
  126. try:
  127. smtpObj = smtplib.SMTP_SSL(self.mail_host)
  128. smtpObj.login(self.mail_user, self.mail_pass)
  129. smtpObj.sendmail(self.sender, self.receivers, message.as_string())
  130. print("邮件发送成功")
  131. except smtplib.SMTPException as e:
  132. print("Error: 无法发送邮件", e)
  133. def send_email_with_keyword(self, series, keys, processed_data):
  134. process_send_data = {}
  135. keys = keys.split('|')
  136. have_data_keys = []
  137. for key in keys:
  138. # print(f'通过关键字: {key} 过滤') # 用来调试 key 是否正确
  139. for data in processed_data:
  140. if key in data['title'] or key in data['context']:
  141. # 如果数据里面无 keyword, 用当前 key 替换一下
  142. if not data.get('keyword'):
  143. data['keyword'] = key
  144. if series not in process_send_data:
  145. process_send_data[series] = [data]
  146. else:
  147. process_send_data[series].append(data)
  148. # 储存一下有数据的 key, 输出用
  149. have_data_keys.append(key)
  150. if process_send_data:
  151. print('{}系列, 以下关键字有数据\n{}'.format(series, list(set(have_data_keys))))
  152. # 发送邮件
  153. print('程序正在准备发送邮件的数据')
  154. for key in process_send_data:
  155. subject = '新闻汇总sub - {}'.format(series)
  156. title = '新闻汇总title - {}'.format(series)
  157. text = '********************************************************\n'
  158. for data in process_send_data[key]:
  159. text += '标题: {}\n'.format(data['title'])
  160. text += '正文: {}\n'.format(data['context'])
  161. text += '文章地址: {}\n'.format(data['link'])
  162. text += '类型: {}\n'.format(data['article_type'])
  163. text += '板块: {}\n'.format(data['article_source'])
  164. text += '关键词: {}\n'.format(key)
  165. text += '文章时间: {}\n'.format(data['posted_date'])
  166. text += '获取时间: {}\n'.format(data['create_datetime'])
  167. text += '********************************************************\n\n'
  168. message = MIMEText(text, 'plain', 'utf-8')
  169. message['From'] = Header(title, 'utf-8')
  170. message['To'] = Header("auto", 'utf-8')
  171. message['Subject'] = Header(subject, 'utf-8')
  172. try:
  173. smtpObj = smtplib.SMTP_SSL(self.mail_host)
  174. smtpObj.login(self.mail_user, self.mail_pass)
  175. smtpObj.sendmail(self.sender, self.receivers, message.as_string())
  176. print("关键字: {} 的邮件发送成功".format(series))
  177. except smtplib.SMTPException as e:
  178. print("Error: 无法发送邮件", e)
  179. def main(self):
  180. # 加载指定天数的所有数据
  181. processed_data = self.load_data()
  182. # 如果无数据, 则退出
  183. if not processed_data:
  184. print("没有找到任何数据")
  185. exit(0)
  186. # 发送一次所有数据的邮件
  187. # self.send_email(processed_data)
  188. # # 这里是通过关键词过滤然后再发送邮件
  189. if filter_switch and filter_keys:
  190. for series, keys in filter_keys.items():
  191. self.send_email_with_keyword(series, keys, processed_data)
  192. if __name__ == '__main__':
  193. NewsDataCollation().main()