From 480f5a87f78a14e02ccdf8bbfb171ca6fa662e63 Mon Sep 17 00:00:00 2001 From: Felix Pankratz Date: Mon, 28 Aug 2023 21:49:06 +0200 Subject: [PATCH] use a dataclass to represent a story, open comments by hitting c --- hn.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/hn.py b/hn.py index a260670..80b0e3d 100644 --- a/hn.py +++ b/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)