Overview
Let’s set up a script that sends one of Paul Graham’s top essays to our inbox every Monday, Wednesday, and Friday. Here’s how we’ll tackle it:- Write the script to fetch a random essay from Paul Graham’s most popular essays
- Set up an email to be sent with the essay every Monday/Wednesday/Friday
- Configure the schedule so that it “remembers” which essays have already been sent through
Just show me the code
Just show me the code
See the finished code on Replit.You can even use the Replit URL to run your job, as long as the Repl is running. Make sure to replace
YOUR_EMAIL_ADDRESS
with a valid email address and YOUR_RESEND_API_KEY
with your Resend API key, and then you can run the following in your terminal:Fetching essay data
We’ll use the cheerio library to parse the essay page HTML. Here’s what that function might look like:- Full output: https://pg.reichertjalex.repl.co/api/demo
- As text: https://pg.reichertjalex.repl.co/api/demo?format=text
- As HTML: https://pg.reichertjalex.repl.co/api/demo?format=html
Triggering an email with the essay
First, let’s define a helper function to pick a random essay:Keeping track of alert history
When you create a job on a schedule, the scheduler will pass in some metadata into the body of each request. Included in the metadata is the schedule’sstate
, which can be accessed at req.body.$state
and set or updated in the response.
Let’s modify the API handler to take advantage of $state
:
body
for our job, we can write it like this:
https://yourdomain.com/api/pg
, you can create your scheduled job by running the following script in your terminal with your BOOPER_API_KEY
set, and the url
modified to the appropriate domain: