use a dataclass to represent a story, open comments by hitting c

master
Felix Pankratz 1 year ago
parent 6b967dd33e
commit 480f5a87f7

26
hn.py

@ -4,6 +4,16 @@ from bs4 import BeautifulSoup as Soup
import curses
import webbrowser
from dataclasses import dataclass
@dataclass
class Story:
id: int
title: str
link: str
author: str
votes: int
def main(stdscr):
stdscr.clear()
@ -18,18 +28,18 @@ def main(stdscr):
story_url = f'https://hacker-news.firebaseio.com/v0/item/{i}.json'
s = requests.get(story_url).json()
try:
stories.append((s['title'], s['url']))
stories.append(Story(s['id'], s['title'], s['url'], s['by'], s['score']))
except KeyError:
stories.append((s['title'], 'No link' ))
stories.append(Story(s['id'], s['title'], 'No URL', s['by'], s['score']))
# Display list of stories in terminal window with arrow key navigation
current_pos = 0
while True:
stdscr.clear()
stdscr.addstr('\n\nHacker News Top Stories:\n')
for i, (title, link) in enumerate(stories):
for i, story in enumerate(stories):
prefix = '>>> ' if i == current_pos else ' '
text = f'{prefix}{i+1}: {title} ({link})\n'
text = f'{prefix}{i+1}: {story.title} ({story.link})\n'
stdscr.addstr(text)
stdscr.refresh()
@ -44,9 +54,11 @@ def main(stdscr):
current_pos += 1
if current_pos >= len(stories):
current_pos = 0
elif c == ord('c'):
webbrowser.open(f'https://news.ycombinator.com/item?id={stories[current_pos].id}')
elif c == curses.KEY_ENTER or c == 10:
title, link = stories[current_pos]
print(f'\nOpening link: {link}\n')
webbrowser.open(link)
#title, link = stories[current_pos]
#print(f'\nOpening link: {link}\n')
webbrowser.open(stories[current_pos].link)
curses.wrapper(main)

Loading…
Cancel
Save