How to post into Facebook page from google Sheet using Python.

In this article we will give you an example Python code that demonstrates how to post to a Facebook page from a Google Sheet using the Facebook Graph API. Please be aware on facebook API policy , Google sheet api policy before you proceed. Make sure that you should hide your credentials.

Libraries required : requests, pygsheets, facebook

  1. pip install requests
  2. pip install pygsheets
  3. pip install facebook-sdk
# First, you will need to install the following Python packages:
# - requests: used to send HTTP requests to the Facebook Graph API
# - pygsheets: used to read data from the Google Sheet
# - facebook-sdk: used to interact with the Facebook Graph API
import requests
import pygsheets
import facebook

# Make sure you replace these values with your own
# How to create facebook page token link below
ACCESS_TOKEN = '<YOUR_FACEBOOK_PAGE_ACCESS_TOKEN>'
GOOGLE_SHEET_URL = '<YOUR_GOOGLE_SHEET_URL>'

# Initialize the pygsheets client and open the Google Sheet
gc = pygsheets.authorize()
sh = gc.open_by_url(GOOGLE_SHEET_URL)

# Select the first worksheet in the Google Sheet
worksheet = sh[0]

# Read the data from the first row of the worksheet
row = worksheet.get_row(1)

# Extract the values from the row
message = row[0]
image_url = row[1]

# Initialize the Facebook Graph API client
graph = facebook.GraphAPI(access_token=ACCESS_TOKEN, version='3.1')

# Create a dictionary with the data for the post
post_data = {
    'message': message,
    'attached_media': [{'media_fbid': image_url}]
}

# Use the Graph API to create the post
response = graph.put_object(parent_object='me', connection_name='feed', **post_data)

# Print the response from the Graph API
print(response)

This code will read the data from the first row of the first worksheet in the Google Sheet, and use it to create a post on your Facebook page. The message for the post will be taken from the first column of the row, and the image for the post will be taken from the second column.

How to get Facebook Page Access Token : Step by step procedure explained

Get more post on Python, PySpark

Author: user

Leave a Reply