def delete_post(post): user = post.user graph = GraphAPI(user.access_token) try: graph.delete( post.post_id ) post.is_deleted = True except FacepyError,e: post.error_delete = e
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 for recog in payload[0]['faceboxes']: name = recog['recognitions'] if name: arr.append({ 'name': name[0]['user']['name'], 'certainity': name[0]['certainty'] }) # Deleting the uploaded picture graph.delete(path=post_id) return arr
def test_delete(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'true' graph.delete('1') mock_request.assert_called_with('DELETE', 'https://graph.facebook.com/1', allow_redirects=True, params={'access_token': '<access token>'})
def test_delete(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'true' graph.delete(1) mock_request.assert_called_with('DELETE', 'https://graph.facebook.com/1', allow_redirects = True, params = { 'access_token': '<access token>' } )
def test_delete(): graph = GraphAPI(TEST_USER_ACCESS_TOKEN) # Yes; this is, in fact, what the Graph API returns upon successfully # deleting an item. response.content = 'true' graph.delete(1) mock_request.assert_called_with('DELETE', 'https://graph.facebook.com/1', allow_redirects = True, params = { 'access_token': TEST_USER_ACCESS_TOKEN } )
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>"}, )
class User(object): """Instances of the User class represent Facebook test users.""" 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) @classmethod def create(self, application_id, access_token, **parameters): """ Create a new Facebook test user. :param application_id: A string describing the Facebook application ID. :param access_token: A string describing the application's access token. :param name: An optional string describing the user's name (defaults to a generated name). :param permissions: An optional list describing permissions. :param locale: An optional string describing the user's locale (defaults to ``en_US``). :param installed: A boolean describing whether the user has installed your application (defaults to ``True``). """ return User(**GraphAPI(access_token).post('%s/accounts/test-users' % application_id, **parameters)) def delete(self): """ Delete the test user. """ self.graph.delete(self.id) def __enter__(self): return self def __exit__(self, *args, **kwargs): self.delete()
class User(object): """Instances of the User class represent Facebook test users.""" 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) @classmethod def create(self, application_id, access_token, **parameters): """ Create a new Facebook test user. :param application_id: A string describing the Facebook application ID. :param access_token: A string describing the application's access token. :param name: An optional string describing the user's name (defaults to a generated name). :param permissions: An optional list describing permissions. :param locale: An optional string describing the user's locale (defaults to ``en_US``). :param installed: A boolean describing whether the user has installed your application (defaults to ``True``). """ return User(**GraphAPI(access_token).post( '%s/accounts/test-users' % application_id, **parameters)) def delete(self): """ Delete the test user. """ self.graph.delete(self.id) def __enter__(self): return self def __exit__(self, *args, **kwargs): self.delete()
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_delete(): graph = GraphAPI(TEST_ACCESS_TOKEN) # Generate a random message (Facebook rejects duplicate messages within a short time frame) message = ''.join( random.sample( 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(), 10)) response = graph.post(path='me/feed', message=message) assert graph.delete(response['id']) is True
def test_delete(): graph = GraphAPI(TEST_ACCESS_TOKEN) # Generate a random message (Facebook rejects duplicate messages within a short time frame) message = ''.join(random.sample('a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(), 10)) response = graph.post( path = 'me/feed', message = message ) assert graph.delete(response['id']) is True
def test_delete(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'true' mock_request.return_value.status_code = 200 graph.delete( path='1', main_page_id='112', location_page_id='113', ) mock_request.assert_called_with('DELETE', 'https://graph.facebook.com/1', allow_redirects=True, verify=True, timeout=None, params={ 'main_page_id': '112', 'location_page_id': '113', 'access_token': '<access token>' })
class User(object): """Instances of the User class represent Facebook test users.""" 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) @classmethod def create(self, application_id, access_token, **parameters): """ Create a new Facebook test user. :param application_id: A string describing the Facebook application ID. :param access_token: A string describing the application's access token. :param name: An optional string describing the user's name (defaults to a generated name). :param permissions: An optional list describing permissions. :param locale: An optional string describing the user's locale (defaults to ``en_US``). :param installed: A boolean describing whether the user has installed your application (defaults to ``True``). """ return User(**GraphAPI(access_token).post( '%s/accounts/test-users' % application_id, **parameters)) def delete(self): """ Delete the test user. """ self.graph.delete(self.id) def befriend(self, other): """ Befriend other user. :param other: Another test User """ r = self.graph.get('me/friends/%s' % other.id) if 'data' in r and r['data'] and r['data'][0]['id'] == other.id: # already friends return self.graph.post('%s/friends/%s' % (self.id, other.id)) other.graph.post('%s/friends/%s' % (other.id, self.id)) @classmethod def users(self, application_id, access_token, **parameters): """ Get existing test users. """ r = GraphAPI(access_token).get( '%s/accounts/test-users' % application_id, **parameters) for u in r['data']: yield User(u['id'], u['access_token'], u['login_url'], None, None) @property def me(self): """ Get user information. """ return self.graph.get('me') def __enter__(self): return self def __exit__(self, *args, **kwargs): self.delete()
class User(object): """Instances of the User class represent Facebook test users.""" 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) @classmethod def create(self, application_id, access_token, **parameters): """ Create a new Facebook test user. :param application_id: A string describing the Facebook application ID. :param access_token: A string describing the application's access token. :param name: An optional string describing the user's name (defaults to a generated name). :param permissions: An optional list describing permissions. :param locale: An optional string describing the user's locale (defaults to ``en_US``). :param installed: A boolean describing whether the user has installed your application (defaults to ``True``). """ return User(**GraphAPI(access_token).post('%s/accounts/test-users' % application_id, **parameters)) def delete(self): """ Delete the test user. """ self.graph.delete(self.id) def befriend(self, other): """ Befriend other user. :param other: Another test User """ r = self.graph.get('me/friends/%s' % other.id) if 'data' in r and r['data'] and r['data'][0]['id'] == other.id: # already friends return self.graph.post('%s/friends/%s' % (self.id, other.id)) other.graph.post('%s/friends/%s' % (other.id, self.id)) @classmethod def users(self, application_id, access_token, **parameters): """ Get existing test users. """ r = GraphAPI(access_token).get('%s/accounts/test-users' % application_id, **parameters) for u in r['data']: yield User(u['id'], u['access_token'], u['login_url'], None, None) @property def me(self): """ Get user information. """ return self.graph.get('me') def __enter__(self): return self def __exit__(self, *args, **kwargs): self.delete()
posts = graph.get( "Group-ID/feed?fields=created_time,reactions,message&limit=100" )['data'] flag = 0 Deadline = time.time() - 6 * 3600 # carefull change according to timezone Lower_Bound = time.time() - 7 * 3600 while 1: change_creation_time() posts.sort(key=get_key, reverse=True) for post in posts: if Lower_Bound <= post['created_time']: if post['created_time'] < Deadline: if len(post['reactions']['data']) < 5: graph.delete(str(post['id'])) else: flag = 1 time.sleep(480) break if flag: break if 'paging' in Group_Handle and 'next' in Group_Handle['paging']: request_str = Group_Handle['paging']['next'].replace( 'https://graph.facebook.com/v2.9', '') Group_Handle = graph.get(request_str)
def delete(self): application_graph = GraphAPI('%s|%s' % (TEST_APP_ID, TEST_APP_SECRET)) application_graph.delete("%s/" % self.user_id)
class FBRecog(object): API_URL = "https://www.facebook.com/photos/tagging/recognition/?dpr=1" def __init__(self, access_token, cookies, fb_dtsg): self.access_token = access_token self.cookies = cookies self.fb_dtsg = fb_dtsg self.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': 'FBRecog/API', 'content-type': 'application/x-www-form-urlencoded', 'accept': '*/*', 'referer': 'https://www.facebook.com/', 'cookie': self.cookies, 'dnt': '1' } self.graph = GraphAPI(self.access_token) def _post_photo(self, path): try: # Uploading the picture to Facebook response = self.graph.post(path='me/photos', retry=3, source=open(path, 'rb')) except Exception as e: print(e) return -1 else: return response['id'] def _query_recognition_api(self, post_id): payload = [] data = 'recognition_project=composer_facerec&photos[0]=' + post_id data += '&target&is_page=false&include_unrecognized_faceboxes=false&include_face_crop_src=true' data += '&include_recognized_user_profile_picture=true&include_low_confidence_recognitions=true' data += '&__a=1&fb_dtsg=' + self.fb_dtsg # Since the POST sometimes returns a blank array, retrying until a payload is obtained for i in range(20): response = requests.post(self.API_URL, data=data, headers=self.headers) payload = json.loads(response.text.replace('for (;;);', ''))['payload'] if payload and "faceboxes" in payload[0] and payload[0][ 'faceboxes']: break return payload[0]['faceboxes'] def recognize_raw(self, path): print('Post data to Facebook, please wait...') post_id = self._post_photo(path) result = None if post_id != -1: try: print("Querying Facebook, please wait...") result = self._query_recognition_api(post_id) except (KeyError, IndexError) as e: print( "Unable to fetch details. API unresponsive. Please try again later." ) except Exception as e: print(e) # Deleting the uploaded picture print("Please wait. Cleaning up...") self.graph.delete(path=post_id, retry=5) print("Finished.") return result def recognize(self, path): """Face recognition using Facebook's recognize method Args: path : file path of the photo to be processed Returns: result : array of recognitions with the name of recognized people and the certainity of each recognition """ faceboxes = self.recognize_raw(path) result = [] for recog in faceboxes: name = recog['recognitions'] if name: result.append({ 'name': name[0]['user']['name'], 'certainity': name[0]['certainty'] }) return result
graph = GraphAPI(Access_Token, version='2.9') while 1: posts = graph.get("Group-ID/feed?fields=created_time,reactions,message&limit=100")['data'] flag = 0 Deadline = time.time() - 6*3600 # carefull change according to timezone Lower_Bound = time.time() - 7*3600 while 1: change_creation_time() posts.sort(key=get_key, reverse=True) for post in posts: if Lower_Bound <= post['created_time']: if post['created_time'] < Deadline: if len(post['reactions']['data']) < 5: graph.delete(str(post['id'])) else: flag = 1 time.sleep(480) break if flag: break if 'paging' in Group_Handle and 'next' in Group_Handle['paging']: request_str = Group_Handle['paging']['next'].replace('https://graph.facebook.com/v2.9', '') Group_Handle = graph.get(request_str)
key = "#" start = time() uptime = start for i in xrange(5): key+=str(randint(0, 9)) print "Please post the following to unlock FBTerminal: "+key while True: if locked: now = time()-start if now%10==0: a = graph.get('me/feed') cmd = a['data'][0]['message'] if cmd == key: print 'unlocked' if postedID is not None: graph.delete(postedID) locked = False posted = graph.post('me/feed', message='FBTerminal was successfully unlocked!') postedID = posted['id'] continue elif cmd==':printKey': print key else: continue else: continue if fileCreated: system('del output.txt') fileCreated = False
class Facebook(object): def __init__(self, token): self.token = token self.graph = GraphAPI(self.token) def upload_photo(self, filepath): try: response = self.graph.post(path='me/photos', source=open(filepath, 'rb')) except Exception as e: raise e return response def delete_photo(self, post_id): try: response = self.graph.delete(path=post_id) except Exception as e: raise e return response def recognize_faces(self, filepath, cookie, fb_dtsg): post_id = self.upload_photo(filepath)['id'] URL = "https://www.facebook.com/photos/tagging/recognition/" headers = { 'accept': '*/*', 'accept-encoding': 'gzip, deflate', 'accept-language': 'en-US,en;q=0.8', 'content-type': 'application/x-www-form-urlencoded', 'cookie': cookie, 'origin': 'https://www.facebook.com', 'referer': 'https://www.facebook.com/', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', 'x_fb_background_state': '1' } params = { 'dpr': '1', 'recognition_project': 'composer_facerec', 'photos[0]': post_id, 'target': '', 'is_page': 'false', 'include_unrecognized_faceboxes': 'false', 'include_face_crop_src': 'false', 'include_recognized_user_profile_picture': 'false', 'include_low_confidence_recognitions': 'true', '__a': '1', 'fb_dtsg': fb_dtsg } payload = None while not payload: response = requests.post(URL, headers=headers, data=params) # [9:] in order to skip 'for (;;);' to make string JSON compatible payload = json.loads(response.text[9:])['payload'] response.raise_for_status() time.sleep(1) self.delete_photo(post_id) return self.parse_names(payload[0]) def parse_names(self, fb_response): names = {} faceboxes = fb_response['faceboxes'] for face in faceboxes: for recognition in face['recognitions']: names[recognition['user']['name']] = recognition['certainty'] return names