summaryrefslogtreecommitdiff
path: root/hnnews.py
blob: 68e333a25b3f8e24c687b9083ef860601609f78d (plain)
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
import requests
baseurl = "https://hacker-news.firebaseio.com"

def _get_topnews_list():
    try:
        resp = requests.get(f'{baseurl}/v0/topstories.json')
        return resp.json()
    except:
        print("error fetching top news list, skipping")
        return []

def get_topnews(limit):
    result = []
    list = _get_topnews_list()
    if len(list) < limit:
        limit = len(list)
    for story_id in list[:limit]:
        try:
            url = f'{baseurl}/v0/item/{story_id}.json'
            resp = requests.get(url)
            story = resp.json()
            if story["type"] != "story":
                continue
            if "url" not in story.keys():
                # print("using alt url")
                story["url"] = f'https://news.ycombinator.com/item?id={story_id}'
            result.append(story)
        except Exception as e:
            print("error fetching story skipping ", e)
    return result

def get_one_item(id):
    try:
        url = f'{baseurl}/v0/item/{story_id}.json'
        resp = requests.get(url)
        story = resp.json()
        if story["type"] != "story":
            return None
        if "url" not in story.keys():
            # print("using alt url")
            story["url"] = f'https://news.ycombinator.com/item?id={story_id}'
        return story
    except Exception as e:
        print("error fetching story skipping ", e)
        return None