Monitoring Facebook Fanpage Using Graph API

Here is a code for monitoring Facebook fanpage posts (not necessarily yours) using Graph API.

APP_SECRET and APP_ID must be from an app created with your Facebook developer account, like in the image below:


And asign company variable to a Facebook fanpage name, for example: socialcuy.

Hope you find it useful.

import urllib2
import json
import pyaudio
import wave
import webbrowser
 
def create_posts_url(graph_url, APP_ID, APP_SECRET): 
    #create authenticated post URL
    post_args = "/posts/?key=value&access_token=" + APP_ID + "|" + APP_SECRET
    posts_url = graph_url + post_args

    return posts_url
    
def render_to_json(graph_url):
    #render graph url call to JSON
    try:
        web_response = urllib2.urlopen(graph_url)
        readable_page = web_response.read()
        json_data = json.loads(readable_page)
        return json_data
    except:
        render_to_json(graph_url)

def get_likes_count(post_id, APP_ID, APP_SECRET):
    count_likes = 0
    try:
        #create Graph API Call
        graph_url = "https://graph.facebook.com/" 
        likes_args = post_id + "/likes?summary=true&key=value&access_token" + APP_ID + "|" + APP_SECRET
        likes_url = graph_url + likes_args
        likes_json = render_to_json(likes_url)
        #pick out the likes count
        count_likes = likes_json["summary"]["total_count"]
    except:
        pass
    return count_likes

def get_value(post, keys):
    try:
        if type(keys) in (tuple, list):
            postvalue = post
            for key in keys:
                postvalue = postvalue[key]
            return postvalue
        else:
            return post[keys]
    except:
        pass
    return ""

def play_audio(path):
    chunk = 1024
    wf = wave.open(path, 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(
        format = p.get_format_from_width(wf.getsampwidth()),
        channels = wf.getnchannels(),
        rate = wf.getframerate(),
        output = True)
    data = wf.readframes(chunk)
    while data != '':
        stream.write(data)
        data = wf.readframes(chunk)
    stream.close()
    p.terminate()

# array containing post ids already seen
posts_ids = []

def main():
    #simple data pull App Secret and App ID
    APP_SECRET = "YOUR APP_SECRET"
    APP_ID = "YOUR APP_ID"
    
    #to find go to page's FB page, at the end of URL find username
    #e.g. http://facebook.com/Wereverwero, Wereverwero is the username
    company = "socialcuy"
    graph_url = "https://graph.facebook.com/"

    #make graph api url with company username
    current_page = graph_url + company

    while True:

        #extract post data
        posts_url = create_posts_url(current_page, APP_ID, APP_SECRET)
        json_postdata = render_to_json(posts_url)
        try:
            json_fbposts = json_postdata['data']
        except:
            continue

        post = json_fbposts[0] #last post

        post_id = get_value(post, "id")
        if post_id in posts_ids:
            print "waiting for new post ........................................."
            continue
        posts_ids.append(post_id)
        print "NEW POST ******************************************"
        
        # if it was recently created then some of these may be empty
        post_created_time = get_value(post, "created_time")
        post_message = get_value(post, "message")
        post_likes_count = get_likes_count(post["id"], APP_ID, APP_SECRET)
        post_link = get_value(post, "link")
        post_name = get_value(post, "name")
        post_description = get_value(post, "description")
        post_shares_count = get_value(post, ["shares", "count"])

        print "post_id = " + str(post_id)
        print "post_created_time = " + post_created_time
        print "post_message = " + post_message
        print "# likes = " + str(post_likes_count)
        print "post_link = " + post_link
        print "post_name = " + post_name
        print "post_description = " + post_description
        print "post_shares_count = " + str(post_shares_count)        
        
        # open post url on default browser
        s_post_id = str(post_id)
        s_post_id = s_post_id[s_post_id.index('_') + 1:]
        webbrowser.open("https://www.facebook.com/" + company + "/posts/" + s_post_id) 

        # play audio and wait till it finishes
        play_audio("alert.wav") 
 
if __name__ == "__main__":
    main() 

It's based on a source code written by @SimpleBeauData, he's also a data science aspirant.