Current state: I'm currently using next.js to build a web app. I would like this web app to also post to my Twitter account. I've already created a developer account on Twitter and an API in nextjs. Calling the api will trigger the post request, and it will create a post on my Twitter account since all the authentication is set up.
What I would like: I would like my account to post a tweet every 24 hours, so let's say every day at 5 in the morning (my local time). I would need this tweet to be posted, also when nobody is requesting the website. Unfortunately, I didn't figure out how to set this up yet. Any help is appreciated.
I've been thinking about using getStaticProps with the revalidate function from nextjs but I realized that when nobody is requesting the webpage it still won't work. Even when the code is executed server-side.
This is what the code in my API currently looks like:
import type { NextApiRequest, NextApiResponse } from 'next'
import Twitter from 'twitter'
export default async function postTweet(req: NextApiRequest, res: NextApiResponse){
const client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY ?? "",
consumer_secret: process.env.TWITTER_CONSUMER_SECRET ?? "",
access_token_key: process.env.ACCESS_TOKEN_KEY ?? "",
access_token_secret: process.env.ACCESS_TOKEN_SECRET ?? "",
});
client.post(
'statuses/update',
{ status: message + `(${currentDate})` },
function (error, tweet, response) {
if (error) throw error;
// console.log(tweet); // Tweet body.
// console.log(response); // Raw response object.
}
);
}
Any ideas of how I could realize this are welcome!
it's really good question.
You can achieve this by setting a CRON JOB. It's a way to tell server to run a specific task with an time interval or at a specific time of a day/week/month etc.
If you want to use GitHub Actions, it has a CRON JOB feature
you can read more here https://vercel.com/docs/concepts/solutions/cron-jobs
You can generate cron expression https://crontab.cronhub.io/
as eg: for everyday at 5AM : 0 5 * * *
name: tweet-at-morning
on:
schedule:
- cron: '0 5 * * *'
jobs:
cron:
runs-on: ubuntu-latest
steps:
- name: Call our API route
run: |
curl --request POST \
--url 'https://yoursite.com/api/cron' \
--header 'Authorization: Bearer ${{ secrets.API_SECRET_KEY }}'
Otherwise, you can use a node library to make a job queue. I found Bull.js https://github.com/OptimalBits/bull this library as easiest and reliable one for creating job server.