Why am I getting KeyError in the following python code?

I wanna execute this code.

This is the error I’m getting in terminal after running the code

Traceback (most recent call last):
  File "/private/var/folders/6j/n37bd5r92sj8wfkn3k_k9k580000gp/T/Cleanup At Startup/bday-459934533.707.py", line 68, in <module>
    print 'total='+str(process_posts(url)) 
  File "/private/var/folders/6j/n37bd5r92sj8wfkn3k_k9k580000gp/T/Cleanup At Startup/bday-459934533.707.py", line 32, in process_posts
    posts=res_obj["data"] 
KeyError: 'data' 

The code is –

import httplib, urllib 
from bs4 import BeautifulSoup 
import os 
import json 
import time 
import calendar 
access_token='value'
dob='2015-07-30'
conn = httplib.HTTPSConnection("graph.facebook.com") 
print 'requesting...'
#conn.request("GET",path,urllib.urlencode(data),{}) 
has_more=False
def convert_to_local(s): 
t=time.strptime(s[:19],"%Y-%m-%dT%H:%M:%S") 
t=time.localtime(calendar.timegm(t)) 
t=time.strftime("%Y-%m-%d",t) 
return t 

def getRandomThnx(msg): 
return 'thanks :)'
def process_posts(url): 
conn = httplib.HTTPSConnection("graph.facebook.com") 
conn.request("GET",url) 
res = conn.getresponse() 
conn.getresponse 
data=res.read() 
res_obj=json.loads(data) 
posts=res_obj["data"] 
processed=0
for post in posts:         
    if not "message" in post: 
        continue
    msg=post["message"] 
    post_date=convert_to_local(post["created_time"])         
    if dob == post_date:             
        if "from" in post and "message" in post:                 
            user= post["from"]["name"]
            path='/'+post['id']+'/comments'
            param_data={  'format':'json', 
                    'message':getRandomThnx(msg), 
                    'access_token':access_token 
                  } 
            conn = httplib.HTTPSConnection("graph.facebook.com") 
            if post["comments"]["count"]==0: 
                print 'responding to :'+user+'->'+msg 
                conn.request("POST",path,urllib.urlencode(param_data),{}) 
                res = conn.getresponse() 
            path='/'+post['id']+'/likes'
            param_data={  'format':'json', 
                    'access_token':access_token 
                  } 
            conn = httplib.HTTPSConnection("graph.facebook.com") 
            processed+=1
if "paging" in res_obj:         
    return processed+process_posts(res_obj["paging"]["next"]      [len("https://graph.facebook.com"):]) 
else: 
    print "Finished"
    return processed     
url='/me/feed?access_token='+access_token 
print 'total='+str(process_posts(url)) 
print 'Thanx to all wisher :)'


Source: facebook

Leave a Reply