base_news_data_collation.py 9.2 KB

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