Facebook

Documentation

  1. Graph API

Get a user access token.

  1. Go to the Graph API Explorer. If you are not already logged into your Facebook account, press the blue Log In button.
  2. Point at My Apps and press the blue Create New App button.
  3. Type in the display name (the name you want to associate with this App ID) and the contact email. I used the display name “Experiment”. Press the blue Create App ID button.
  4. In the Select a Scenario page, I pressed the Skip button in the lower right corner. I arrived at the dashboard page https://developers.facebook.com/apps/myappid/dashboard/
  5. Go back to the Graph API Explorer. In the upper right corner of the Graph API Explorer, select your new app from the dropdown menu.
  6. From the Get Token menu, select Get User Access Token. In the Select Permissions window, check
    1. user_birthday
    2. user_friends
    3. user_gender
    4. user_photos
    Press the blue Get Access Token button. You will paste this long string into your Python program.
  7. The Log in With Facebook window says, Experiment will receive your name and profile picture. Press the blue Continue As button.
  8. Go to the Access Token Tool, Press the Debug button to the right of User Token for your app (“Experiment”).

Install the modules

pip3 install urllib3
pip3 install requests
pip3 install facebook-sdk
pip3 list

Print all the facebook posts in a given range of dates

When getting the user access token, check user_posts too.

"""
daterange.py

List my Facebook posts in the given date range.
"""

import sys
import facebook

#Get the user access token from https://developers.facebook.com/tools/explorer
token = "blahblahblah"
graph = facebook.GraphAPI(access_token = token)

#Get a dictionary of information about myself.
try:
    dictionary = graph.get_object("me/feed?limit=68&until=15 june 2018&since=3 april 2018")
except facebook.GraphAPIError as error:
    print(error, file = sys.stderr)
    sys.exit(1)

listOfPosts = dictionary["data"]

for post in listOfPosts:    #or for post in reversed(listOfPosts):
    #post is a dict.
    print(f'id = {post["id"]}')
    print(f'created_time = {post["created_time"]}')
    print(f'message = {post["message"]}')
    print()

sys.exit(0)
id = 100003285209008_1688498031269687
created_time = 2018-06-14T08:52:11+0000
message = Flew into JFK, reassembled my bicycle, and was back home in Manhattan's East Village at 4:00 a.m. I saw many beautiful lands and heard many strange creeds, but now at last I'm back at our sea-washed, sunset gates. "I lift my lamp beside the golden door!"

id = 100003285209008_1679820198804137
created_time = 2018-06-07T04:39:08+0000
message = Day 65 (Wed Jun 6, 2018): Livermore to San Francisco, California. Cool and humid.

id = 100003285209008_1678799532239537
created_time = 2018-06-06T06:25:47+0000
message = Day 64 (Tue Jun 5, 2018): Patterson to Livermore, California. Dispiriting day of detours and Plan B's, ending with a powerful headwind up in the Diablo Range.

https://en.m.wikipedia.org/wiki/Diablo_Range

etc.

id = 100003285209008_1615106041942220
created_time = 2018-04-06T02:08:25+0000
message = Day 3 (Thu Apr 5, 2018): Philadelphia to Lancaster, Pennsylvania. First day without freezing rain, but it snowed on me this morning in Philly and I fought a stiff headwind until late afternoon. Tomorrow: more rain and record lows.

id = 100003285209008_1613873898732101
created_time = 2018-04-04T22:34:40+0000
message = Day 2: Trenton to Philadelphia.

id = 100003285209008_1612855695500588
created_time = 2018-04-03T22:20:34+0000
message = MERETZKYS ACROSS AMERICA:
New York to Nashville to San Francisco!

Read a photo from Facebook

"""
facebook.py

Read information about the user from the Facebook graph.
"""

import sys
import facebook

#to display the jpg image with tkinter:
import urllib.request
import tkinter
import PIL.ImageTk

#Get the user access token from https://developers.facebook.com/tools/explorer
token = "blahblahblah"
graph = facebook.GraphAPI(access_token = token)
print(f"type(graph) = {type(graph)}")

#Get a dictionary of information about myself.
try:
    dictionary1 = graph.get_object("me?fields=id,name,birthday,friends,gender,photos")
except facebook.GraphAPIError as error:
    print(error, file = sys.stderr)
    sys.exit(1)

for key, value in dictionary1.items():
    print(f"{key:8} {str(type(value)):14}", end = "")
    if key != "photos":
        print(f" {value}")
    else:
        print()
        print()

        listOfPhotos = value["data"]  #value is a dictionary
        dictionary2 = listOfPhotos[0] #the most recent photo
        id = dictionary2["id"]        #the id number of the photo
        print(f'dictionary2["id"] = {id}')
        print(f'dictionary2["created_time"] = {dictionary2["created_time"]}')
        print(f'dictionary2["name"] = {dictionary2["name"]}')
        print()

        try:
            dictionary3 = graph.get_object(f"{id}/picture")
        except facebook.GraphAPIError as error:
            print(error, file = sys.stderr)
            sys.exit(1)

        url = dictionary3["url"]
        print(f'dictionary3["mime-type"] = {dictionary3["mime-type"]}')
        print(f'dictionary3["url"] = {url}')
        print(f'type(dictionary3["data"]) = {type(dictionary3["data"])}')
        print(f'len(dictionary3["data"]) = {len(dictionary3["data"])}')

try:
    binaryFile = urllib.request.urlopen(url)
except urllib.error.URLError as error:
    print(error, file = sys.stderr)
    sys.exit(1)

sequenceOfBytes = binaryFile.read()     #not a string of characters
binaryFile.close()

root = tkinter.Tk()

#Display the image.

try:
    #The following statement cannot come before the tkinter.Tk().
    photoImage = PIL.ImageTk.PhotoImage(data = sequenceOfBytes)
except BaseException as error:
    print(error, file = sys.stderr)
    sys.exit(1)

width = photoImage.width()
height = photoImage.height()
root.geometry(f"{width}x{height}")
root.title(dictionary2["name"].split(maxsplit = 4)[:4]) #first four words

#Put the center of the image at the center of the canvas.
canvas = tkinter.Canvas(root, highlightthickness = 0)
canvas.create_image(width / 2, height / 2, image = photoImage)
canvas.pack(expand = tkinter.YES, fill = "both")

root.mainloop()
type(graph) = <class 'facebook.GraphAPI'>
id       <class 'str'>  100003285209008
name     <class 'str'>  Mark Meretzky
birthday <class 'str'>  07/12/1955
friends  <class 'dict'> {'data': [], 'summary': {'total_count': 51}}
gender   <class 'str'>  male
photos   <class 'dict'>

dictionary2["id"] = 2346269302159220
dictionary2["created_time"] = 2019-08-11T00:42:56+0000
dictionary2["name"] = A brass plaque shiny enough to reflect an image.  Is that part of the message?

dictionary3["mime-type"] = image/jpeg
dictionary3["url"] = https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/67710648_2346269305492553_3937319047070220288_n.jpg?_nc_cat=104&_nc_oc=AQmIo-velghaYvuPS7Rmx1svlDmqT9LcD9qkrM1jbmYHMuC1QKG10-y3o8ehBJuIHj0&_nc_ht=scontent.xx&oh=42750ed62f3deb67df05857a88841400&oe=5E2D3900
type(dictionary3["data"]) = <class 'bytes'>
len(dictionary3["data"]) = 89223

Things to try

  1. How can we download more stuff from Facebook?
  2. Can we get the Python program to appear as an app or a game on a Facebook page?