-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.py
executable file
·60 lines (45 loc) · 1.46 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# _*_ coding: utf-8 _*_
from bs4 import BeautifulSoup
from datetime import datetime
from config import config
import feedparser
import telebot
import json
import os
def get_timestamp(dt):
return datetime.strptime(dt, '%a, %d %b %Y %H:%M:%S %z').timestamp()
bot = telebot.TeleBot(config.get('telegram-token'))
feeds = list()
if type(config.get('feeds')) == str:
feeds.append(feedparser.parse(config.get('feeds')))
else:
for feed in config.get('feeds'):
feeds.append(feedparser.parse(feed))
new_posts = []
if not os.path.exists('posts.json'):
with open('posts.json', 'w') as f:
json.dump([], f)
f.close()
with open('posts.json') as f:
guids = json.load(f)
f.close()
for feed in feeds:
for entry in feed.entries:
content = entry['description']
post = {}
soup = BeautifulSoup(content, 'html.parser')
if soup.img:
post['image'] = soup.img['src']
post['text'] = '\n'.join(soup.stripped_strings)
post['text'] += '\n\n{}'.format(entry['link'])
post['date'] = get_timestamp(entry['published'])
if entry['guid'] not in guids:
# TODO: strip guid with a regex like /d{4,}\/{?}$/
new_posts.append(post)
guids.append(entry['guid'])
new_posts.sort(key=lambda x: x['date'])
for post in new_posts:
bot.send_message(config.get('channel-id'), post.get('text'))
with open('posts.json', 'w') as f:
json.dump(guids, f)
f.close()