def get_graph_api(user): try: access_token = UserSocialAuth.objects.get( user=user).extra_data['access_token'] return GraphAPI(access_token) except ObjectDoesNotExist: return None
def __init__(self): app_id = Config.get_value('authentication', 'app_id') app_secret = Config.get_value('authentication', 'app_secret') self.oath_access_token = None if self.oath_access_token is None: self.oath_access_token = utils.get_application_access_token(app_id, app_secret) self.graph = GraphAPI(self.oath_access_token)
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 main(): """ FYI: This takes ~10-15 seconds to run on my laptop. """ utf = io.open('cluster.txt', 'w', encoding='utf8') utf.close() utf = io.open('cluster.txt', 'a', encoding='utf8') #utf=io.open('summary.txt', 'a', encoding='utf8') config = configparser.ConfigParser() config.read("configure.txt") graph = GraphAPI(config.get("facebook", "USER_TOKEN")) FbpageDetails = graph.get(config.get("facebook", "Trump"), page=False, retry=3) PageName = FbpageDetails["name"] graph = read_graph() draw_network(graph) print('graph has %d nodes and %d edges' % (graph.order(), graph.number_of_edges())) utf.write("\nTotal Graph nodes and edges=" + str(graph.order()) + " " + str(graph.number_of_edges())) subgraph = get_subgraph(graph, 2) print('subgraph has %d nodes and %d edges' % (subgraph.order(), subgraph.number_of_edges())) utf.write("\nTotal Graph nodes and edges=" + str(subgraph.order()) + " " + str(subgraph.number_of_edges())) result = girvan_newman(subgraph.copy()) # minsize=10, maxsize=100) i = 0 print("Graphs of Clusters greater then size 10 only shown") clusterlabel = [] for cluster in result: i = i + 1 figs = str(i) + ".png" degrees = (graph.subgraph(cluster)).degree() labels = {n: n for n, d in sorted(degrees.items())} if (len(labels) > 1): clusterlabel.append(len(labels)) draw_network(graph.subgraph(cluster), label_thresh=5, draw_thresh=0, savefig=figs, length=len(labels)) print("Cluster Created of Sizes, -->", str(clusterlabel)) utf.write("\n Cluster Created of Sizes=" + str(clusterlabel)) utf.write("\n Number of communities discovered=" + str(len(clusterlabel))) utf.write("\n Average number of users per community=" + str((subgraph.order() * 1.0) / len(clusterlabel))) print("\n Average number of users per community=" + str((subgraph.order() * 1.0) / len(clusterlabel))) # utf.write("Cluster Created of Sizes, -->"+clusterlabel) test_node = PageName train_graph = make_training_graph(subgraph, test_node, 5) jaccard_scores = jaccard(train_graph, test_node, 5) print('jaccard accuracy=%.3f' % evaluate(jaccard_scores, subgraph, n=10)) utf.write('\n jaccard accuracy=%.3f' % evaluate(jaccard_scores, subgraph, n=10)) utf.close()
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 uploadPicture(picturePath): token = settings.ACCESS_TOKEN try: graph = GraphAPI(token) # Get my latest posts #print graph.get('me/posts') # Post a photo graph.post( path='me/photos', #source = picturePath source=open(picturePath, 'rb') #source = open('hslls.bmp', 'rb') ) except: print("-------------------") print("") print("Change access token") print("") print("-------------------") #uploadPicture("")
def graph(self): """ A ``Facepy.GraphAPI`` instance initialized with the user's access token (See `Facepy`_). .. _Facepy: http://github.com/jgorset/facepy """ return GraphAPI(self.oauth_token.token)
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': '******', }) 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, params={'access_token': '<access token>'})
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_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_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_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.' } ] }) mock_request.return_value.status_code = 200 graph.search( term='shaft quotes', type='post' ) mock_request.assert_called_with( 'GET', 'https://graph.facebook.com/search', allow_redirects=True, verify=True, timeout=None, params={ 'q': 'shaft quotes', 'type': 'post', 'access_token': '<access token>' } )
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_errors(): graph = GraphAPI('<access token>') # Test errors mock_request.return_value.content = json.dumps({ 'error': { 'code': 1, 'message': 'An unknown error occurred' } }) mock_request.return_value.status_code = 200 assert_raises(GraphAPI.FacebookError, graph.get, 'me') # Test legacy errors mock_request.return_value.content = json.dumps({ 'error_code': 1, 'error_msg': 'An unknown error occurred', }) mock_request.return_value.status_code = 200 assert_raises(GraphAPI.FacebookError, graph.get, 'me') # Test legacy errors without an error code mock_request.return_value.content = json.dumps({ 'error_msg': 'The action you\'re trying to publish is invalid' }) mock_request.return_value.status_code = 200 assert_raises(GraphAPI.FacebookError, graph.get, 'me')
def test_forbidden_delete(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'false' mock_request.return_value.status_code = 200 assert_raises(GraphAPI.FacebookError, graph.delete, 'me')
def spam(): token = "EAAFYfkmP4UcBAO9QjTA7F26oQgqrTzYBFvu95TpxBblZBNNZAStmw3V8Fa2b84S8NypgNQBSIRHtQRikdUNVXkpuw4km5WQclvwLePQcBCK3D4ClhOcDpUk283PvOBlhncZBGJBUFG4pZCl2cigvf5LbqZC8sLYf3bYydxn4mikHvzcHLGLttGPMfkZBnsrCGa96JiY9ZCqknRDU0EpmaMD" #Insert access token here. facebook = fb.graph.api(token) graph1 = GraphAPI(token) vid = '100348971905356' 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 = 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 = input("Enter the message to be commented: ") if int(nos) <= len(idlist): for indid in (idlist[(len(idlist) - int(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 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_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_query_transport_error(): graph = GraphAPI('<access token>') mock_request.side_effect = ConnectionError( 'Max retries exceeded with url: /') assert_raises(GraphAPI.HTTPError, graph.get, 'me')
def __init__( self, page_url=None, published: bool = False, **kwargs, ): try: fb_dict = _facebook_map[page_url or FACEBOOK_URL] except KeyError: raise ValueError(f"{page_url} not found in registry") self.published = published self.id = None self.parent_id = None self.content = None self.added = None self.posted = False self._set_attrs_to_values(kwargs) self.token = fb_dict["token"] self.table = fb_dict["table"] self.page = page_url.rstrip("/") self._images: List[str] = [] self._api = GraphAPI(self.token) self._description = None
def writeComment(page_token_in, comment, dest_id, link_in = ""): pg = GraphAPI(page_token_in) pg.post( path = dest_id + '/comments', message = comment, link = link_in )
def postMessage(token_in, text, link_in = ""): g = GraphAPI(token_in) g.post( path =group_id + '/feed', message = text, link = link_in )
def facebook_post_video(sender, instance, created, **kwargs): '''Once video is created, if facebook connect and video public is set to True Video link would then be posted to Facebook page of user ''' video = instance user = instance.uploader if user and created: profile = UserProfile.objects.get(user=user) if profile.facebook_connect and video.is_public: 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) domain = Site.objects.get_current().domain url = 'http://%s/%s' % (domain, video.slug) img_url = 'http://%s/%s' % (domain, 'media/gfx/logo.png') graph.post( path='me/links', picture=img_url, message= "Hi Guys! Posted a new video, %s. Check it out on the AWESOME %s site!" % (video.title, Site.objects.get_current().name), link=url, )
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_if_raises_error_on_facebook_500(): graph = GraphAPI('<access token>') mock_request.return_value.status_code = 500 mock_request.return_value.content = '' assert_raises(GraphAPI.FacebookError, graph.get, 'me')
def build_profile(self,fields,api_key): for field, values in fields.items(): params = [('save','Save')] postUrl = "https://m.facebook.com/a/editprofile.php" if field == 'gender': url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) params.extend([('new_info',values),('new_info_arr[0]','0')]) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "birthday": #dont forget to remove the continue line #continue date = values.split("/") month = date[0] day = date[1] year = date[2] params.extend([('month',month),('day',day),('year',year)]) url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "relationship": params.extend([("status", values)]) url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "interested": params.extend([("new_info_arr[0]",values)]) url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == 'current_city' or field == 'hometown': params.extend([("add_ids[]",values)]) url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "languages": params.extend([('add_strs[0]',values)]) url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "religious" or field == "political": params.extend([('add_strs[]',values)]) url = "https://m.facebook.com/editprofile.php?type=basic&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "quote" or field == "about_me": params.extend([('new_info',values)]) url = "https://m.facebook.com/editprofile.php?type=personal&edit=%s&refid=17" % (field) self.httpParse("/a/editprofile.php","action",url,params,postUrl) elif field == "photo_location": #dont forget to remove the continue #two months token graph = GraphAPI(api_key) pictures = glob.glob(values+ '*.jpg') for i in range(1,len(pictures),1): self.pic_upload(pictures[i])
def __init__(self, key=None): global key_index """ >>> Graph = processGraph() You May Initialise Facebook GraphAPI with your own AppID and AppSecret >>> Graph = processGraph("<<App_ID>>|<<App_Secret>>") """ if not key: while True: self.graph = GraphAPI(KEYS_FB[key_index]) try: self.graph.search("test", "place") break except: key_index = (key_index + 1) % len(KEYS_FB) else: self.graph = GraphAPI(key)
def handle(text, mic, profile): print "I'm Busy.py" token = "CAACEdEose0cBAOs8kQn5iLHkd3ZCObZCEZC7IAfXZBt8ZCFyx9ESVP6N3JNDki9cQZApw2GLg6m2vNjhIiK9hjwtt88bs5O58D1cZBPTo5RnFafSOvOODQsLhnXN8jjezYTfZA1b2qARsH9AR9zmuEaTRaauktr1Tj4rhDZARMPI1ViAh3GK6iWcbwhWCZCuFRkI7v7TR5TiSEgPmCKbnUKXXe" graph = GraphAPI(token) postid = graph.post(path = 'me/feed',message = "I'm busy") print postid mic.say("Busy mode on")
def test_get_with_fpnum(): graph = GraphAPI('<access token>') mock_request.return_value.content = '{"payout": 0.94}' mock_request.return_value.status_code = 200 resp = graph.get('<paymend_id>') assert_equal(resp, {'payout': float('0.94')})
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)