Note: Keep in mind that the information shared, including the use of the Facebook API, was accurate at the time of writing. However, it’s recommended to double-check for any updates or changes before applying these methods.
The other day I was working on something that required the automation of Facebook posts. The APIs are not difficult but the process of issuing access tokens and all that is something that could be called “straightforward”. Hence, I thought, why not come up with a blog post to record something not for my own but for others as well. As my old readers know that I always prefer to come up with some interesting or at least realistic use case while discussing a concept so I came up with an idea of automation recipe posting on Facebook using Python and Tweepy library. Since chatGPT is available now so unlike past, I did not have to make much efforts coming up with an idea.
This blog post consist of five parts:
- Creation of Facebook Page
- Create Facebook APP
- Getting an access token
- Test Facebook API to post on the newly created page
- Scraping the featured recipe from https://www.allrecipes.com/ and then will be posting it on the facebook page.
So, let’s start!
Facebook Page Creation
The creation of the facebook page is not so difficult. The page is created, I named it YummyDishes ( https://facebook.com/yummyyummydishes))
Creating Facebook App
In order to generate access token you need to create a Facebook App. Head over to https://developers.facebook.com/apps/ and create a new app, below are the screens of app creations and permissions:
Select the Business Option and click Next
Now assign the App name and Email:
Once the app is created, you will get an App ID like I got mine: 666475567111216 and the screen like the below:
So far so good, now head on to https://developers.facebook.com/tools/explorer/, select the newly created app and under User or Page combo, select Get Page Access Token option:
Now select the Fb Page you want to be connected with the app:
If connected successfully, you will see something like the below:
Do make sure that you will be selecting the Page for page access token rather than user token
Now, we have to select the permission that will be responsible to create a post, search pages_manage_posts and select it:
Once it is selected, click on Generate Access Token button, once logged in, it will show the newly assigned permissions:
While you opted for this, the access token is also refreshed, copy it somewhere and head on to Access Token Debugger and paste in the field and hit the Debug button. It will all the details about it:
You could see the scopes assigned and Expiry Date that is infront of Expires section. Now click on Extend Access Token button, it generates a long-lived token that expires on December:
But this will be expired in 2 months, our goal is to get the token that never expires. Access the below url:
https://graph.facebook.com/v2.10/me?fields=access\_token&access\_token=
Where EXTENDED TOKEN is the token the long lived you generated above. When you hit the URL with your required token you’d get a JSON payload like the below:
{ "access_token": "EAAJMVHRqZAlABOzVbvpsrO4iVs1kBXDY51YWfvaB6SCVd4Al2ZBpGyArtTwZCjoS9rwshTIMro2ZBCVas6j8CAan5SHZBvXceDnqPSwZC8tpSnm2DPZApNXsnqB0fbln8ZD", "id": "133534166516215" }
Now, if you debug this access token you’d see something like the below:
As you see, this page token will never expire. Now save this token somewhere, we will use in development.
Testing Facebook API for posting
We have done all the heavy lifting. Now the task is to create a function:
def post_to_fb_page(msg, image_url):
post_url = 'https://graph.facebook.com/v18.0/{}/photos'.format(PAGE_ID)
payload = {
'message': msg,
'access_token': ACCESS_TOKEN,
'url': image_url
}
# Uploading on FB Group
r = requests.post(post_url, data=payload)
data = r.json()
print(data)
if 'id' in data:
return True
else:
return False
The time I was writing this article, the API version was 18.0 but older version works as well, depends on the feature you are requested. The function written above is pretty simple, it makes a request to the graph API endpoint that publishes a post with the image. We are going to make a test post. I went to https://www.allrecipes.com/ and copy both the URL as well as the featured dish name.
from functions import post_to_fb_page
if __name__ == ' __main__':
post_to_fb_page(msg='Instant Pot Best Beef Stew',
image_url='https://www.allrecipes.com/thmb/d7iH4d7LSY0c6aI98G-3AwLZTWw=/800x533/filters:no_upscale():max_bytes(150000):strip_icc():focal(399x0:401x2):format(webp)/263037-instant-pot-beef-stew-mfs-beauty-1x1-BP-2467-80aedb6795b84febbedc172f6d921c14.jpg')
If all goes well it’d return a JSON payload like the below:
{'id': '122100397148075671', 'post_id': '133534166516215_122103677168075671'}
On page, it appears like the below:
You could see the app name after Published By which tells it was an automated post.
Scraping featured recipe
Now I am going to write a function to scrape the featured recipe from the main page of https://www.allrecipes.com/.
I will be using ScraperAPI cloud API for scraping purpose. Why? well pretty simple, using ScraperAPI’s cloud service gives you proxy feature so you do not have to buy expensive yet pathetic proxies from other services. This app is a simple app but imagine you are scraping millions of records a week, the chance of blocking your real IP is high. ScraperAPIs free you from all such issues. Oh if you sign up here with my referral link or enter promo code adnan10 , you will get a 10% discount on it. They offer other services too like using their builtin Amazon and Google Search scraper. In case you do not get the discount then just let me know via email on my site and I’d sure help you out.
Anyways, I am writing a function that will return Dish title and the image URL, enough for this blog post. Below is the function to scrape data related to recipe.
def get_featured_recipie():
URL_TO_SCRAPE = 'https://allrecipes.com/'
title = None
image_url = None
headers = {
'authority': 'www.allrecipes.com',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9,ur;q=0.8,zh-CN;q=0.7,zh;q=0.6',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
}
payload = {'api_key': API_KEY, 'url': URL_TO_SCRAPE, 'render': 'true'}
r = requests.get('http://api.scraperapi.com', params=payload, timeout=60)
html = r.text.strip()
soup = BeautifulSoup(html, 'lxml')
title = soup.select('#card--featured_1-0 .card__title-text')[0].text.strip()
image_url = soup.select('#card--featured_1-0 img')[0]['data-src'].strip()
return title, image_url
Conclusion
So in this post, we learned how we can automate posting on a Facebook page in Python. I hope you would have enjoyed this post. Like always, the code is available on Github.
Originally published at https://blog.adnansiddiqi.me on October 13, 2023.
Top comments (0)