def post_social(self): if settings.DEBUG: return try: verb = self.get_verb_past() object = self.get_object_singular() if verb == "favourited": action_type = "deepsouthsounds:favourite" if verb == "liked": action_type = "like" if verb == "followed": action_type = "og.follows" else: action_type = "deepsouthsounds:play" if False: social_account = SocialToken.objects.filter( account__user=self.user.user, account__provider='facebook')[0] facebook = OpenFacebook(social_account.token) notification_html = {object: wrap_full(self.get_object_url())} result = facebook.set('me/%s' % action_type, notification_html) print(result) except Exception as ex: print(ex) pass
def send_post(request): if request.POST: user = FacebookProfile.objects.get(user_id=request.user.id) access_token = user.access_token facebook = OpenFacebook(access_token) # facebook.get('me') # info about me message = request.POST.get('post_text') # facebook.set('me/feed', message=message, picture='http://neutr10.com/wp-content/uploads/2016/02/python-snake.jpg') # posted message for me photo_urls = [ 'http://neutr10.com/wp-content/uploads/2016/02/python-snake.jpg', 'http://neutr10.com/wp-content/uploads/2016/02/python-snake.jpg', ] for photo in photo_urls: print facebook.set('me/feed', message=message, picture=photo, url='http://www.me.com', link=photo, caption="") return render(request, 'send_post.html', {'message': 'Success'}) return render(request, 'send_post.html')
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 connected_facebook_and_yapster_post_on_facebook(user, facebook_access_token): facebook = OpenFacebook(facebook_access_token) url = "http://yapster.co" name = str(user.first_name) + ' ' + str(user.last_name) + " (@" + str( user.username) + ") just connected Yapster to Facebook!" description = "Click here and download the app to listen to what " + " @" + str( user.username) + " has been yapping about." b = connect_s3(bucket_name="yapsterapp") fb_share_yapster_picture_key = b.get_key( '/yapstersocialmedia/yapster_white_y_green_background') fb_share_yapster_picture_url = fb_share_yapster_picture_key.generate_url( expires_in=600) if user.settings.facebook_connection_flag == True: if user.settings.facebook_page_connection_flag == True: api_url = str(user.settings.facebook_page_id) + '/feed' elif user.settings.facebook_page_connection_flag == False: api_url = str(user.settings.facebook_account_id) + '/feed' facebook_post = facebook.set(api_url, link=url, picture=fb_share_yapster_picture_url, name=name, description=description)['id'] return facebook_post else: return 'User has not setup Facebook Connection'
def is_authenticated(self, request, **kwargs): """ Authenticate with facebook, and return user upon success. """ # Make sure user supplied access token in request try: access_token = request.GET['access_token'] except KeyError: return self._unauthorized() # Authenticate with facebook from open_facebook import OpenFacebook from django_facebook.connect import connect_user facebook = OpenFacebook(access_token) try: if not facebook or \ not facebook.is_authenticated(): return self._unauthorized() except: return self._unauthorized() # Facebook authenticated, now associate # with own internal user, Creating a new user if # necessary. action, user = connect_user(request, access_token, facebook) request.user = user return True
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 fb_image(user): if not user.id: return False facebook = OpenFacebook(user.access_token) img_url = facebook.my_image_url(size="small") return img_url
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 _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 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 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 post_catch_of_the_week(self): fish = self.queryset.first() graph = OpenFacebook(self.page_token) img_url = '{}{}'.format(settings.BASE_URL, fish.image.url) url = '{}{}'.format(settings.BASE_URL, reverse('fish_enlarge', args=[fish.pk])) message = 'Fish of the week - {} {}kg. '.format( fish.species.name, fish.weight) graph.set('me/feed', picture=img_url, link=url, message=message)
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 share_yap_story_on_facebook(user, facebook_access_token, yap): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: if user.settings.facebook_account_id != None: name = str(yap.title.encode('utf-8')) if user.settings.facebook_page_connection_flag == True: object_api_url = str( user.settings.facebook_page_id) + '/objects/yapster_fb:yap' elif user.settings.facebook_page_connection_flag == False: object_api_url = str(user.settings.facebook_account_id ) + '/objects/yapster_fb:yap' url = "http://web.yapster.co/yap/" + str(yap.pk) + '/' b = connect_s3(bucket_name="yapster") if yap.picture_flag == True: yap_picture_key = b.get_key(yap.picture_cropped_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) elif yap.picture_flag == False: yap_picture_key = b.get_key(user.profile.profile_picture_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) if yap.description != None: fb_yap = facebook.set(object_api_url, object={ "url": url, "image": yap_picture_url, "title": json.dumps(name), "description": json.dumps(yap.description) })['id'] elif yap.description == None: fb_yap = facebook.set(object_api_url, object={ "url": url, "image": yap_picture_url, "title": json.dumps(name) })['id'] if user.settings.facebook_page_connection_flag == True: story_api_url = str( user.settings.facebook_page_id) + '/yapster_fb:yapped' elif user.settings.facebook_page_connection_flag == False: story_api_url = str( user.settings.facebook_account_id) + '/yapster_fb:yapped' fb_share_yap = facebook.set(story_api_url, yap=fb_yap)['id'] return fb_share_yap else: return "User has not set up a facebook_account_id." else: return "User has not set up their account with Facebook."
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 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 post_weekly_gallery(self): graph = OpenFacebook(self.page_token) resp = graph.set('me/albums', name='Week {}'.format(timezone.now().strftime('%W')), privacy={'value': 'SELF'}) album_id = resp['id'] # album_id = '1482194405444590' graph_url = '{}/photos'.format(album_id) for fish in self.queryset: img_url = '{}{}'.format(settings.BASE_URL, fish.image.url) url = '{}{}'.format(settings.BASE_URL, reverse('fish_enlarge', args=[fish.pk])) resp = graph.set(graph_url, url=img_url, link=url)
def notify_bidders_thread(**kwargs): auction = kwargs['auction'] text = '' if kwargs['signal'] == 'auction_started': text = u'The auction for a {item} has started. Hurry and go win it!.'.format( item=auction.item.name) if kwargs['signal'] == 'precap_finishing': text = u'The auction for a {item} is about to start. Go play for it!.'.format( item=auction.item.name) for member in auction.bidders.all(): of = OpenFacebook(member.access_token) args = { 'template': text, 'access_token': FacebookAuthorization.get_app_access_token() } destination = '{facebook_id}/notifications'.format( facebook_id=member.facebook_id) response = of.set(destination, **args)
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 share_new_subscribed_story_on_facebook(user, user_followed, facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_account_id != None: if user.settings.facebook_page_connection_flag == True: story_api_url = str( user.settings.facebook_page_id) + '/yapster_fb:followed' elif user.settings.facebook_page_connection_flag == False: story_api_url = str( user.settings.facebook_account_id) + '/yapster_fb:followed' name = str(user_followed.first_name) + ' ' + str( user_followed.last_name) + ' (@' + str( user_followed.username.encode('utf-8') + ')') url = "http://yapster.co" b = connect_s3(bucket_name="yapsterapp") if user_followed.profile.profile_picture_flag == True: user_followed_picture_key = b.get_key( user_followed.profile.profile_picture_cropped_path) user_followed_picture_url = user_followed_picture_key.generate_url( expires_in=600) elif user_followed.profile.profile_picture_flag == False: user_followed_picture_url = None if user.settings.facebook_page_connection_flag == True: object_api_url = str( user.settings.facebook_page_id) + '/objects/yapster_fb:user' elif user.settings.facebook_page_connection_flag == False: object_api_url = str( user.settings.facebook_account_id) + '/objects/yapster_fb:user' description = 'Check out what @' + str(user.username) + ' and @' + str( user_followed.username ) + ' have been yapping about and listening to!' user_followed_object = facebook.set(object_api_url, object={ "url": url, "image": user_followed_picture_url, "title": name })['id'] fb_share = facebook.set(story_api_url, user=user_followed_object)['id'] return fb_share else: return "User has not set up a facebook_account_id."
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 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 share_yap_on_facebook(user, facebook_access_token, yap): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: if user.settings.facebook_account_id != None: name = str(yap.user.first_name) + ' ' + str( yap.user.last_name) + " (@" + str( user.username) + ") posted a yap on Yapster" if user.settings.facebook_page_connection_flag == True: api_url = str(user.settings.facebook_page_id) + '/feed' elif user.settings.facebook_page_connection_flag == False: api_url = str(user.settings.facebook_account_id) + '/feed' url = "http://web.yapster.co/yap/" + str(yap.pk) b = connect_s3(bucket_name="yapster") if yap.picture_flag == True: yap_picture_key = b.get_key(yap.picture_cropped_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) elif yap.picture_flag == False: yap_picture_key = b.get_key(user.profile.profile_picture_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) if yap.description != None: fb_share_yap_message = "\"" + str( yap.title.encode('utf-8')) + "\" - " + str( yap.description) + " " + "\n" + str(url) elif yap.description == None: fb_share_yap_message = "\"" + str( yap.title.encode('utf-8')) + "\" " + str(url) fb_share_yap_description = "Listen to this yap - and other yaps from " + str( user.first_name) + " " + str(user.last_name) fb_share_yap = facebook.set(api_url, link=url, picture=yap_picture_url, name=name, description=fb_share_yap_description, message=fb_share_yap_message)['id'] return fb_share_yap else: return "User has not set up a facebook_account_id." else: return "User has not connected their account with Facebook."
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
# -*- 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
profile = request.user.get_profile() access_token = getattr(profile, 'access_token', None) if not access_token: if raise_: message = 'Couldnt find an access token in the request or the users profile' raise open_facebook_exceptions.OAuthException(message) else: return None else: if raise_: message = 'Couldnt find an access token in the request or cookies' raise open_facebook_exceptions.OAuthException(message) else: return None graph = OpenFacebook(access_token, parsed_data, expires=expires) #add user specific identifiers if request: _add_current_user_id(graph, request.user) return graph def _add_current_user_id(graph, user): ''' set the current user id, convenient if you want to make sure you fb session and user belong together ''' if graph: graph.current_user_id = None
profile = request.user.get_profile() access_token = getattr(profile, 'access_token', None) if not access_token: if raise_: message = 'Couldnt find an access token in the request or the users profile' raise open_facebook_exceptions.OAuthException(message) else: return None else: if raise_: message = 'Couldnt find an access token in the request or cookies' raise open_facebook_exceptions.OAuthException(message) else: return None graph = OpenFacebook(access_token, signed_data, expires=expires) # add user specific identifiers if request: _add_current_user_id(graph, request.user) return graph def _add_current_user_id(graph, user): ''' set the current user id, convenient if you want to make sure you fb session and user belong together ''' if graph: graph.current_user_id = None
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