Scheduled Facebook posts via Bash

I was looking for an easy way to create scheduled posts on facebook. Though I didn’t find a fully automated way I was able to create a process that only needs manual steps every 60 days.

With the app created on facebook developer pages I first need the clientId (appId) and clientSecret (appSecret).

The first manual step is to login an grant permission to the app by copying an URL to the browser (don’t forget to replace the clientId):

https://www.facebook.com/v17.0/dialog/oauth?client_id=<CLIENT_ID>&redirect_uri=http%3A%2F%2Flocalhost%3A9000%2Flogin-success&state=1&response_type=token&scope=pages_read_engagement%2Cpages_manage_posts

I didn’t had my app reviewed yet so I was only able to post to pages. But that’s fine – let’s use a page then. The redirect lands on localhost. From the URL the access_token is needed. This token is valid for only one hour. But there is a way to extend this token to 60 days:

curl --location 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=278756521529473&client_secret=4e085a2a7b1f08d73c6ea0d34415e434&fb_exchange_token=<ACCESS_TOKEN_FROM_STEP_BEFORE>'

The result contains another access token that now has 60 days validity. Fine for me =)

With that extended token I can create posts in a script and schedule them as needed:

#!/usr/bin/env bash

ACCESS_TOKEN=<THE_EXTENDED_TOKEN>

PAGE_TOKEN=$(curl -s --location "https://graph.facebook.com/v17.0/me/accounts?access_token=$ACCESS_TOKEN" | jq -r '.data[0] | .access_token')

curl --location --request POST \
 --data-urlencode "message=some message above the preview" \
 --data-urlencode "link=https://youtube.com/shorts/t_zfdjgYarw" \
 "https://graph.facebook.com/v17.0/me/feed?access_token=$PAGE_TOKEN"

Running this script posts to the timeline of the page. The PAGE_TOKEN is another token valid only for a single page. Have a look at the response of the /me/accounts query to see what options you have. Maybe you don’t want the first one as I chose in the script by the us of jq.

For the scheduling part I simply add these scripts to cron on my server.