def updateFacebookStatus(status): # fb.APP_ID = FACEBOOK_ID fb.AUTH_SCOPE = ["publish_stream"] fb.authenticate() fb.post("/crimson.beacon/feed", {"message": status}) fb.logout()
def upload(request, post_pk, pk=None): """ Upload selected images to Facebook or Smugmug """ if not pk: pklst = request.POST.getlist("checked") else: pklst = [pk] image_dict = {} for pk in pklst: img = Image.objects.get(pk=pk) img_path = str("./media/" + img.image.name) image_dict[img] = img_path if "_fb" in request.POST: for k,v in image_dict.items(): fb.authenticate() #instead of "My photo" you can pass in comments or tags fb.graph_post("/me/photos", {"message":str(k.title), "source":open(v)}) elif "_sm" in request.POST: smug = SmugmugClient() login_info = smug.login('smugmug.login.withPassword') #album_name = raw_input('Name of album to upload to: ') # todo @linh: how get a pop up message to ask user which album to upload to in views.py session = login_info['Login']['Session']['id'] # album_id = smug.getalbumid(session, album_name) # comment out to just assign a known album_id for testing integration within django album_id = 38487135 # a known existing album_id for testing. http://linhchan.smugmug.com/Testing/ for v in image_dict.values(): smug.uploadtoalbum(v,session,album_id) # todo @linh: Add pop-up message to confirm success or failure return HttpResponseRedirect(request.META["HTTP_REFERER"], dict(media_url=settings.MEDIA_URL))
def commentlikepost(post_limit): ''' Likes and comments post ''' fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream'] fbconsole.authenticate() #status = fbconsole.post('/me/feed', {'message':'Hello from python s script'}) fbconsole.authenticate() query = fbconsole.fql("SELECT actor_id, post_id FROM stream WHERE source_id=me() LIMIT %s" % post_limit) print query for post in query: r = requests.get('https://graph.facebook.com/%s' % post['actor_id']) user = json.loads(r.text) comment = '%s %s: Like and comment from python script! :)' % (user['first_name'] , user['last_name']) print comment #Reply comment comment_id = requests.post("https://graph.facebook.com/" + str(post['post_id']) + "/comments/?access_token=" + fbconsole.ACCESS_TOKEN + "&message=%s" % comment ) print "Comment id: " + comment_id.text #Like the post requests.post("https://graph.facebook.com/" + str(post['post_id']) + "/likes/?access_token=" + fbconsole.ACCESS_TOKEN + "&method=POST") print "Liked" fbconsole.logout()
def handle(self, *args, **options): if not os.path.isdir(TEMP_DIR): os.makedirs(TEMP_DIR, 0o700) self.stdout.write("Loading data from Facebook...") fbconsole.authenticate() # Use fbconsole.logout() to log out # Retrieve user data user = fbget_user() self.stdout.write("User '{name}', ID {id}, username {username}".format(**user)) # Load accounts cache cache = {user['id']: user} for filename in glob.glob(os.path.join(PROFILE_DIR, '*.json')): profile = load_data(filename) if not profile or 'id' not in profile: self.stderr.write("Nothing loaded in file '{0}'".format(filename)) cache[profile['id']] = profile if len(cache) > 1: print("Loaded {0} profiles from cache".format(len(cache))) # Enumerate friends for friend in fbconsole.iter_pages(fbconsole.get('/me/friends')): fid = friend['id'] fname = friend['name'].encode('ascii', 'replace') if fid not in cache: self.stdout.write("Retrieve profile of {0}, (ID={1})".format(fname, fid)) profile = fbconsole.get('/' + fid) if profile['id'] != fid: self.stderr.write("{0} has two IDs: {1} and {2}".format(fname, fid, profile['id'])) save_data(os.path.join(PROFILE_DIR, profile['id'] + '.json'), profile) cache[profile['id']] = profile self.stdout.write(".. done")
def index_page(): """This takes care fo the index page before and after facebook authentication Also, takes care of facebook authentication using fbconsole""" global SUBMIT_TITLE global FACEBOOK_VAL global PARAMS global FRIENDS if SUBMIT_TITLE: """IF at the submition page clear the filter parmeters and clear list of Friends""" PARAMS={'male':False,'female':False,'relationship':False,'single':False} FRIENDS={} if not FACEBOOK_VAL: """If not facebook Validated initalize facebook authentication""" fbconsole.APP_ID="316500388373772" fbconsole.AUTH_SCOPE= ['friends_relationships'] fbconsole.authenticate() FACEBOOK_VAL=True """render submition page to see""" return render_template('submit.html') else: """if neither facebook authticated or at the submition page render the initial facebook initilaztion page""" fbconsole.logout() SUBMIT_TITLE=True return render_template('index.html')
def __init__(self): print "Enter your GMAIL details:" self.auth = base64.encodestring('%s:%s'%(raw_input('Username: '******'read_stream','manage_notifications','read_mailbox','read_requests','user_status'] fb.authenticate() last_check1 = time.time() - INTERVAL * 60 # GMAIL check last_check2 = time.time() - INTERVAL * 60 + 30 # FB check fCounter = 0 gCounter = 0 while True: if time.time() - last_check1 > 60 * INTERVAL: last_check1 = time.time() gCounter = self.count(self.getfeed(self.auth)) print "Unread Mails on GMAIL :", gCounter writeSer(GMAIL,str(gCounter)) if time.time() - last_check2 > 60 * INTERVAL: last_check2 = time.time() userId = fb.fql("SELECT uid,name FROM user WHERE uid = me()") notify = fb.fql("SELECT notification_id,created_time,title_text FROM notification WHERE recipient_id = me() AND is_unread = 1") mail = fb.fql("SELECT name,unread_count FROM mailbox_folder WHERE folder_id = 0 AND viewer_id = me()") if len(mail): fCounter += 1 if len(notify): fCounter += len(notify) writeSer(FB,fCounter) print "Notifiactions on FB :",fCounter fCounter = 0
def __init__(self, dump_path): fbconsole.AUTH_SCOPE = ['user_friends', 'read_stream', 'friends_actions.news', 'friends_activities', 'friends_photos'] fbconsole.authenticate() self.fb = fbconsole self.dump_path = dump_path self.logger = logging.getLogger(self.__class__.__name__)
def about_me(): fb.AUTH_SCOPE = ['publish_stream', 'user_photos', 'friends_photos'] fb.authenticate() me = fb.get('/me') about = '' for key, value in me.iteritems(): about += '%s -> %s <br>' % (key, value) return about
def fb_access(): """ logs into Facebook account and asks for permission. Further the music names are extracted from the profile""" fbconsole.AUTH_SCOPE = ['user_likes','publish_checkins' ] fbconsole.authenticate() music = fbconsole.fql("SELECT music FROM user WHERE uid=me()") music_names(music) fbconsole.logout()
def upload(request, post_pk, pk=None): """ Upload selected images to facebook """ if not pk: pklst = request.POST.getlist("fb") else: pklst = [pk] for pk in pklst: img = Image.objects.get(pk=pk) img_path = str("./media/" + img.image.name) fb.authenticate() #instead of "My photo" you can pass in comments or tags fb.graph_post("/me/photos", {"message":str(img.title), "source":open(img_path)}) return HttpResponseRedirect(request.META["HTTP_REFERER"], dict(media_url=settings.MEDIA_URL))
def fbpost(request): fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins'] fbconsole.authenticate() month = datetime.datetime.now().strftime("%B") day = datetime.datetime.now().strftime("%d") query = day+" "+month person = Person.objects.filter(date_of_birth=query,photo__isnull=False)[:60] for p in person: url = "http://muvidb.com/cast_%d.dhtml"%p.id fbconsole.post('/me/feed', {'link':url}) time.sleep(30) return HttpResponseRedirect(reverse('home'))
def music(request): fbconsole.AUTH_SCOPE = ['user_likes','publish_checkins' ] fbconsole.authenticate() music = fbconsole.fql("SELECT music FROM user WHERE uid=me()") music_list = music[0].values() for name in music_list: #fetch music names music_name = (choice(name.split(','))).encode('utf-8') for url in search('%s gaana' %music_name, stop=1): #validating if the music are avalialble if re.search(ur'http://gaana.com', url, re.UNICODE): webbrowser.open_new(url) break
def retrieve_friends(): fbconsole.authenticate() friends = fbconsole.get('/me/friends', {'fields':'id,first_name,last_name'}) next_url = friends.get('paging') friends = friends['data'] while next_url: p = fbconsole.urlparse(next_url['next']) more_friends = fbconsole.get(p.path+'?'+p.query) next_url = more_friends.get('paging') more_friends = more_friends['data'] if not more_friends: break friends.extend(more_friends) return friends
def authenticate(): """Authenticate with facebook""" global APP_SECRET # get temp access token fbconsole.authenticate() # get longer access token params = {"grant_type":"fb_exchange_token", "client_id":fbconsole.APP_ID, "client_secret":APP_SECRET, "fb_exchange_token":fbconsole.ACCESS_TOKEN } post_resp = requests.post(url="https://graph.facebook.com/oauth/access_token",data=params) new_access_token = re.search(r'access_token=(.*)&',post_resp.text).groups()[0] fbconsole.ACCESS_TOKEN = new_access_token
def facebookFriends(self, speech, language): if (language == "de-DE"): AnswerString = "" view = AddViews(self.refId, dialogPhase="Completion") fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access'] fbconsole.authenticate() for post in fbconsole.iter_pages(fbconsole.get('/me/friends')): AnswerString = AnswerString + post['name'] + "\n" self.say("Das sind deine Freunde:") FacebookFriends = AnswerObject(title='Deine Freunde :',lines=[AnswerObjectLine(text=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[FacebookFriends]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request()
def photos(): fb.AUTH_SCOPE = ['publish_stream', 'user_photos', 'friends_photos'] fql = '''select object_id, owner, src_big from photo where aid in (select aid from album where name="Profile Pictures" and owner in (select uid2 from friend where uid1=me() ))''' fb.authenticate() print 'autenticou' links = fb.fql(fql) for photo_links in links: uid = photo_links['owner'] photo_id = photo_links['src_big'] for key, value in photo_links.items(): if key == 'src_big': http_client.fetch(value, buscar(uid, photo_id)) print photo_id baixar.add(photo_id) ioloop.IOLoop.instance().start()
def main(access_token_file='.fb_access_token'): fb.APP_ID = "265270133561898" fb.ACCESS_TOKEN_FILE = access_token_file fb.AUTH_SCOPE = [ 'public_profile', 'user_friends', 'email', 'user_about_me', 'user_actions.books', 'user_actions.fitness', 'user_actions.music', 'user_actions.news', 'user_actions.video', 'user_birthday', 'user_education_history', 'user_events', 'user_games_activity', 'user_hometown', 'user_likes', 'user_location', 'user_managed_groups', 'user_photos', 'user_posts', 'user_relationships', 'user_relationship_details', 'user_religion_politics', 'user_tagged_places', 'user_videos', 'user_website', 'user_work_history', 'read_custom_friendlists', 'read_insights', 'read_page_mailboxes', 'manage_pages', 'publish_pages', 'publish_actions', 'rsvp_event', 'ads_read', 'ads_management', ] fb.authenticate()
def __init__(self): self.counter = 0 #fb = imp.load_source('fb', '.fbconsole.py') fb.AUTH_SCOPE = ['read_stream','manage_notifications','read_mailbox','read_requests','user_status'] #fb.ACCESS_TOKEN = "713005285382454|QXlQXvch37hPNejb7TuFZBFoulU" #fb.APP_ID = '713005285382454' fb.authenticate() last_check = time.time() - INTERVAL*60 # subtract so that we check first time while True: if time.time() - last_check < INTERVAL*60: continue last_check = time.time() self.queryFB() #Counter of Notification if len(self.mail): self.counter += 1 if len(self.notify): self.counter += len(self.notify) self.printNotification() writeSer(FB,self.counter) self.counter = 0
def facebookNotifications(self, speech, language): if (language == "de-DE"): AnswerString = "" fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access'] fbconsole.authenticate() view = AddViews(self.refId, dialogPhase="Completion") file = urllib2.urlopen('https://api.facebook.com/method/notifications.getList?access_token=%s&format=json' % (fbconsole.ACCESS_TOKEN)) data = json.load(file) error = 0 number = 0 while (error != 1): try : AnswerString = AnswerString + data["notifications"][number]["title_text"] + "\n\n" number = number + 1 except IndexError : error = 1 if (number == 0): self.say("Du hast keine neue Nachrichten!") self.complete_request() if (number == 0): self.say("Du hast eine neue Nachricht!") FacebookNotifications = AnswerObject(title='Your notification :',lines=[AnswerObjectLine(text=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[FacebookNotifications]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() self.say("Du hast %s neue Nachrichten!" % (number)) FacebookNotifications = AnswerObject(title='Your notifications :',lines=[AnswerObjectLine(text=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[FacebookNotifications]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request()
def facebookFriendRequests(self, speech, language): if (language == "de-DE"): fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access', 'manage_notifications', 'read_requests'] fbconsole.authenticate() self.say("Ich checke ...") AnswerString = "" view = AddViews(self.refId, dialogPhase="Completion") error = 0 number = 0 while (error != 1): try: AnswerString = AnswerString + fbconsole.get('/me/friendrequests')['data'][number]['from']['name'] + "\n" number = number + 1 except IndexError: error = 1 if (number == 0): self.say("Du hast keine Freundschaftsanfragen!") self.complete_request() if (number == 1): self.say("Du hast eine neue Freundschaftsanfrage!") FacebookRequests = AnswerObject(title='Friend request from :',lines=[AnswerObjectLine(text=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[FacebookRequests]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request() self.say("Du hast %s neue Freundschaftsanfragen!" % (number)) FacebookRequests = AnswerObject(title='Friend requests from :',lines=[AnswerObjectLine(text=AnswerString)]) view1 = 0 view1 = AnswerSnippet(answers=[FacebookRequests]) view.views = [view1] self.sendRequestWithoutAnswer(view) self.complete_request()
import gdata.youtube import gdata.youtube.service import praw import fbconsole import PIL from PIL import Image import base64 import cStringIO import HTMLParser from config import * yt_service = gdata.youtube.service.YouTubeService() r = praw.Reddit(user_agent='mumblebot by /u/underyx') r.login(reddituser, redditpass) """ fbconsole.AUTH_SCOPE = ['offline_access'] fbconsole.authenticate() """ def strip_accents(s): # Credit to oefe on stackoverflow.com if not s: return False return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) def getYoutubeData(videoid): entry = yt_service.GetYouTubeVideoEntry(video_id=videoid) title = entry.media.title.text m, s = divmod(int(entry.media.duration.seconds), 60) return strip_accents(unicode(title)), unicode("%d:%02d" %(m, s)) def getRedditTitle(link):
def __init__(self, app_id=None): if app_id: fbconsole.APP_ID = '<' + app_id + '>' fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins'] fbconsole.authenticate()
def last_post(): fb.AUTH_SCOPE = ['publish_stream'] fb.authenticate() data = fb.get('/me/feed') return data['data'][0]['message']
def post(self): fbconsole.AUTH_SCOPE = ['email','user_interests', 'user_likes', 'friends_interests', 'friends_likes', 'user_location', 'friends_location', 'user_activities', 'friends_activities'] fbconsole.authenticate() self.redirect("/main");
import fbconsole fbconsole.AUTH_SCOPE = ['manage_notifications', 'read_mailbox'] fbconsole.authenticate() def notification(): print 'fetching your unread notifications.... \n ' notify = fbconsole.fql( "SELECT is_unread,title_text FROM notification WHERE recipient_id=me()" ) for i in notify: list(i) a = i.values() if a[1] == 1: print a[0] + '\n' def unread(): print 'showing number of unread messages in your inbox.... \n' unread = fbconsole.fql( "SELECT unread_count FROM mailbox_folder WHERE folder_id =0 AND viewer_id =me()" ) print ' %s unread message(s) in your inbox' % (unread[0].values()) def main(): print 'enter you choice:' a = raw_input('n--> for notification \n' 'r--> for unread messages \n') if a == 'n': notification()
print('The gorupset file is not exist') sys.exit() if os.path.isfile(MESSAGE_FILE_NAME) and os.access(MESSAGE_FILE_NAME, os.R_OK): GetMessageList() else: print('The message file is not exist') sys.exit() fbconsole.AUTH_SCOPE = ['publish_actions'] # fbconsole.APP_ID = '534039770107244' # fbconsole.APP_ID = sys.argv[1] TOKEN_FILE = '.fb_access_token' fbconsole.authenticate() access_token = fbconsole.ACCESS_TOKEN access_token = 'CAACEdEose0cBAMdksmVnvBX4zZAX9alYey1dkwORQpsjRoInavY9athhPwOlQissv5EiqB1QSK6bzekTzZARd4WAsonqZAxoFQxBBlJ3kchOK8M5C0MhykEYVw18D0Ea2BYYtGoTHYQtXhGrk0YLFeHgKjnl3yoCsL6Cm5DPgJphnEcXNUycg1TzapZAFrLl3zjyvBAc9UyotIb2PnNQ' graph = facebook.GraphAPI(access_token) for Msg in MessageList: MsgText = Msg.split(',')[0] MsgLink = Msg.split(',')[1] # print(MsgText + MsgLink) for Group in GroupList: GroupId = Group.split(',')[0].strip(' \r\n') GroupName = Group.split(',')[1].strip(' \r\n') LogData = ('Msg = %s, Link = %s, Id = %s, Name = %s' %(MsgText, MsgLink, GroupId, GroupName)) try: # res = graph.put_wall_post(message=MsgText, attachment = {'link':MsgLink}, profile_id = GroupId )
def loadData(self, preload): preload.isLoading = True try: fb.authenticate() print('Authenticating to Facebook...', end=' ') result = fb.get('/me', {'fields':'id,name'}) user_id = result['id'] user_name = result['name'] print('Complete') # fake user data # user_id = '100001868030396' # user_name = 'Krerkkiat Chusap' # # user_id = '252287594960325' # user_name = 'Test User #1' # # user_id = '247059255488681' # user_name = 'Test User #2' # login to our server print('Authenticating to our server...', end=' ') login_data = bytes('{"type":"action", "value":"login", "uid":"%s"}' % user_id, 'utf-8') result = ConnectionManager.send(login_data) if ConnectionManager.isSuccessfulResponse(result): user = result['data']['user'] hangar = result['data']['hangar'] self._pilot = Pilot(user_id, user_name, user['score'], user['wave'], user['time']) print('Complete') else: print('Fail') SceneManager.exit() # fetch and register resource_register_data print('Loading resource register data...', end=' ') result = ConnectionManager.send('''{"type":"action","value":"get","target":"resource_register_data"}''') if ConnectionManager.isSuccessfulResponse(result): print('Complete') print('Registering resource register data...', end=' ') for key in result['data']: if key == 'surface': self.regisSurfaces(result['data']['surface']) elif key == 'sound': pass elif key == 'background_music': pass elif key == 'background_image': pass print('Complete') # register local surface print('Registering local resource register data...', end=' ') SurfaceManager.register('upBtn', os.path.join(Config.assetsRoot, 'ui', 'up_btn.png'), convert_alpha=True) SurfaceManager.register('downBtn', os.path.join(Config.assetsRoot, 'ui', 'down_btn.png'), convert_alpha=True) SurfaceManager.register('leftBtn', os.path.join(Config.assetsRoot, 'ui', 'left_btn.png'), convert_alpha=True) SurfaceManager.register('rightBtn', os.path.join(Config.assetsRoot, 'ui', 'right_btn.png'), convert_alpha=True) print('Complete') except urllib.error.URLError as e: print('[Error]: Can not connect to server:', e.reason, e) preload.nextScene = None SceneManager.exit() except Exception as e: print('[Error]: Unexpected exception:', e.reason, e) preload.nextScene = None SceneManager.exit() preload.isLoading = False
def run(self): fbconsole.AUTH_SCOPE = ['user_photos', 'friends_photos', 'user_videos'] fbconsole.authenticate() print "Getting mutual friends" mutual_friends = fbconsole.get('/me/mutualfriends/%s' % \ self.target) friendlist = "(%s)" % ','.join( ["'%s'" % user['id'] for user in mutual_friends['data']] ) time.sleep(1) print "Getting albums" albums = fbconsole.fql(""" SELECT aid, name, owner FROM album WHERE owner IN %s """ % friendlist) for album in albums: time.sleep(1) sys.stdout.write('.') sys.stdout.flush() photos = fbconsole.fql(""" SELECT src_big, link, caption, images, pid, created FROM photo WHERE pid IN ( SELECT pid FROM photo_tag WHERE pid IN ( SELECT pid FROM photo WHERE aid = '%s' ) AND subject = '%s' ) """ % (album['aid'], self.target) ) if len(photos) > 0: print "\nIn: '%s' by %d:" % (album['name'], album['owner']) for photo in photos: biggest_image = 0 biggest_dim = 0 for i, image in enumerate(photo['images']): if biggest_dim < image['height']: biggest_dim = image['height'] biggest_image = i image_url = photo['images'][biggest_image]['source'] file_part = image_url.split('/')[-1] file_path = "%s/%s" % (self.destination, "%s_%s_%s" % \ (album['owner'], album['aid'], file_part)) print "Retrieving %s" % image_url try: # Grab the photo. response = urllib2.urlopen(image_url) image_data = response.read() newfile = open(file_path, 'w') newfile.write(image_data) newfile.flush() newfile.close() # Set file modification/creation time to the original # upload date. if photo['created'] > 666666: print "creation date is %d" % photo['created'] os.utime(file_path, (photo['created'], photo['created'])) except urllib2.HTTPError as (e): print "Error received during image grab: %s" % e.read()
def print1(): horoscope1(moon_sign) horoscope2(moon_sign) horoscope3(moon_sign) while True: try: moon_sign = raw_input("Your moon sign : ").lower() print1() #Posting on fb import fbconsole as fb fb.AUTH_SCOPE = ['public_profile', 'user_friends', 'manage_pages'] fb.APP_ID = '738141636393999' fb.authenticate() fb.post('/me/feed/', {'message': 'Today\'s Horoscope : ' + moon_sign + '\n\n' + a}) fb.post('/me/feed/', {'message': 'Today\'s Horoscope : ' + moon_sign + '\n\n' + c}) fb.post('/me/feed/', {'message': 'Today\'s Horoscope : ' + moon_sign + '\n\n' + d}) fb.logout() break except urllib2.HTTPError: print "Entered sign is incorrect.Please enter coorect one" time.sleep(1)
import unicodedata import gdata.youtube import gdata.youtube.service import praw import fbconsole import PIL from PIL import Image import base64 import cStringIO import HTMLParser from config import * yt_service = gdata.youtube.service.YouTubeService() r = praw.Reddit(user_agent='mumblebot by /u/underyx') r.login(reddituser, redditpass) """ fbconsole.AUTH_SCOPE = ['offline_access'] fbconsole.authenticate() """ def strip_accents(s): # Credit to oefe on stackoverflow.com if not s: return False return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) def getYoutubeData(videoid): entry = yt_service.GetYouTubeVideoEntry(video_id=videoid) title = entry.media.title.text
def login(): fbconsole.AUTH_SCOPE = ['publish_stream', 'read_stream', 'status_update'] fbconsole.authenticate()
def setup(self): fb.AUTH_SCOPE = ['publish_stream', \ 'publish_checkins', 'read_stream'] fb.authenticate()
def getFBPicture(): fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access'] fbconsole.authenticate() file = urllib2.urlopen('https://graph.facebook.com/%s?access_token=%s&fields=picture' % (fbconsole.get('/me')['id'], fbconsole.ACCESS_TOKEN)) data = json.load(file) return data["picture"]
def __init__(self, group_id, actor_id): self.group_id = group_id self.actor_id = actor_id fb.AUTH_SCOPE = ['read_stream', 'user_groups'] fb.authenticate()
def login(request): fbconsole.logout() fbconsole.AUTH_SCOPE = ['read_stream'] fbconsole.authenticate() user = is_user_exists() print user req = get_json_graph_url(api_url = '/me/feed') fb_list = ['id','created_time','updated_time'] while(len(req.json().get('data',''))): for item in req.json()['data']: db_row = [] if item['from']['name']: db_row.append(item['from']['name']) else: db_row.append('') for fb_parse_list in range(len(fb_list)): if item.get(fb_list[fb_parse_list]): db_row.append(item.get(fb_list[fb_parse_list])) else: db_row.append('') time_delta = get_time_delta(ctime=item.get('created_time'),utime=item.get('updated_time')) print time_delta time_delta=str(time_delta) print time_delta try: if item['type'] == 'photo': n = News.objects.create( user=user[0], post_by = db_row[0], post_id = db_row[1], time = db_row[2], updated_time = db_row[3], photo = item["link"], time_delta = time_delta ) else: n = News.objects.create( user=user[0], post_by = db_row[0], post_id = db_row[1], time = db_row[2], updated_time = db_row[3], time_delta = time_delta ) n.save() except: pass if item.has_key('status_type'): if item['status_type']=='shared_story': try: News.objects.filter(post_id__iexact=db_row[1]).update(post_by=item['properties'][0]['text']) News.objects.filter(post_id__iexact=db_row[1]).update(shared='Y') except: pass if item.has_key('comments'): if item.has_key('data'): update_comments_table(n, data = item['comments']['data']) if item.has_key('likes'): if item.has_key('data'): update_likes_table(n, data = item['likes']['data']) next_url = req.json()['paging']['next'] req = requests.get(next_url) fbconsole.logout() return render_to_response('index.html')
def init(perms = []): fbconsole.AUTH_SCOPE = list(perms) fbconsole.authenticate()