def getUserInbox(user): access_token = user.access_token facebook = OpenFacebook(access_token) inbox = facebook.get('/me/inbox') inbox2 = facebook.get(inbox['paging']['next'].split("v2.0")[1]) return breadthlooper(inbox,user, facebook)
def recursive_graph_call(graph_id, *args, **kwargs): ''' response = recursive_graph_call('147863265269488_588392457883231/likes', limit=500) ''' graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) if 'limit' not in kwargs: kwargs['limit'] = 100 response = {} while True: r = graph.get(graph_id, *args, **kwargs) if not response: # first call response = r else: response['data'] += r['data'] if 'paging' in r: kwargs['after'] = r['paging']['cursors']['after'] else: break return response
def is_authenticated(self, request, **kwargs): print "Authentication starting..." # Make sure user supplied access token in request try: if request.method == 'GET': access_token = request.GET['access_token'] elif request.method == 'POST': access_token = request.POST['access_token'] except KeyError: return self._unauthorized() # Authenticate with facebook from open_facebook import OpenFacebook from django_facebook.connect import connect_user print "Authentication token found. Verifying..." facebook = OpenFacebook(access_token) print "Connection to Facebook server in progress..." try: if not facebook or not facebook.is_authenticated(): return self._unauthorized() except: return self._unauthorized() print "Connection established. Authentication successful." # Facebook authenticated, now associate # with own internal user, Creating a new user if # necessary. #action, user = connect_user(request, access_token, facebook) user = facebook.get('me') return user
def handle(self, app_id, app_secret, facebook_page_id, user_token, *args, **options): # To generate a user_token use https://developers.facebook.com/tools/explorer/ # Select your application and Get Access Token # manage_pages in Extended Permissions must be enabled for this token # facebook_page_id can also be obtained from https://developers.facebook.com/tools/explorer/ # Query for 'me/accounts' and look for the id of your facebook page # Another way to find the id is using http://findmyfacebookid.com/ # There you will only have to enter the url of your page to get the page id h = httplib2.Http("") resp, content = h.request("https://graph.facebook.com/oauth/access_token?client_id" "="+app_id+"&client_secret="+app_secret+"&grant_type=fb_excha" "nge_token&fb_exchange_token="+user_token, "POST") user_token_extended = content[13:] graph = OpenFacebook(user_token_extended) accounts = graph.get('me/accounts') page = filter(lambda page: page['id'] == facebook_page_id, accounts["data"])[0] not_expiring_token = page["access_token"] print not_expiring_token
def get_user_from_id(cls, fb_id, token): print "received post", fb_id, token fb = OpenFacebook(token) data = fb.get("me") print data cls.create(data, token)
def get_context_data(self, **kwargs): fb_user = FacebookCustomUserActive.objects.get(id=self.request.user.id) if fb_user.facebook_id and fb_user.access_token: facebook = OpenFacebook(fb_user.access_token) data = facebook.get('me/photos/uploaded', fields='picture')['data'] else: data = {} kwargs['facebook_photos'] = data return super(CreateFacebookPhoto, self).get_context_data(**kwargs)
def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) user = SocialAccount.objects.get(user=request.user) access_token = SocialToken.objects.get(account_id=user, account__provider='facebook') idUser = user.uid graph = OpenFacebook(access_token=access_token) if graph.is_authenticated(): idPages = (graph.get('me/accounts/')) id_Pages_List = [id['id'] for id in idPages['data']] id_Pages_List = ", ".join(id_Pages_List) id_Page_Access_Token = (graph.get(id_Pages_List, fields='access_token')) id_Page_Access_Token = (id_Page_Access_Token['access_token']) graph = OpenFacebook(access_token=id_Page_Access_Token) feed_url = 'https://graph.facebook.com/'+id_Pages_List+'/feed?message='+post.text+'&access_token='+id_Page_Access_Token feed_Request = requests.post(feed_url) print(feed_Request.status_code) if(feed_Request.status_code == 200): return render(request, 'blog/home.html', {'user': request.user,'access_token': id_Page_Access_Token,'page_id': id_Pages_List }) else: return HttpResponse(feed_Request) print('bad') return render(request, 'blog/loginFacebook.html', {'access_token': access_token, 'idUser': idUser}) else: print('bad') return render(request, 'blog/loginFacebook.html') else: form = PostForm() return render(request, 'blog/add_new_post.html', {'form': form})
def set_page_token(self): token = FacebookAdminToken.objects.last() auth_token = token.access_token graph = OpenFacebook(auth_token) result = graph.get('me/accounts') for row in result['data']: if row['id'] == settings.PAGE_ID: self.page_token = row['access_token'] print('Page Token: ', self.page_token, ' ***') break
def populate_likes(self): assert self.token try: fb = OpenFacebook(self.token) likes = fb.get("me/likes")['data'] for like in likes: Interest.get_or_create(like, self) except Exception, e: logging.exception(e)
def get_all_of_users_facebook_friends_on_yapster(user, facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends', fields="id")['data'] this_users_facebook_friends_on_yapster = [ friend_facebook_id['id'] for friend_facebook_id in facebook_friends if Settings.objects.filter( is_active=True, facebook_account_id=friend_facebook_id['id']).exists() == True ] return this_users_facebook_friends_on_yapster
def main(): social_datas = Social_Data.objects.filter(active=True) for social_data in social_datas: if social_data.account_type == '0': #facebook graph = OpenFacebook(social_data.account_token) profile = graph.get('me') profile_id = profile['id'] friends = graph.get('me/friends') total_follower = int(friends['summary']['total_count']) social_data.total_follower = total_follower social_data.save() elif social_data.account_type == '1': #twitter api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=social_data.account_id, access_token_secret=social_data.account_token) social_data.total_follower = api.VerifyCredentials( ).followers_count social_data.save()
def create_default_photo(sender, instance, created, **kwargs): if created: logger.info('create_default_photo triggered by {} {}'.format( sender, instance )) facebook = OpenFacebook(instance.user.access_token) data = facebook.get('me', fields='picture.hight(1000).width(1000)') image_url = data.get('picture', {}).get('data', {}).get('url', {}) FacebookPhoto.objects.get_or_create( photo=image_url, order=0, user=instance.user )
def get_playlists(client, username, request): if len(username) > 1: username = username else: print "Whoops, need your username!" print "usage: python user_playlists.py [username]" sys.exit() token = util.prompt_for_user_token(username) if token: sp = spotipy.Spotify(auth=token) playlists = sp.user_playlists(username) print playlists #playlist = sp.user_playlist(username, playlist_id=playlist, fields=None) #print playlist #print playlist['tracks']['total'] limit = 100 #playlist = sp.user_playlist_tracks(username, playlist_id=playlist, fields=None, limit=limit, offset=100) #print playlist #print playlist['next'] i=1 print "Access Token:" me = request.user print me #graph = get_persistent_graph(user2) graph = me.get_offline_graph() print graph access_token = me.access_token print access_token facebook = OpenFacebook(access_token) me = facebook.get('me', fields ='third_party_id') print me print 'got it!' ''' for track in playlist['items']: print str(i) + ' ' + track['track']['name'] + ' ' + track['track']['uri'] if i == limit: print playlist['next'] return i += 1 ''' else: print "Can't get token for", username
def get_admin_access_token_complete(request): code = request.GET['code'] graph = OpenFacebook() params = { 'code': code, 'client_id': settings.SOCIAL_AUTH_FACEBOOK_APP_KEY, 'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET, 'redirect_uri': request.build_absolute_uri(reverse('get_admin_access_token_complete')) } resp = graph.get('oauth/access_token', **params) FacebookAdminToken(access_token=resp['access_token']).save() return HttpResponseRedirect('/admin/')
def get_posts_impressions(request): """Get the number of impressions for a post id. Receives the post id as a GET parameter and uses Facebook api to get lifetime impressions. Returns JSON for total lifetime impressions for a post id. """ post_id = request.GET['post_id'] # call facebook api using OpenFacebook api facebook = OpenFacebook(request.user.access_token) impressions = facebook.get('%s/insights/post_impressions_unique' % (post_id)) try: # try getting the impressions from json and return N/A if not found num_impression = impressions['data'][0]['values'][0]['value'] except: num_impression = 'N/A' return JsonResponse({"impressions": num_impression})
def renew_facebook_admin_token(): current_token = FacebookAdminToken.objects.last() if current_token.obtained > (timezone.now() - timezone.timedelta(days=14)): return # obtained two weeks ago, time to renew params = { 'grant_type': 'fb_exchange_token', 'client_id': settings.SOCIAL_AUTH_FACEBOOK_APP_KEY, 'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET, 'fb_exchange_token': current_token.access_token } graph = OpenFacebook() resp = graph.get('oauth/access_token', **params) FacebookAdminToken(resp['access_token']).save()
def _PostToFB(message): token = getattr(settings, 'FACEBOOK_AUTHENTICATION_TOKEN', "") page = str(getattr(settings, 'FACEBOOK_PAGE_ID', 123)) user_account = OpenFacebook(token) accounts = user_account.get('me/accounts') for x in accounts['data']: if x['id'] == page: page = x break else: # page not found print "Page not found with corresponding ID" return page_graph = OpenFacebook(page['access_token']) result = page_graph.set('me/feed', message=message) print "FB post result:", result
def get_facebook_access_token(request): me = [] if request.method == 'GET': code = request.GET.get('code',None) redirect_uri = "http://localhost:8000%s" % reverse('facebook-access') response=FacebookAuthorization.convert_code(code,redirect_uri =redirect_uri) access_token=response.get('access_token',None) expire = response.get('expires',None) expiration = datetime.datetime.now() + datetime.timedelta(seconds=int(expire)) try: stored_token = FaceBookAcessToken.objects.all()[0] stored_token.access_token=access_token stored_token.expiration=expiration except: stored_token = FaceBookAcessToken(access_token=access_token,expiration=expiration) stored_token.save() facebook=OpenFacebook(access_token) me =facebook.get('me') return render(request,"facebook_access/facebook_access.html", {"me":me,})
def page_listing(request): """Fetches the pages managed by a user and shows it on listing.html page. Uses Facebook API to get the pages for a uset. """ facebook = OpenFacebook(request.user.access_token) details = facebook.get('me/accounts') details_dict = details page_info_list = [] # list containing details of all the pages for entry in details_dict.get('data'): temp_dict = { 'name': entry['name'], 'id': entry['id'], 'category': entry['category'] } page_info_list.append(temp_dict) # render to template return render_to_response('listing.html', locals(), RequestContext(request))
def userListens(access_token, client_username): # Form has username info to get access_token from Spotify username = client_username token = util.prompt_for_user_token(username) sp = spotipy.Spotify(auth=token) graph = OpenFacebook(access_token) if access_token is not None: listen_data = graph.get('me/music.listens') user_listens = [] listens = listen_data['data'] for listen in listens: tmp = [] song_name = listen['data']['song']['title'] client_url = listen['data']['song']['url'] client_unique = re.search('track\/(.*)', client_url).group(1) print client_unique # Get tuneboss track if it exists, othewise create it. try: tb_track = Track.objects.get(client_unique=client_unique) except Track.DoesNotExist: sp_track = sp.track(client_unique) client = Client.objects.get(client_name='Spotify') tb_track = create_track(sp_track, client, username) artist_name = tb_track.artist_name tmp.append(client_unique) tmp.append(song_name) tmp.append(artist_name) if listen['data'].get('playlist'): playlist = listen['data']['playlist']['title'] tmp.append(playlist) user_listens.append(tmp) print(json.dumps(song_name, sort_keys=True, indent=4, separators=(',', ': '))) return user_listens
def save_post(request): """Saves the post(both published and unpublished) for a specific page. Receives page id, message and a publish-unpublish flag as parameters. Then finds out the page access token for the page and uses it to post as the page. """ if request.POST.get('publish-check'): published = True else: published = False message = request.POST['post-message'] page_id = request.POST['page_id_post'] user_facebook = OpenFacebook(request.user.access_token) response = user_facebook.get('me/accounts') # get page access token for entry in response['data']: if entry['id'] == page_id: page_access_token = entry['access_token'] break facebook = OpenFacebook(page_access_token) facebook.set('%s/feed' % (page_id), message=message, published=published) return redirect('page-posts', page_id)
def dash(request): """ Show user pics in dashboard """ context = RequestContext(request, {'user': request.user}) # access token from user profile # will be used to access fb user_profile = request.user.get_profile() facebook = OpenFacebook(user_profile.access_token) # get all user uploaded pics from fb photos = facebook.get("me/photos/uploaded", fields='images,album') # logic to get the smallest image # single image and album will be displayed display_photos = [] for photo in photos['data']: sorted_images = sorted(photo['images']) thumbnail = sorted_images[0] large = sorted_images[-1] display_photos.append((photo['album'], thumbnail, large)) context['display_photos'] = display_photos return render_to_response('dash.html', context_instance=context)
def get_all_of_users_facebook_friends(user, facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends', fields="id,name,picture")['data'] return facebook_friends
def get_spotify_username(request): me = request.user context = {} if me.id is not None: access_token = me.access_token print access_token graph = OpenFacebook(access_token) if access_token is not None: listen_data = graph.get('me/music.listens') user_listens = [] listens = listen_data['data'] for listen in listens: tmp = [] song_name = listen['data']['song']['title'] client_url = listen['data']['song']['url'] client_unique = re.search('track\/(.*)', client_url).group(1) tmp.append(song_name) tmp.append(client_unique) user_listens.append(tmp) print(json.dumps(song_name, sort_keys=True, indent=4, separators=(',', ': '))) context['user_listens'] = user_listens current_user = request.user print 'something' if current_user.id is not None: clientProfiles = current_user.clients.all() if clientProfiles: print clientProfiles else: print "clientProfiles" # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ClientUsernameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: # Get information from username form username = form.cleaned_data["username"] client_name = form.cleaned_data["client"] # Client object and ID based on client chosen by user client = Client.objects.get(client_name=client_name) client_id = client.id # Check if the user has this a profile for this client, if not create it. try: client = current_user.clients.get(id=client_id) except client.DoesNotExist: new_client_profile = ClientProfile(user=current_user, client=client, username=username) new_client_profile.save() # Get user's playlists - Inside this helper function we will decide whether the data needs to be added to TuneBoss, updated or is already present. playlists = update_user_playlists(client, username, request) context = {} if current_user.id is not None: context['user_clientlists'] = current_user.member_clientlists.all() return render(request, 'home.html', context) # if a GET (or any other method) we'll create a blank form else: form = ClientUsernameForm() if current_user.id is not None: print "current_user " + str(current_user.email) context['user_clientlists'] = current_user.member_clientlists.all() context['form'] = form return render(request, 'home.html', context)
def registered_facebook(request): global token social_account = None username = '' try: token = request.POST.get('access_token') long_access_token = FacebookAuthorization.extend_access_token(token)['access_token'] print 'long is generated' print long_access_token except Exception as e: print e print "register 1" long_access_token = token print long_access_token try: graph = OpenFacebook(long_access_token) profile = graph.get('me') profile_id = profile['id'] # profile_email = profile['email'] profile_first_name = profile['first_name'] profile_last_name = profile['last_name'] profile_gender = profile['gender'] if profile_gender == 'male': sex = True else: sex = False except Exception as e: print '%s (%s)' % (e.message, type(e)) return HttpResponseRedirect('/sorry/') try: print "1212122asas" social_account = SocialData.objects.filter(account_id=str(profile_id)).all() print social_account print "1" except Exception as e: print "HATA" + e try: print "sss" print "r4" if social_account: print "hesap var" user = User.objects.get(id=social_account[0].user.id) social_network = SocialData.objects.get(user=user.id) username = str(user.username) password = str(user.password) social_network.account_token = long_access_token print username print password print "sss" else: print "Hesap yok" user_auth = User.objects.create_user(profile_id, 'sss', profile_id) user_auth.first_name = profile_first_name user_auth.last_name = profile_last_name print "sss" user_auth.email = "" user_auth.is_staff = False user_auth.is_active = True user_auth.save() print "user kayit oldu" au = Audience.objects.get(id=1) users = Users.objects.create(user_id=user_auth.id, gender=sex, been_id=1, lives_in_id=1) users.save() print "users kayit oldu" social_network = SocialData(user=user_auth, account_type=0, account_id=profile_id, account_token=long_access_token) username = profile_id social_network.save() dada = authenticate(username=username, password=username) if dada is not None: print "ac" if dada.is_active: print "ba" auth_login(request, dada) print "you are login !!!" + "hello " + request.user.username return HttpResponse("true", content_type='application/json') else: print "b" print "a" print "social_network kayıt oldu" return "false" except Exception as e: print e print "register4" return HttpResponseRedirect('/login/')
class FacebookApiExplorer(SocialApi): def get_data(self): self.graph = OpenFacebook(self.credentials['access_token']) feed = self.graph.get('me/posts') self.contents = feed["data"] def process_contents(self): for post in self.contents: post_id = post["id"] identification = re.split("_", post_id) account_id = identification[0] post_id = identification[1] published_at = post["created_time"] published_at = datetime.strptime(published_at[0:10]+' '+published_at[11:19], '%Y-%m-%d %H:%M:%S') published_at = timezone.make_aware(published_at, timezone.get_fixed_timezone(0)) if "link" in post.keys(): original_url = post["link"] else: original_url = "https://www.facebook.com/"+account_id+"/posts/"+post_id def search(parameter): try: return post[parameter] except KeyError: return "" def amount(parameter): try: return self.graph.get(post['id']+'/'+parameter, summary='1')['summary']['total_count'] except KeyError: return 0 text = search("message") video_url = search("source") image_url = search("picture") image_id = search("object_id") post_type = search("type") number_of_likes = amount("likes") number_of_comments = amount("comments") if image_url and image_id: feed = self.graph.get(image_id) try: if post_type == 'video': image_url = sorted(feed['format'], key=lambda k: k['width'], reverse=True)[0]['picture'] else: image_url = sorted(feed['images'], key=lambda k: k['width'], reverse=True)[0]['source'] except KeyError: #Error finding image_url pass new_content = FacebookContent(identifier=post_id, text=text, published_at=published_at, image_url=image_url, original_url=original_url, number_of_comments=number_of_comments, number_of_likes=number_of_likes, video_url=video_url) try: if (text or video_url or image_url) and post_type != 'link': self.update_content(new_content) except Exception as err: print 'Could not save content %s: %s' % (new_content, err)
def news(request): if request.method == 'GET': graph = OpenFacebook(request.user.access_token) likes_response = graph.get('me/likes', limit=50000) likes = likes_response and likes_response.get('data') return HttpResponse(likes)
def fb_auth_handler(request): # Retrieve oAuth response response = urlparse(request.get_full_path()) query = parse_qs(response.query) # Handle oAuth initial request error if "error" in query and "access_denied" in query["error"] and \ "user_denied" in query["error_reason"]: try: logger.warning("Facebook returned error: %s" % query["error"]) except KeyError: err_msg = "Please login and allow Facebook to continue." return HttpResponse(json.dumps({"status": "fail", "message": err_msg})) # Recreate the redirect_uri redir_path = request.get_full_path() logger.info("exchanging code for accesstoken...") redirect_uri = request.META['wsgi.url_scheme'] + "://" +\ request.get_host() + reverse("fb_auth_handler") payload = { "client_id": settings.FACEBOOK_APP_ID, "redirect_uri": redirect_uri, "client_secret": settings.FACEBOOK_APP_SECRET, "code": query["code"][0] } xrequest = requests.get("https://graph.facebook.com/oauth/access_token", params=payload) # Handle oAuth secondary request error fbresponse = parse_qs(xrequest.text) if "error" in fbresponse or not len(fbresponse): # TODO: Error handling if "error" in fbresponse: err_msg = "FB returned error: %s" % fbresponse["error"] logger.warning(err_msg) else: err_msg = "User fb token expired." logger.warning(err_msg) return HttpResponse(json.dumps({"status": "fail", "message": err_msg})) # Acquire accesstoken accesstoken = fbresponse["access_token"][0] # Acquire userinfo graph = OpenFacebook(accesstoken) user_data = graph.get('me') user = User.create(user_data, token=accesstoken) if user: request.session['me'] = user.fb_id return redirect("/nearby/") # return HttpResponse(json.dumps({"status": "success", # "data": dict(user)})) else: return HttpResponse(json.dumps({"status": "fail"}))
def get_page_posts(request): """ Gets the posts for a given page id. -- This view is called by the datatable as an ajax call to get the next set of posts(both published and unpublished). -- Receives page id and next urls for published and unpublished posts as get parameter. If next urls are passed, calls them to get the next set of posts. Else calls the default urls. -- As post impressions are not known through the same api, we pass a hidden field with value as post id for that column. Once all the rows are loaded, a different ajax call is made to populate that field. -- Merges the result of published and unpublished posts and returns as a JSON to be populated in datatable. """ page_id = request.GET['page_id'] next_url = request.GET['next_url'] unpublished_url = request.GET['unpublished_next_url'] # this represents if all unpublished posts have been received skip_unpublished = request.GET.get('skip_unpublished', 'False') facebook = OpenFacebook(request.user.access_token) # placeholder for main data. Represents a list of lists where each inner list corresponds to a row in table. return_list = [] unpublished_next_url = unpublished_url if skip_unpublished == 'False': # means we should call the unpublished api also try: if unpublished_url: # next url is passed as GET parameter. use this to get the posts. unpublished_post = facebook.get( unpublished_url.replace('https://graph.facebook.com/v2.8/', '')) else: unpublished_post = facebook.get('%s/promotable_posts/' % (page_id), is_published=False) # update the next url for next call unpublished_next_url = unpublished_post['paging']['next'] # populate return list in specific format. Each inner row represents a row. for post in unpublished_post['data']: if unpublished_url: # if next url was called, the first result is repeated. Ignore the first row. unpublished_url = None continue # populate the result list. return_list.append([ post.get('message', post.get('story')), post['created_time'][:-5], '<input type="hidden" name="post_id" value="%s"/>' % (post['id']), "UnPublished" ]) except: unpublished_next_url = unpublished_url skip_unpublished = 'True' # now get the published posts try: if next_url: # next url is passed as GET parameter. use this to get the posts. feed_details = facebook.get( next_url.replace('https://graph.facebook.com/v2.8/', '')) else: feed_details = facebook.get('%s/posts/' % (page_id), limit=10) for element in feed_details['data']: if next_url: # if next url was called, the first result is repeated. Ignore the first row. next_url = None continue # populate the result list. return_list.append([ element.get('message', element.get('story')), element['created_time'][:-5], '<input type="hidden" name="post_id" value="%s"/>' % (element['id']), "Published" ]) # get the next url for published posts new_next_url = feed_details['paging']['next'] # create a json to be consumed by the datatable. The json follows predefined format. The main data is passed as # aaData which is consumed by datatable to create the rows. return JsonResponse({ "sEcho": request.GET['sEcho'], "iTotalRecords": 100000, "iTotalDisplayRecords": 1000000, "aaData": return_list, "next": new_next_url, "unpublished_next": unpublished_next_url, "skip_unpublished": skip_unpublished }) except: return JsonResponse({ "sEcho": request.GET['sEcho'], "iTotalRecords": 100000, "iTotalDisplayRecords": 1, "aaData": [], "next": '', "unpublished_next": unpublished_next_url, "skip_unpublished": skip_unpublished })
def get_all_of_users_facebook_friends(user,facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends',fields="id,name,picture")['data'] return facebook_friends
def get_all_of_users_facebook_friends_on_yapster(user,facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends',fields="id")['data'] this_users_facebook_friends_on_yapster = [friend_facebook_id['id'] for friend_facebook_id in facebook_friends if Settings.objects.filter(is_active=True,facebook_account_id=friend_facebook_id['id']).exists() == True] return this_users_facebook_friends_on_yapster
#import settings as facebook_settings from django.conf import settings settings.configure() from django_facebook import settings as facebook_settings from open_facebook import OpenFacebook from open_facebook.api import FacebookAuthorization import json facebook_settings.FACEBOOK_APP_ID = '611406969009887' facebook_settings.FACEBOOK_APP_SECRET = '6be22272c73f9a90f8ded333fbb0ff4d' access_token = FacebookAuthorization.get_app_access_token() graph = OpenFacebook(access_token) print access_token fb_name = 'HongKongPoliceForce' target = graph.get(fb_name) #fields='id,from,message,created_time,updated_time,reactions.limit(5),comments.limit(5){id,from,message,created_time,comments,likes}' fields = 'reactions.limit(100){id,name,type}' #dict={} #posts=graph.get(target['id']+'/posts',limit=2, fields=fields,version='v2.6') #fields=created_time,id,from,comment_count,message,like_count,likes,comments{parent,message,from,id}&limit=100 #fields=comments.limit(20){from,id,created_time,message,likes,comments},id,created_time,from,message,reactions,updated_time&limit=10 id = target['id'] print id contents = graph.get(id + '/posts', limit=50, fields=fields, version='v2.6') print contents def getUrl(url): if '\\' in url: url = eval('u' + "'" + url + "'")
# -*- coding: utf-8 -*- import requests from django.conf import settings settings.configure() from django_facebook import settings as facebook_settings from open_facebook import OpenFacebook from open_facebook.api import FacebookAuthorization import json facebook_settings.FACEBOOK_APP_ID ='611406969009887' facebook_settings.FACEBOOK_APP_SECRET ='6be22272c73f9a90f8ded333fbb0ff4d' access_token=FacebookAuthorization.get_app_access_token() graph=OpenFacebook(access_token) fb_name='HongKongPoliceForce' target=graph.get(fb_name) fields='reactions.limit(100){id,name,type},comments.limit(100){id,name}' id=target['id'] print id posts=graph.get(id+'/posts',limit=100,fields=fields,version='v2.6') def getUrl(url): if '\\' in url: url=eval('u'+"'"+url+"'") url=url.replace('\\','') return url
def get_fb(links): from open_facebook import OpenFacebook graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) rows = [] for link in links: # https://www.facebook.com/Beelinerus/posts/588392457883231 matches = re.match(r'^https?://www.facebook.com/(.*?)/posts/(\d+)$', link) link = '<a href="{0}">{0}</a>'.format(link) if matches: company_slug = matches.group(1) post_id = matches.group(2) try: company = graph.get(company_slug, fields='id,likes,talking_about_count') except OpenFacebookException as e: rows.append({ 'status': 'error', 'data': [ link, 'Company not found', ] }) continue post_graph_id = '%s_%s' % (company['id'], post_id) try: post = graph.get(post_graph_id, fields='comments.limit(0).summary(true),likes.limit(0).summary(true),shares.limit(0).summary(true)') except OpenFacebookException as e: rows.append({ 'status': 'error', 'data': [ link, 'Post not found', ] }) continue likes = '' shares = '' comments = '' if 'likes' in post: likes = post['likes']['summary']['total_count'] if 'shares' in post: shares = post['shares']['count'] if 'comments' in post: comments = post['comments']['summary']['total_count'] rows.append({ 'status': 'ok', 'data': [ link, company['likes'], company['talking_about_count'], likes, shares, comments, ] }) else: rows.append({ 'status': 'error', 'data': [ link, 'Incorrect url', ] }) return rows
def main(): consumer_key = 'zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret = '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8' published_adverts = Published_Adverts.objects.filter(active=True) for published_advert in published_adverts: if published_advert.campaign.campaign_type == '0': account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='1') api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=account.account_id, access_token_secret=account.account_token) try: if api.GetRetweets(statusid=published_advert.message_link, count=1)[0].retweeted == False: is_message_none(published_advert.social_data.publisher) except Exception as e: print e elif published_advert.campaign.campaign_type == '1': account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='1') api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=account.account_id, access_token_secret=account.account_token) print api.GetStatus(id='565490400102985729').user.id try: if api.GetStatus(id='565490400102985729' ).user.id == api.VerifyCredentials().id: pass else: is_message_none(published_advert.social_data.publisher) except Exception as e: print e elif published_advert.campaign.campaign_type == '2': pass elif published_advert.campaign.campaign_type == '3': account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='0') print account.account_token facebook = OpenFacebook(account.account_token) print facebook.get('deadspace/')['id'] print facebook.get('me/likes/18523496657') if facebook.get('me/likes/' + str(published_advert.message_link))['data'] == []: is_message_none(published_advert.social_data.publisher) else: account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='1') api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=account.account_id, access_token_secret=account.account_token) id_list = api.GetFollowerIDs(user_id=published_advert.message_link) try: if not api.VerifyCredentials().id in id_list: is_message_none(published_advert.social_data.publisher) except Exception as e: print e
def get_fb(links): from open_facebook import OpenFacebook graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) rows = [] for link in links: # https://www.facebook.com/Beelinerus/posts/588392457883231 matches = re.match( r'^https?://www.facebook.com/(.*?)/posts/(\d+)$', link) link = '<a href="{0}">{0}</a>'.format(link) if matches: company_slug = matches.group(1) post_id = matches.group(2) try: company = graph.get(company_slug, fields='id,likes,talking_about_count') except OpenFacebookException as e: rows.append({ 'status': 'error', 'data': [ link, 'Company not found', ] }) continue post_graph_id = '%s_%s' % (company['id'], post_id) try: post = graph.get( post_graph_id, fields= 'comments.limit(0).summary(true),likes.limit(0).summary(true),shares.limit(0).summary(true)' ) except OpenFacebookException as e: rows.append({ 'status': 'error', 'data': [ link, 'Post not found', ] }) continue likes = '' shares = '' comments = '' if 'likes' in post: likes = post['likes']['summary']['total_count'] if 'shares' in post: shares = post['shares']['count'] if 'comments' in post: comments = post['comments']['summary']['total_count'] rows.append({ 'status': 'ok', 'data': [ link, company['likes'], company['talking_about_count'], likes, shares, comments, ] }) else: rows.append({ 'status': 'error', 'data': [ link, 'Incorrect url', ] }) return rows
def get_fb(self, links): from open_facebook import OpenFacebook from . utils import recursive_graph_call graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) ids = set() for link in links: matches = re.match(r'^https?://www.facebook.com/(.*?)/posts/(\d+)$', link) if matches: company_slug = matches.group(1) post_id = matches.group(2) try: company = graph.get(company_slug, fields='id') except OpenFacebookException as e: continue # check post_graph_id = '%s_%s' % (company['id'], post_id) try: post = graph.get(post_graph_id, fields='id') except OpenFacebookException as e: continue # getting likes response = recursive_graph_call(post_graph_id + '/likes', limit=500) for user in response['data']: ids.add(user['id']) # u = self.fb_user(user) # u['like'] = 1 # rows[user['id']] = u # getting shares response = recursive_graph_call(post_graph_id + '/sharedposts', fields='from', limit=500) for share in response['data']: user = share['from'] ids.add(user['id']) # if user['id'] not in rows: # u = self.fb_user(user) # u['share'] = 1 # rows[user['id']] = u # else: # rows[user['id']]['share'] = 1 # getting comments response = recursive_graph_call(post_graph_id + '/comments', fields='from', limit=500) for comment in response['data']: user = comment['from'] ids.add(user['id']) # if user['id'] not in rows: # u = self.fb_user(user) # u['comment'] += 1 # rows[user['id']] = u # else: # rows[user['id']]['comment'] += 1 # else: # rows['errors'] = 'Invalid post link' return ids
def get_fb(self, links): from open_facebook import OpenFacebook from .utils import recursive_graph_call graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) ids = set() for link in links: matches = re.match( r'^https?://www.facebook.com/(.*?)/posts/(\d+)$', link) if matches: company_slug = matches.group(1) post_id = matches.group(2) try: company = graph.get(company_slug, fields='id') except OpenFacebookException as e: continue # check post_graph_id = '%s_%s' % (company['id'], post_id) try: post = graph.get(post_graph_id, fields='id') except OpenFacebookException as e: continue # getting likes response = recursive_graph_call(post_graph_id + '/likes', limit=500) for user in response['data']: ids.add(user['id']) # u = self.fb_user(user) # u['like'] = 1 # rows[user['id']] = u # getting shares response = recursive_graph_call(post_graph_id + '/sharedposts', fields='from', limit=500) for share in response['data']: user = share['from'] ids.add(user['id']) # if user['id'] not in rows: # u = self.fb_user(user) # u['share'] = 1 # rows[user['id']] = u # else: # rows[user['id']]['share'] = 1 # getting comments response = recursive_graph_call(post_graph_id + '/comments', fields='from', limit=500) for comment in response['data']: user = comment['from'] ids.add(user['id']) # if user['id'] not in rows: # u = self.fb_user(user) # u['comment'] += 1 # rows[user['id']] = u # else: # rows[user['id']]['comment'] += 1 # else: # rows['errors'] = 'Invalid post link' return ids