-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
118 lines (99 loc) · 4.09 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import time
import datetime
import timeago
from apis.hn import get_top_stories, get_story_details
from apis.telegram import send_message, get_last_hundred_messages
from summarizer import summarize_story
from cachetools import TTLCache
from utils import extract_hn_ids
# Initialize an in-memory cache with a TTL of 3 days
cache = TTLCache(maxsize=300, ttl=60 * 60 * 24 * 14)
SCORE_THRESHOLD = 150
FOUR_HOURS = datetime.timedelta(hours=4)
TWO_DAYS = datetime.timedelta(days=2)
def read_message_ids_from_file():
try:
with open('message_ids.txt', 'r') as f:
ids = [int(line.strip()) for line in f.readlines()]
for hn_id in ids:
cache[hn_id] = True
print("Message IDs have been read from message_ids.txt and cached.")
except Exception as e:
print(f"Error reading message IDs from file: {e}")
def main():
read_message_ids_from_file()
while True:
start_time = time.time()
try:
top_stories = get_top_stories() # Fetch top stories
print(f"{len(top_stories)} top stories.")
except Exception as e:
print(f"Error fetching top stories: {e}")
time.sleep(600)
continue
count = 0
for story_id in top_stories:
count += 1
print(f"{count}. {story_id} | ", end="")
# Check cache
if story_id in cache:
print(f"cached skipping. ")
continue
try:
# Get story details
story = get_story_details(story_id)
print(
f"score {story.get('score')} | {story.get('title')} | ", end="")
if story.get('score') < SCORE_THRESHOLD:
print("low score. ")
continue
except Exception as e:
print(f"Error getting story details for {story_id}: {e}")
continue
try:
# Summarize story
summary = summarize_story(story.get('url'))
print('sumz-ed | ', end="")
except Exception as e:
print(f'Error summarizing story {story_id}: {e}')
continue
try:
# Prepare message
current_time = datetime.datetime.now()
published_time = datetime.datetime.fromtimestamp(
story.get('time'))
ago = timeago.format(current_time, published_time)
status_emoji = ''
delta = current_time - published_time
if delta <= FOUR_HOURS:
status_emoji = '🔥 '
elif delta >= TWO_DAYS:
status_emoji = '❄️ '
message = f"<b>{story.get('title')}</b> ({status_emoji}Score: {story.get('score')}+ {ago})\n\n<b>Read more: </b><a href='{story.get('url')}'>{story.get('url')}</a>\n<b>Comments: </b><a href='https://news.ycombinator.com/item?id={story_id}'>https://news.ycombinator.com/item?id={story_id}</a> \n\n<b>Brief</b>: {summary}"
buttons = []
comments_count = story.get('descendants', 0)
buttons.append({
'text': f"{comments_count}+ Comments",
'url': f"https://news.ycombinator.com/item?id={story_id}"
})
buttons.append({
'text': 'Read',
'url': f"{story.get('url')}"
})
# Send message to Telegram
send_message(message, reply_markup={
'inline_keyboard': [buttons]})
print("sent.", end="")
except Exception as e:
print(
f"Error preparing/sending message for story {story_id}: {e}")
continue
# Cache the story ID
cache[story_id] = True
end_time = time.time()
print("Finished one round in %s seconds. Sleeping for 10 min." %
(end_time - start_time))
# Sleep for 10 min
time.sleep(600)
if __name__ == "__main__":
main()