Overview

Let’s set up a script that alerts us every hour of new posts on the front page of Hacker News that have exceeded a certain point threshold.

Here’s how we’ll tackle it:

  1. Write the script to fetch all front page posts with a minimum upvote score
  2. Set up a notification to be sent to Discord whenever a new post is found
  3. Configure the schedule so that it “remembers” which posts have already been sent through

Fetching top stories from HN

We’ll use the Hacker News API endpoints to fetch the top page stories. Here’s what that function might look like:

It’s basically an N+1 query, but no big deal. If we limit the results to the first page (i.e. the first 30 posts), the request is generally fast enough.

Triggering a Discord alert when new posts are found

First, let’s define two helper functions:

  • format: formats story data into Discord markdown
  • notify: sends an alert to Discord via webhook URL

Now, the simplest thing we can do is just send an alert to Discord whenever we find posts that meet the minimum score requirement set in the request body.

Here we handle that in a NextJS API endpoint:

This is fine if we run the script every hour or two, and don’t mind seeing repeated links. But what if we want to avoid sending duplicates?

Keeping track of alert history

There are two ways we can keep track of which posts have been sent out already.

When you create a job on a schedule, the scheduler will pass in some metadata into the body of each request. Included in that metadata is the response from the previous run, which can be seen at req.body.$previous.

Also included in the metadata is the schedule’s state, which can be accessed at req.body.$state and set or updated in the response.