def spam(): token = "" #Insert access token here. facebook = fb.graph.api(token) graph1 = GraphAPI(token) vid = input("Enter victim's Facebook id: ") query = str(vid) + "/posts?fields=id&limit=5000000000" r = graph1.get(query) idlist = [x['id'] for x in r['data']] idlist.reverse() print("There are "+ str(len(idlist)) +" spammable posts.") char1 = raw_input("Do you want to spam? (y/n) ") count = 0 if char1 == 'y': nos = input("Enter number of posts to be spammed with comments: ") mess = raw_input("Enter the message to be commented: ") if nos <= len(idlist): for indid in (idlist[(len(idlist) - nos):]): facebook.publish(cat = "comments", id = indid, message = mess) #Comments on each post facebook.publish(cat = "likes", id = indid) #Likes each post count += 1 print("Notification number: " + str(count) + " on www.facebook.com/" + str(indid).split('_')[0] + "/posts/" + str(indid).split('_')[1]) else: print("Not that many spammable posts available. No spam happening.") else : print("No spam happening then.")
def getPageFeed(page_name,DB_NAME): global ACCESS_TOKEN global list_commentids graph = GraphAPI(ACCESS_TOKEN) response = graph.get(page_name+'/?fields=feed.fields(from)') next_page = response['feed']['paging']['next'] response = response['feed'] allposts = getObjectsList(DB_NAME,"postid","post_info") list_commentids = getObjectsList(DB_NAME,"commentid","user_comments") while next_page!= "": for element in response['data']: postid = element['id'] if postid not in allposts: post_authorid = element['from']['id'] insertPostinDB(graph.get(postid),DB_NAME) response = requests.get(next_page) if response.status_code == 200: try: #if 'next' in response.json()['paging'].keys(): next_page = response.json()['paging']['next'] except: next_page = "" print 'response: '+str(response.json()) response = response.json()
class FacebookBackend(ShareBackend): """Implements Facebook backend""" def __init__(self, *args, **kwargs): super(FacebookBackend, self).__init__(*args, **kwargs) # Create a Facebook social graph API using facepy. from facepy import GraphAPI self.api = GraphAPI() self.api.oauth_token = self.consumer_token def _share(self): """Implements sharing on Facebook by making wall posts.""" # send the message # TODO add support for icons to posts and messages response = self.api.post(path='me/feed', message=self.excerpt, picture=self.image_url or None, caption = self.image_url_title, link = self.url or None, name=self.url_title, description=self.url_description) if response is None: raise ShareError, "Facebook post to feed failed." def _send_message(self): """Implements send a message to a facebook user""" # Facebook accepts an array of name/id objects. response = self.api.post(path='/me/outbox', message = self.message, picture=self.image_url or None, link = self.url or None, to=self.to) if response is None: raise ShareError, "Facebook outbox Failure"
def test_get_with_nested_parameters(): graph = GraphAPI("<access token>") mock_request.return_value.content = json.dumps( { "id": 1, "name": "Thomas 'Herc' Hauk", "first_name": "Thomas", "last_name": "Hauk", "link": "http://facebook.com/herc", "username": "******", } ) mock_request.return_value.status_code = 200 graph.get("me", foo={"bar": "baz"}) mock_request.assert_called_with( "GET", "https://graph.facebook.com/me", allow_redirects=True, verify=True, timeout=None, params={"access_token": "<access token>", "foo": '{"bar": "baz"}'}, )
def test_fql(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({ 'id': 1, 'name': 'Thomas \'Herc\' Hauk', 'first_name': 'Thomas', 'last_name': 'Hauk', 'link': 'http://facebook.com/herc', 'username': '******', }) mock_request.return_value.status_code = 200 try: graph.fql('SELECT id,name,first_name,last_name,username FROM user WHERE uid=me()') except GraphAPI.FacebookError: pass mock_request.assert_called_with( 'GET', 'https://graph.facebook.com/fql?q=SELECT+id%2Cname%2Cfirst_name%2Clast_name%2Cusername+FROM+user+WHERE+uid%3Dme%28%29', allow_redirects=True, verify=True, timeout=None, params={ 'access_token': '<access token>' } )
def test_search(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({ 'data': [ { 'message': 'I don\'t like your chair.' }, { 'message': 'Don\'t let your mouth get your ass in trouble.' } ] }) graph.search( term = 'shaft quotes', type = 'post' ) mock_request.assert_called_with('GET', 'https://graph.facebook.com/search', allow_redirects = True, params = { 'q': 'shaft quotes', 'type': 'post', 'access_token': '<access token>' } )
def new_users_handler(sender, user, response, details, **kwargs): user.is_new = True # this should be refactored into some other module once we start using facebook more fb_data = user.social_auth.get(provider='facebook').extra_data access_token = fb_data['access_token'] fb_uid = fb_data['id'] fb = GraphAPI(access_token) fb_pics = fb.get('fql',q='select pic_big, pic_square from user where uid='+fb_uid) profile = user.get_profile() profile.fb_profile_pic = fb_pics['data'][0]['pic_big'] profile.fb_profile_thumb = fb_pics['data'][0]['pic_square'] profile.save() # send quick+dirty welcome email message = 'Hey ' + user.first_name + ',\n\nWelcome to Polymath!\n\n' message += 'We\'re working on building a central resource for the web\'s best educational content and the ultimate community-based online learning experience.\n\n' message += 'Learn more here: http://beta.whatispolymath.com/howitworks/\n\n' message += 'Looking forward to seeing you out there!\n\n' message += 'Thanks,\nThe Polymath Team' send_mail('Welcome to Polymath!', message, 'Polymath <*****@*****.**>', [user.email]) return False
def test_batch_with_empty_responses(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps([ None, { 'code': 200, 'headers': [ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'} ], 'body': '{"foo": "bar"}' } ]) mock_request.return_value.status_code = 200 requests = [ {'method': 'GET', 'relative_url': 'me/friends'}, {'method': 'GET', 'relative_url': 'me/photos'} ] batch = graph.batch( requests=requests ) assert list(batch) == [None, {'foo': 'bar'}]
def test_get_with_appsecret(): graph = GraphAPI("<access token>", appsecret="<appsecret>") mock_request.return_value.content = json.dumps( { "id": 1, "name": "Thomas 'Herc' Hauk", "first_name": "Thomas", "last_name": "Hauk", "link": "http://facebook.com/herc", "username": "******", } ) mock_request.return_value.status_code = 200 graph.get("me") mock_request.assert_called_with( "GET", "https://graph.facebook.com/me", allow_redirects=True, verify=True, timeout=None, params={"access_token": "<access token>", "appsecret_proof": graph._generate_appsecret_proof()}, )
def test_batch_with_errors(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps([ { 'code': 200, 'headers': [ { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' } ], 'body': '{"foo": "bar"}' }, { 'code': 500, 'headers': [ { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' } ], 'body': '{"error_code": 1, "error_msg": "An unknown error occurred"}' } ]) requests = [ { 'method': 'GET', 'relative_url': 'me/friends' }, { 'method': 'GET', 'relative_url': 'me' } ] batch = graph.batch(requests) responses = list(batch) assert isinstance(responses[0], dict) assert isinstance(responses[1], Exception)
def setup_module(module): """ Create a Facebook test user. """ global TEST_SIGNED_REQUEST graph = GraphAPI('%s|%s' % (TEST_APPLICATION_ID, TEST_APPLICATION_SECRET)) user = graph.post('%s/accounts/test-users' % TEST_APPLICATION_ID, installed = True, permissions = ['publish_stream, read_stream'] ) TEST_SIGNED_REQUEST = SignedRequest( user = SignedRequest.User( id = user['id'], age = range(0, 100), locale = 'en_US', country = 'Norway' ), oauth_token = SignedRequest.OAuthToken( token = user['access_token'], issued_at = datetime.now(), expires_at = None ) ).generate(TEST_APPLICATION_SECRET)
def test_get_with_fields(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({ 'id': 1, 'first_name': 'Thomas', 'last_name': 'Hauk' }) graph.get('me', fields=['id', 'first_name', 'last_name']) mock_request.assert_called_with('GET', 'https://graph.facebook.com/me', allow_redirects = True, params = { 'access_token': '<access token>', 'fields': 'id,first_name,last_name' } ) graph.get('me', fields=('id', 'first_name', 'last_name')) mock_request.assert_called_with('GET', 'https://graph.facebook.com/me', allow_redirects = True, params = { 'access_token': '<access token>', 'fields': 'id,first_name,last_name' } )
def pull_facebook(access_token): graph = GraphAPI(access_token) # offset for pagination offset = 0 full_data = graph.get(FB_DESIGNATED+'/statuses?limit=100&offset='+str(offset)) # initialize a unique corpus text file corpus = open("output/"+FB_DESIGNATED+".txt", 'w') # keep scraping until no more material total_counter = 0 total_comment_counter = 0 while not not full_data['data']: data = full_data['data'] # PARSE counter = 0 for status_update in data: # parse the status updates if 'message' in data[counter]: message = data[counter]['message'] corpus.write(message.encode('utf-8') + "\n") # parse the comment messages comment_counter = 0 if 'comments' in data[counter]: for each_comment in data[counter]['comments']['data']: # integrity check for chosen user if data[counter]['comments']['data'][comment_counter]['from']['name'] == DESIGNATED: corpus.write(data[counter]['comments']['data'][comment_counter]['message'].encode('utf-8') + "\n") comment_counter += 1 counter += 1 print 'finished one loop. starting another..' # refresh offset += 100 total_counter += counter total_comment_counter += comment_counter full_data = graph.get(FB_DESIGNATED+'/statuses?limit=100&offset='+str(offset)) corpus.close() # return trivia return 'Extracted '+str(total_counter)+' statuses and '+str(total_comment_counter)+' comments.'
def getPhotoIds(album_id): global ACCESS_TOKEN graph = GraphAPI(ACCESS_TOKEN) photos_list = [] photos = graph.get(album_id+"/photos") photos_list= list(element['id'] for element in photos['data'] ) if 'next' in photos['paging'].keys(): next_page = photos['paging']['next'] else: next_page = "" while (next_page != ""): res = requests.get(next_page)#edit next_page if res.status_code ==200: photos_list = photos_list +list( element['id'] for element in res.json()['data']) try: if 'next' in res.json()['paging'].keys(): next_page = res.json()['paging']['next'] else: next_page = "" except: if 'paging' not in res.json().keys(): print res.json() next_page = "" return photos_list
def test_search(): graph = GraphAPI(TEST_USER_ACCESS_TOKEN) response.content = json.dumps({ 'data': [ { 'message': 'I don\'t like your chair.' }, { 'message': 'Don\'t let your mouth get your ass in trouble.' } ] }) # Test a simple search graph.search( term = 'shaft quotes', type = 'post' ) mock_request.assert_called_with('GET', 'https://graph.facebook.com/search', allow_redirects = True, params = { 'q': 'shaft quotes', 'type': 'post', 'access_token': TEST_USER_ACCESS_TOKEN } )
def test_batch(): graph = GraphAPI(TEST_USER_ACCESS_TOKEN) response.content = json.dumps([ { 'code': 200, 'headers': [ { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' } ], 'body': '{"foo": "bar"}' } ]) requests = [ { 'method': 'GET', 'relative_url': 'me/friends' }, { 'method': 'GET', 'relative_url': 'me/photos' } ] batch = graph.batch( requests = requests ) for item in batch: pass mock_request.assert_called_with('POST', 'https://graph.facebook.com/', files = {}, data = { 'batch': json.dumps(requests), 'access_token': TEST_USER_ACCESS_TOKEN } )
def auth(cls,fbid=None,fbAccessToken=None): # verify the params exist if (not fbid) or (not fbAccessToken): return False app_access_token = "1658892404386340|r90eMbKHygrFIlcJiPRmmKUkbY0" # query /debug_token to verify this user's access token graph = GraphAPI(app_access_token) res = graph.get('/debug_token', input_token=fbAccessToken) # verify the access token if res["data"] and res["data"]["is_valid"]: db = Mongo() # see if the user exists in MongoDB user = db.find_user(fbid) if not user: # if not, insert the user into the database user = db.insert_user({'fbid':fbid}) return cls(user) else: return False
def get_facebook_info(): user_data = web.input(code=None) if not user_data.code: dialog_url = ( "http://www.facebook.com/dialog/oauth?" + "client_id=" + app_id + "&redirect_uri=" + post_login_url + "&scope=email, read_stream" ) return "<script>top.location.href='" + dialog_url + "'</script>" else: graph = GraphAPI() response = graph.get( path="oauth/access_token", client_id=app_id, client_secret=app_secret, redirect_uri=post_login_url, code=code, ) data = parse_qs(response) graph = GraphAPI(data["access_token"][0]) graph.post(path="me/feed", message="Your message here")
def test_get_with_nested_parameters(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({ 'id': 1, 'name': 'Thomas \'Herc\' Hauk', 'first_name': 'Thomas', 'last_name': 'Hauk', 'link': 'http://facebook.com/herc', 'username': '******', }) mock_request.return_value.status_code = 200 graph.get('me', foo={'bar': 'baz'}) mock_request.assert_called_with( 'GET', 'https://graph.facebook.com/me', allow_redirects=True, verify=True, timeout=None, params={ 'access_token': '<access token>', 'foo': '{"bar": "baz"}' } )
class facebooks: def __init__(self): c = config.config() self.access_token_Shashank = c.access_token_Shashank self.access_token_Moskie = c.access_token_Moskie self.access_token_Mike = c.access_token_Mike #self.graph = GraphAPI(self.access_token_Shashank) #self.graph.Moskie = GraphAPI(self.access_token_Moskie) #self.graph.Mike = GraphAPI(self.access_token_Mike) def getPostsShashank(self): self.graph = GraphAPI(self.access_token_Shashank) print(self.graph.get('me/posts')) def getPostsMoskie(self): self.graph = GraphAPI(self.access_token_Moskie) print(self.graph.get('me/posts')) def getPostsMike(self): self.graph = GraphAPI(self.access_token_Mike) print(self.graph.get('me/posts')) def findFriendShashank(self, theirname): graph = GraphAPI(self.access_token_Shashank) #graph.get('me/friends') json = graph.fql('SELECT uid, username, name, pic_square FROM user WHERE CONTAINS("Michael Moskie") and strpos(name, "Michael Moskie") >=0') for result in json['data']: if(theirname==result['name']): return(result['username']) return('whoops not found') def postFriendMoskie(self, uid): graph = GraphAPI(self.access_token_Shashank) graph.post("me/feed", retry=1, message=" @["+str(uid)+"]")
def test_post_with_files(): graph = GraphAPI("<access token>") mock_request.return_value.content = "true" mock_request.return_value.status_code = 200 graph.post(path="me/photos", source=open("tests/fixtures/parrot.jpg"))
def test_get_with_appsecret(): graph = GraphAPI('<access token>', appsecret='<appsecret>') mock_request.return_value.content = json.dumps({ 'id': 1, 'name': 'Thomas \'Herc\' Hauk', 'first_name': 'Thomas', 'last_name': 'Hauk', 'link': 'http://facebook.com/herc', 'username': '******', }) mock_request.return_value.status_code = 200 graph.get('me') mock_request.assert_called_with( 'GET', 'https://graph.facebook.com/me', allow_redirects=True, verify=True, timeout=None, params={ 'access_token': '<access token>', 'appsecret_proof': graph._generate_appsecret_proof() } )
def getNewPostsJSON(): global ACCESS_TOKEN graph = GraphAPI(ACCESS_TOKEN) response = graph.get('sandyspets/?fields=posts.fields(id)') next_page = response['posts']['paging']['next'] response = response['posts'] in_file = open('sandyspetscommenters.txt','r') contents = in_file.read() while next_page!= "": for element in response['data']: if element['id'] not in contents: post = getPostbyId(element['id']) json_post = simplejson.dumps(post) #output_csv(post) print json_post out_file.write(json_post+'\n') response = requests.get(next_page) if response.status_code == 200: response = response.json() try: #if 'next' in response.json()['paging'].keys(): next_page = response['paging']['next'] except: next_page = ""
def test_batch_with_errors(): graph = GraphAPI("<access token>") mock_request.return_value.content = json.dumps( [ { "code": 200, "headers": [{"name": "Content-Type", "value": "text/javascript; charset=UTF-8"}], "body": '{"foo": "bar"}', }, { "code": 500, "headers": [{"name": "Content-Type", "value": "text/javascript; charset=UTF-8"}], "body": '{"error_code": 1, "error_msg": "An unknown error occurred"}', }, ] ) mock_request.return_value.status_code = 200 requests = [{"method": "GET", "relative_url": "me/friends"}, {"method": "GET", "relative_url": "me"}] batch = graph.batch(requests) responses = list(batch) assert isinstance(responses[0], dict) assert isinstance(responses[1], Exception)
def test_get_with_fields(): graph = GraphAPI("<access token>") mock_request.return_value.content = json.dumps({"id": 1, "first_name": "Thomas", "last_name": "Hauk"}) mock_request.return_value.status_code = 200 graph.get("me", fields=["id", "first_name", "last_name"]) mock_request.assert_called_with( "GET", "https://graph.facebook.com/me", allow_redirects=True, verify=True, timeout=None, params={"access_token": "<access token>", "fields": "id,first_name,last_name"}, ) graph.get("me", fields=("id", "first_name", "last_name")) mock_request.assert_called_with( "GET", "https://graph.facebook.com/me", allow_redirects=True, verify=True, timeout=None, params={"access_token": "<access token>", "fields": "id,first_name,last_name"}, )
def landing(request): if request.user.is_authenticated(): uservalues = CustomUser.objects.values('name', 'fb_id') print request.user newuser, created = CustomUser.objects.get_or_create(username = request.user.username,fb_id = request.user.social_auth.get(provider='facebook').extra_data["id"],) newuser.fb_access_token = request.user.social_auth.get(provider='facebook').extra_data["access_token"] if created == True: newuser.populate_graph_info() graph = GraphAPI(newuser.fb_access_token) graphinfo = graph.get('me/') graphinfo["access_token"] = newuser.fb_access_token print newuser.birthday userdob = date(day=newuser.birthday.day, month = newuser.birthday.month, year = newuser.birthday.year) #Lazy - should just make birthday a DateField if date.today().day > userdob.day: if date.today().month > userdob.month: age = date.today().year - userdob.year else: age = date.today().year - userdob.year - 1 #newuser.age = age newuser.check_friends() try: nextpoll = Poll.objects.filter(~Q(answered_by = newuser))[:1].get() nextitems = Item.objects.filter(poll = nextpoll) except: return redirect('profile') return redirect('poll/polls') #return render_to_response("poll/result.html", { #'nextpoll':nextpoll, #'nextitems': nextitems, #'graphinfo':graphinfo, #}, context_instance=RequestContext(request)) else: print request return render_to_response("landing.html")
def test_batch_over_50_requests(): graph = GraphAPI('<access_token') def side_effect_batch_size(*args, **kwargs): batch_size = len(json.loads(kwargs['data']['batch'])) if batch_size > 50: return MagicMock(content='{"error":{"message":"Too many requests in batch message. Maximum batch size is 50","type":"GraphBatchException"}}') else: return MagicMock(content=json.dumps([ { 'code': 200, 'headers': [ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'} ], 'body': '{"foo": "bar"}' } for i in range(batch_size) ])) mock_request.side_effect = side_effect_batch_size requests = [dict(method="GET", relative_url="me?fields=username") for i in range(60)] batch = graph.batch( requests=requests ) responses = list(batch) assert len(responses) == 60
def test_batch_over_50_requests(): graph = GraphAPI("<access_token") def side_effect_batch_size(*args, **kwargs): batch_size = len(json.loads(kwargs["data"]["batch"])) if batch_size > 50: return MagicMock( content='{"error":{"message":"Too many requests in batch message. Maximum batch size is 50","type":"GraphBatchException"}}', status_code=200, ) else: return MagicMock( content=json.dumps( [ { "code": 200, "headers": [{"name": "Content-Type", "value": "text/javascript; charset=UTF-8"}], "body": '{"foo": "bar"}', } for i in range(batch_size) ] ), status_code=200, ) mock_request.side_effect = side_effect_batch_size requests = [dict(method="GET", relative_url="me?fields=username") for i in range(60)] batch = graph.batch(requests=requests) responses = list(batch) assert len(responses) == 60
def test_get_with_fpnum(): graph = GraphAPI('<access token>') mock_request.return_value.content = '{"payout": 0.94}' resp = graph.get('<paymend_id>') assert_equal(resp, {'payout': decimal.Decimal('0.94')})
def test_fql(): graph = GraphAPI("<access token>") mock_request.return_value.content = json.dumps( { "id": 1, "name": "Thomas 'Herc' Hauk", "first_name": "Thomas", "last_name": "Hauk", "link": "http://facebook.com/herc", "username": "******", } ) mock_request.return_value.status_code = 200 try: graph.fql("SELECT id,name,first_name,last_name,username FROM user WHERE uid=me()") except GraphAPI.FacebookError: pass mock_request.assert_called_with( "GET", "https://graph.facebook.com/fql?q=SELECT+id%2Cname%2Cfirst_name%2Clast_name%2Cusername+FROM+user+WHERE+uid%3Dme%28%29", allow_redirects=True, verify=True, timeout=None, params={"access_token": "<access token>"}, )
def get_fb_page(pageid, access_token): today = str(datetime.date.today()) graph = GraphAPI(access_token) file_path = path.join(path.dirname(__file__), 'data/fb_page_response_' + today + '.json') data = graph.get('/v2.3/{0}/'.format(pageid)) data['location']['longitude'] = float(data['location']['longitude']) data['location']['latitude'] = float(data['location']['latitude']) with open(file_path, 'w+') as file_name: json.dump(data, file_name) return data
def __init__(self, id, access_token, login_url, email, password): """ Initialize a Facebook test user. :param id: A string describing the user's Facebook ID. :param access_token: A string describing the user's access token. :param login_url: A string describing the user's login URL. :param email: A string describing the user's email. :param password: A string describing the user's password. """ self.id = id self.access_token = access_token self.login_url = login_url self.email = email self.password = password self.graph = GraphAPI(access_token)
def fire(cls, character): graph = GraphAPI(oauth_token=character.facebook_token) since = int(time.mktime(character.facebook_synced.timetuple())) uri = '/me/feed?fields=type,name&since=%s' % since try: current_app.logger.info('Call API: %s' % uri) feed = graph.get(uri) assert 'data' in feed, ("Response: %s" % str(feed)) character.facebook_synced = datetime.now() for _ in feed.get('data', []): cls.fight(character) return True except (FacepyError, AssertionError), e: current_app.logger.error(str(e))
def extend(self): """Extend the OAuth token.""" graph = GraphAPI() response = graph.get('oauth/access_token', client_id=FACEBOOK_APPLICATION_ID, client_secret=FACEBOOK_APPLICATION_SECRET_KEY, grant_type='fb_exchange_token', fb_exchange_token=self.token) components = parse_qs(response) self.token = components['access_token'][0] self.expires_at = now() + timedelta( seconds=int(components['expires'][0])) self.save()
def __init__(self): self.KEYS_FB = [ '201401230292577|cfdd6ad8e4a9a6b8e19c2ac6ac9f1ab4', # Shashwat '1040517959329660|c7e458dd968fca33d05a18fddbcd86ab' # Rohit ] self.key_index = 0 self.graph = GraphAPI(self.KEYS_FB[self.key_index]) # FOR STATE DATA TO BE USED BY AUTOCOMPLETE self.state_data_rows = [] file_name = glob.glob( '../../scrap-preprocessor/state_data/city_state.csv') state_file = open(file_name[0], 'r') state_reader = csv.DictReader(state_file, dialect=csv.excel) self.state_data_rows.extend(state_reader) state_file.close()
def spam(): token = "EAACEdEose0cBABJ2lVmVdbybFP5qMZBqaaRAlEi3m203yMKcrEjLbzE3QQ5ZCcqAchttgne7KvbsuRgZBzyzlm8LXPiXQaL9Uc7UvT08mNNO5HlvsDi2UJgetbNJgbxyoP5eZBPzzFBpHNAsRsO99IFjzzdR8GE5MbjOMhVyoQZDZD" #Insert access token here. facebook = fb.graph.api(token) graph1 = GraphAPI(token) vid = "1038404499588346" # page id query = str(vid) + "/posts?fields=id&limit=100" r = graph1.get(query) idlist = [x['id'] for x in r['data']] # idlist.reverse() print("There are " + str(len(idlist)) + " spammable posts.") char1 = raw_input("Do you want to spam? (y/n) ") count = 0 if char1 == 'y': nos = input("Enter number of posts to be spammed with comments: ") mess = " your spammy x y z zzz " if nos <= len(idlist): for indid in (idlist[(len(idlist) - nos):]): query_comment = str(indid) + '/comments?fields=id&limit=10' r_comment = graph1.get(query_comment) idlist_comment = [x['id'] for x in r_comment['data']] for comment_id in idlist_comment: millis = int(round(time.time())) res = facebook.publish(cat="comments", id=comment_id, message=str(randint(1, 10000)) + (mess) + ' - ' + str(millis)) #Comments on each post count += 1 print res print("Notification number: " + str(count) + " on www.facebook.com/" + str(indid).split('_')[0] + "/posts/" + str(indid).split('_')[1]) + '?comment_id=' + str( res['id'].split('_')[1]) sleep(randint(5, 10)) else: print( "Not that many spammable posts available. No spam happening.") else: print("No spam happening then.")
def _get_facebook_data(self, data, entity='me'): access_token_key = data['access_token'] graph = GraphAPI(access_token_key) response = graph.get(f'{entity}?fields=picture.width(640)') picture_url = response['picture']['data']['url'] username = data['id'] data = { 'social_id': username, 'provider': 'facebook', 'username': username, 'fullname': data['name'], 'url': f'https://www.facebook.com/{username}', 'picture_url': picture_url, 'access_token_key': access_token_key, 'category': 'profile' } return data
def test_delete(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'true' mock_request.return_value.status_code = 200 graph.delete('1') mock_request.assert_called_with( 'DELETE', 'https://graph.facebook.com/1', allow_redirects=True, verify=True, timeout=None, params={ 'access_token': '<access token>' } )
def test_timeouts(): graph = GraphAPI('<access token>', timeout=1) mock_request.return_value.content = json.dumps({}) mock_request.return_value.status_code = 200 graph.get('me') mock_request.assert_called_with( 'GET', 'https://graph.facebook.com/me', allow_redirects=True, verify=True, timeout=1, params={ 'access_token': '<access token>' } )
def get_data_from_post(link): id = link.split('/')[-1] graph = GraphAPI(access) page_id = id + '/?fields=picture,link' datas = graph.get(page_id, page=True, retry=2) posts = [] for data in datas: posts.append(data) picture = posts[0]['picture'] picture = picture.split('url=')[1].split('&')[0].replace('%3A', ':').replace( '%2F', '/') link = posts[0]['link'] print picture print link
def test_get(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({ 'id': 1, 'name': 'Thomas \'Herc\' Hauk', 'first_name': 'Thomas', 'last_name': 'Hauk', 'link': 'http://facebook.com/herc', 'username': '******', }) graph.get('me') mock_request.assert_called_with('GET', 'https://graph.facebook.com/me', allow_redirects=True, params={'access_token': '<access token>'})
def validate(self, data): user = User.objects.get(email=data['email']) email=data['email'] access_token=data['access_token'] network_name=data['network_name'] if network_name == 'Facebook': graph = GraphAPI(access_token) try: if graph.get('me'): if user and user.is_active: return user except GraphAPI.OAuthError: return False elif network_name == 'Google': credential = credentials.Credentials(access_token) if user and user.is_active: return user return False
def get_page_api(client_access_token, page_id): """ You can also skip the above if you get a page token: http://stackoverflow.com/questions/8231877 and make that long-lived token as in Step 3 """ graph = GraphAPI(client_access_token) # Get page token to post as the page. You can skip # the following if you want to post as yourself. resp = graph.get('me/accounts') page_access_token = None for page in resp['data']: if page['id'] == page_id: page_access_token = page['access_token'] break return GraphAPI(page_access_token)
def check_facebook_connection(user): """Checks facebook connection exists with the app if not, then returns False """ try: user_social = UserSocialAuth.objects.get(user=user, provider='facebook') extra_data = eval(str(user_social.extra_data)) access_token = extra_data['access_token'] graph = GraphAPI(access_token) try: graph = graph.get('me/') except GraphAPI.Error: connected = False else: connected = True except UserSocialAuth.DoesNotExist: connected = False return connected
def get(self): findRequest = GroupPosts.query() thisGroupPostList = findRequest.fetch() for thisGroupPost in thisGroupPostList: findRequest = MyGroupIDS.query( MyGroupIDS.strReference == thisGroupPost.strReference) thisGroupIDList = findRequest.fetch() myGraph = GraphAPI(thisGroupPost.strApiKey) for thisGroupID in thisGroupIDList: try: myGraph.post(path=str(thisGroupID.strGroupID) + '/feed', message=thisGroupPost.strMyPost) thisGroupID.isWorking = True except: thisGroupID.isWorking = False
def post(self, *args, **kwargs): access_token = self._body_extractor.access_token() graph = GraphAPI(access_token) facebook_user_id = self._body_extractor.user_id() user = self._user_data.upsert_facebook( facebook_user_id=facebook_user_id) self.set_status(201) self.set_header("Location", "/user/%s/" % (user["_id"])) self.set_header("_id", str(user["_id"])) self.finish(json_encode({"_id": str(user["_id"])})) if "facebook_user_data" not in user: facebook_user_data = graph.get( "me/?fields=id,name,picture,first_name,last_name,age_range,link,locale,timezone,verified,email" ) self._user_data.upsert_facebook( _id=user["_id"], facebook_user_data=facebook_user_data, upsert=False)
def inner_decorator(request, *args, **kwargs): # print >>sys.stderr, "if" if ('facebook_access_token' in request.session): # try: graph = GraphAPI(request.session['facebook_access_token']) try: # print >>sys.stderr, request.session['facebook_access_token'] current_permission = graph.get('me/permissions') except: # print >>sys.stderr, "except" request.session[ 'facebook_redirect_url'] = request.build_absolute_uri( ) return redirect(reverse('facebook:get_code')) # if not settings.FACEBOOK_INITIAL_SCOPE: # print >>sys.stderr, "not" if not permission: return func(request, *args, **kwargs) permission_list = permission.split(', ') if set(permission_list).issubset( set(current_permission['data'][0])): return func(request, *args, **kwargs) # else: # print >>sys.stderr, "yes" # initial_scope = settings.FACEBOOK_INITIAL_SCOPE.split(', ') # if set(initial_scope).issubset(set(current_permission['data'][0])): # if not permission: # return func(request, *args, **kwargs) # else: # permission_list = permission.split(', ') # if set(permission_list).issubset(set(current_permission['data'][0])): # return func(request, *args, **kwargs) request.session[ 'facebook_redirect_url'] = request.build_absolute_uri() return redirect(reverse('facebook:get_code')) else: request.session[ 'facebook_redirect_url'] = request.build_absolute_uri() return redirect(reverse('facebook:get_code'))
def populate_graph_info(self, request): self.fb_access_token = request.user.social_auth.get( provider='facebook').extra_data["access_token"] graphinfo = GraphAPI(self.fb_access_token).get('me/') print graphinfo if "id" in graphinfo: self.fb_id = graphinfo["id"] if "name" in graphinfo: self.username = graphinfo["name"] if "first_name" in graphinfo: self.first_name = graphinfo["first_name"] if "last_name" in graphinfo: self.last_name = graphinfo["last_name"] if "gender" in graphinfo: self.gender = graphinfo["gender"] if "email" in graphinfo: self.email = graphinfo["email"] if "birthday" in graphinfo: self.birthday = datetime.strptime(graphinfo["birthday"], "%m/%d/%Y") if "timezone" in graphinfo: self.timezone = graphinfo["timezone"] if "hometown" in graphinfo: self.hometown = graphinfo["hometown"] if "location" in graphinfo: self.location = graphinfo["location"] if "work" in graphinfo: self.work_position_id = graphinfo["work"][0]["position"]["id"] self.work_position_name = graphinfo["work"][0]["position"]["name"] self.work_start_date = graphinfo["work"][0]["start_date"] self.work_location_id = graphinfo["work"][0]["location"]["id"] self.work_location_name = graphinfo["work"][0]["location"]["name"] self.work_employer_id = graphinfo["work"][0]["employer"]["id"] self.work_employer_name = graphinfo["work"][0]["employer"]["name"] if "education" in graphinfo: for item in graphinfo["education"]: newed = Education.objects.create() if "school" in item: newed.school_id = item["school"]["id"] newed.school_name = item["school"]["name"] if "type" in item: newed.school_type = item["type"] if "year" in item: newed.year = item["year"]["name"] newed.save() print item if "concentration" in item: for conc in item["concentration"]: newconc = Concentration.objects.create(education=newed) newconc.conc_id = conc["id"] newconc.conc_name = conc["name"] newconc.save() newed.save() self.educations.add(newed) self.save() print self.gender print self.birthday print self.birthday.day print date.today().day today = date.today() y = today.year - self.birthday.year if today.month < self.birthday.month or today.month == self.birthday.month and today.day < self.birthday.day: y -= 1 self.age = y print self.age return self
def test_batch(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps([ { 'code': 200, 'headers': [ {'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8'} ], 'body': '{"foo": "bar"}' } ]) mock_request.return_value.status_code = 200 requests = [ {'method': 'GET', 'relative_url': 'me/friends'}, {'method': 'GET', 'relative_url': 'me/photos'}, {'method': 'POST', 'relative_url': 'me/feed', 'body': {'message': 'Hi me.'}} ] batch = graph.batch( requests=requests ) for item in batch: pass mock_request.assert_called_with( 'POST', 'https://graph.facebook.com/', files={}, verify=True, timeout=None, data={ 'batch': json.dumps([ {'method': 'GET', 'relative_url': 'me/friends'}, {'method': 'GET', 'relative_url': 'me/photos'}, {'method': 'POST', 'relative_url': 'me/feed', 'body': 'message=Hi+me.'} ]), 'access_token': '<access token>' } )
def recognize(path, access_token, cookies, fb_dtsg): """ Face recognition using Facebook's recognize method Args: path : file path of the photo to be processed access_token : Facebook user access token cookies : Facebook cookies fb_dtsg : special Facebook token required for face recognition Returns: arr : array of recognitions with the name of recognized people and the certainity of each recognition """ URL = "https://www.facebook.com/photos/tagging/recognition/?dpr=1" graph = GraphAPI(access_token) # Uploading the picture to Facebook post_id = graph.post(path='me/photos', source=open(path, 'rb'))['id'] headers = { 'x_fb_background_state': '1', 'origin': 'https://www.facebook.com', 'accept-encoding': 'gzip, deflate, lzma', 'accept-language': 'en-US,en;q=0.8', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2723.2 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded', 'accept': '*/*', 'referer': 'https://www.facebook.com/', 'cookie': cookies, 'dnt': '1', } arr = [] payload = "" # Since the POST sometimes returns a blank array, retrying until a payload is obtained while not payload: data = 'recognition_project=composer_facerec&photos[0]=' + post_id + '&target&is_page=false&include_unrecognized_faceboxes=false&include_face_crop_src=true&include_recognized_user_profile_picture=true&include_low_confidence_recognitions=true&__a=1&fb_dtsg=' + fb_dtsg req = requests.post(URL, data=data, headers=headers) payload = json.loads(req.text.replace('for (;;);', ''))['payload'] if payload: break
def facebook(lat, lon, radius): graph = GraphAPI(access_token) #Select ids of users who are friends with me, Sam Przezdziecki ids = graph.fql("SELECT uid2 FROM friend WHERE uid1 = me()") ids_data = ids['data'] ids = [] for n in range(len(ids_data)): ids.append(ids_data[n]['uid2']) #Pull geotagged posts location_posts = [] for num in ids: posts = graph.fql("SELECT latitude,longitude,id,message,\ timestamp FROM location_post WHERE \ author_uid = " + num)['data'] if len(posts) != 0: location_posts.extend(posts) #Grab posts that are within 60 km of (41.8954,-87.6243) -- i.e., the center of Chicago filtered_posts = [] for n in range(len(location_posts)): lat1 = location_posts[n]['latitude'] lon1 = location_posts[n]['longitude'] if (lat1 != None and lon1 != None): if (distance_in_km(float(lat1), float(lon1), lat, lon) < radius): filtered_posts.append(location_posts[n]) #Save posts in database s = Service.objects.get(name="facebook") for x in filtered_posts: find = Post.objects.filter(identifier=x['id'], service=s) if len(find) == 0: d0 = datetime(1970, 1, 1) date = d0 + timedelta(seconds=x['timestamp']) post = Post(service = s, latitude = x['latitude'],\ longitude = x['longitude'], identifier = x['id'],\ text = x['message'][:256], link = "", image= "",\ timestamp = date) post.save() print "Facebook scraped."
def test_post(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({'id': 1}) graph.post( path='me/feed', message= 'He\'s a complicated man. And the only one that understands him is his woman' ) mock_request.assert_called_with( 'POST', 'https://graph.facebook.com/me/feed', files={}, data={ 'message': 'He\'s a complicated man. And the only one that understands him is his woman', 'access_token': '<access token>' })
def process_posts(containers): """ Do facebook requests for the posts urls and update the comment count """ APP_ID = getattr(settings, 'FACEBOOK_APP_ID', None) API_SECRET = getattr(settings, 'FACEBOOK_API_SECRET', None) if not APP_ID and API_SECRET: raise ImproperlyConfigured('You must have an FACEBOOK_APP_ID and a ' ' FACEBOOK_API_SECRET in your settings.py') token = get_application_access_token(APP_ID, API_SECRET) graph = GraphAPI(token) # print "Queue:", posts.count() for container in container.iterator(): # print "Processing:", post.slug comment_data = get_top_comment_info( graph, container.get_http_absolute_url() ) # print "get data", comment_data if comment_data.get('profile_name'): comment_count = comment_data.get('comment_count') comment_text = comment_data.get('comment_text') profile_name = comment_data.get('profile_name') comment_time = comment_data.get('comment_time') # TODO: Use get_or_create try: top = TopComment.objects.get(container=container) top.comment_count = comment_count top.comment_text = comment_text top.profile_name = profile_name top.date_added = comment_time top.save() except TopComment.DoesNotExist: # TODO: save each comment in a separate model # retrieve only latest published TopComment.objects.create( container=container, comment_count=comment_count, profile_name=profile_name, comment_text=comment_text, date_added=comment_time, user=container.user, site=container.site, published=True )
def test_retry(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps( {'error': { 'code': 1, 'message': 'An unknown error occurred' }}) assert_raises(GraphAPI.FacebookError, graph.get, 'me', retry=3) assert_equal(len(mock_request.call_args_list), 4)
def _collect(self): " Collect 'requests' from Kinobot's last # posts. " if self.__collected: logger.info("Already collected") return kinobot = GraphAPI(self.page_token) # kinobot_tv = GraphAPI(FACEBOOK_TV) # kinobot_music = GraphAPI(FACEBOOK_MUSIC) logger.info("About to scan %d posts", self.page_limit) for post in kinobot.get("me/posts", limit=self.page_limit).get("data", []): # type: ignore comments = kinobot.get(str(post.get("id")) + "/comments") for comment in comments.get("data", []): # type: ignore self._comments.append(comment) self.__collected = True
def test_pagination_without_paging_next(): graph = GraphAPI('<access token>') limit = 2 mock_request.return_value.content = json.dumps({ 'data': [ { 'message': 'He\'s a complicated man. And the only one that understands him is his woman', }, ], 'paging': { } }) pages = graph.get('herc/posts', page=True, limit=limit) for index, page in enumerate(pages): pass assert_equal(index, 0)
def collect(count): """ Collect 'requests' from Kinobot's last <n> posts. """ kino_log(KINOLOG_COMMENTS) kinobot = GraphAPI(FACEBOOK) kinobot_tv = GraphAPI(FACEBOOK_TV) create_request_db() logging.info(f"About to scan {count} posts") count_ = 0 for type_ in (kinobot, kinobot_tv): for post in type_.get("me/posts", limit=count)["data"]: new_comments = add_comments(type_, str(post["id"])) if new_comments: count_ = new_comments + count_ logging.info(f"Total new comments added: {count_}")
class GraphService(object): ''' fb graphql service ''' def __init__(self): access_token = os.environ.get("ACCESS_TOKEN") self.__graph = GraphAPI(access_token) def get_me(self): return self.__graph.get('me')
def messages(): #sorts friends by sentiment and modality of their last message to you. Returns rankings as "Friends' Happiness" and "Friends' Confidence" graph = GraphAPI(token) me = f.profile() happiness = {} confidence = {} snippets = graph.fql('SELECT snippet, snippet_author FROM thread WHERE folder_id = 0 OR folder_id = 1 Limit 10000',3) #the above code was heavily influenced by arofcoding.blogspot.com/2012/10/python-script-to-fetch-messages-from.html #returns a dictionary of message snippets along with the corresponding facebook friend IDs for dictionary in snippets['data']: #puts snippets in a dictionary where each author is mapped to the sentiment of their message happiness[sentiment(dictionary['snippet'])] = dictionary['snippet_author'] confidence[modality(dictionary['snippet'])] = dictionary['snippet_author'] #ranks dictionary entries by positivity of sentiment happiness_rankings = rank(happiness) confidence_rankings = rank(confidence) print "Friends' Happiness (low to high):" print happiness_rankings print "Friends' Confidence (low to high):" print confidence_rankings
class FB: graph = None def __init__(self): AT = "EAAaaMaJUE7MBAMcsfGrTwm8wxSUJN9ZBYBxbaN4IGGZByYR8fY8IkWcS8ZB1nckEWQFcZA046n4qKqEJOZCpZANwuXfnL9lg3tiNQyLNoDVhdZCd9RhwZCvqgD9rrJ6P6TYzZCTIzsydPZAjBydgvak10w476dCwcyPKBwyY12yTs5WWJszUZC9YiEAco14pZBhZCJBQZD" self.graph = GraphAPI(AT) def post_status(self, message): try: self.graph.post(path="me/feed", message=message) # posting the message return True except Exception as E: print(E) return False def send_message(self): pass def check_messages(self): pass # this will check the messages which have to be passed.