Passed
Push — master ( ac1a25...20c679 )
by
unknown
02:10
created

api_rssbot   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 54
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A RssRobot.remove_old_history() 0 6 1
B RssRobot.main() 0 26 6
1
# -*- encoding: utf-8 -*-
2
"""
3
cron: */15 6-22/2 * * *
4
new Env('RSS 订阅推送');
5
"""
6
7
from datetime import datetime, timedelta
8
9
import feedparser
10
11
from notify_mtr import send
12
from utils_models import History, Rss, db
13
14
15
class RssRobot:
16
    def main(self):
17
        self.remove_old_history()
18
        rss_list = Rss.select()
19
        msg = ""
20
        post_url_list = [
21
            rss_history.url
22
            for rss_history in History.select().where(
23
                History.publish_at == datetime.today().strftime("%Y-%m-%d")
24
            )
25
        ]
26
        for rss in rss_list:
27
            rss_history_list = []
28
            feed = feedparser.parse(rss.feed)
29
            for entry in feed.entries:
30
                if entry.link not in post_url_list and \
31
                        (
32
                                datetime.now() -
33
                                datetime.strptime(entry['published'].strip().split("T")[0].split(" ")[0], "%Y-%m-%d")
34
                        ).days < 7:
35
                    msg = msg + f"{entry.title}\n{entry.link}\n\n"
36
                    rss_history_list.append(History(url=entry.link))
37
38
            with db.atomic():
39
                History.bulk_create(rss_history_list, batch_size=10)
40
41
        return msg
42
43
    def remove_old_history(self):
44
        # 只保留最近一周的记录
45
        week_date_range = datetime.now() + timedelta(days=-7)
46
        History.delete().where(
47
            History.publish_at < week_date_range.strftime("%Y-%m-%d")
48
        ).execute()
49
50
51
if __name__ == "__main__":
52
    res = RssRobot().main()
53
    send("RSS 订阅", res)
54