def _get_facebook_token(fb_app_id, fb_app_secret): # try to authenticate fb_auth = _authorize_get_response('http://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=http://0.0.0.0:8080/&scope=manage_pages' % fb_app_id) if 'code' not in fb_auth.keys(): abort('Did not receive a token from Facebook! Did you decline authorization?') # get a short-term access token graph = GraphAPI() response = graph.get( path='oauth/access_token', client_id=fb_app_id, client_secret=fb_app_secret, redirect_uri='http://0.0.0.0:8080/', code=fb_auth['code'][0] ) data = parse_qs(response) # extend the token extended_token = utils.get_extended_access_token(data['access_token'][0], fb_app_id, fb_app_secret) graph = GraphAPI(extended_token[0]) # get the accounts associated with the token (list of pages managed by the user) pages = [] accounts = graph.get(path = 'me/accounts') for entry in accounts['data']: pages.append({'value': {'page_id': unicode(entry['id']), 'token': unicode(entry['access_token'])}, 'display': '%s - %s' % (unicode(entry['id']), unicode(entry['name']))}) # get the user's selected page selected_page = _get_user_choice('Select a page from your authorized ones: ', pages) if selected_page: return (selected_page['token'], selected_page['page_id']) else: return (None, None)
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_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_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 post () : token = 'EAAD8B9lvyRABAHjCqkvsmJT4PIZCKqJBMRgGiG8Pzif91PcZAKz9EA6QB7RbBCjLAbQmjzlcCEB1gSXI6CPoMBSmqktNr76r5uzKw1tNQREEAFO9GubrCWV6GNdUiaMa7uYmFCDOzZC3RuRidFwWa6aN8k1PASdOPYjhhDuK2iAqVKbaeT3SPLfb3qEZBzLZCG5sgW7azQAZDZD' #sempre atualizar o token de acesso graph = GraphAPI(token) post = graph.get('me/posts') quase = post['data'] li = [] lin = [] for i in quase: li.append(i) for j in range(len(li)): po = "" if 'message' in li[j]: po = li[j] lin.append(po) u = graph.get('me') usuario = u['name'] ids = u['id'] return lin,usuario,ids
def main(): app_id = 1486791588264932 app_secret = "93595d85e282ce2bb395a21c92139631" oath_access_token = utils.get_application_access_token(app_id, app_secret) token = "CAACEdEose0cBAHdKj7pO0wWcQ1l7Nk5SXOUZAWdIEOZCvFg6JuL8IRJQcTJZBg GpNgoO5M2d3nZBYOhOdnDgn9gJc9mZCk8bC9N5yIMAEVpZAWX8pgIv CSZCGWu6vkfX5I1VDCfkyLHaKkxpgLOyTsnOCHuWkiBrjlW5dN1IHNLmZ C168XZBMJIc1r5UA7ssNZAUhJPsbNzaR1rer93oSuQA4kZAfNIjGCp95IZD" print oath_access_token graph = GraphAPI(token) for friendlist in graph.get('me/friendlists/')["data"]: print for friend in graph.get( friendlist["id"] + "/members" )["data"]: print friend["name"] try: print len( graph.get(friend["id"] + "/friends/")["data"] ) print len(frnd_friendlist) except : print 0
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_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': '******', }) 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_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 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 Upload(): with open(r"C:\autismomeme\authcode.txt", "r") as myfile: authcode = myfile.read() graph = GraphAPI(authcode) graph.get("/autsimomeme/photos") graph.post(path="/autsimomeme/photos", message="", source=open(("temp.jpg"), "rb")) return
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 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 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()
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_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 fb_validate_token(token): graph = GraphAPI(token) try: graph.get('me') except OAuthError: return False return True
def index(request): if request.method == 'GET': name = request.GET.get('name', '') location = request.GET.get('location') acc_token = request.GET.get('token') if location: geolocator = Nominatim() location = geolocator.geocode(location) location = str(location.latitude) + ',' + str(location.longitude) else: lat = request.GET.get('lat') lon = request.GET.get('lon') location = str(lat) + ',' + str(lon) print name, location, acc_token if acc_token: graph = GraphAPI(acc_token) else: graph = GraphAPI( 'CAACEdEose0cBAPJRZA8xHkMmbokHYBCUyjcKxZBohVhzJnGlm2ETlOYESQpEjG1Gj6ykTV4FMmhqMUrgFsJp0HdH4TszHwCkoMA8PS8L2MRFth3w3Wm7ucx4xMglc9ZBZAMhnyrr3XNAlH6MHZBtGmeWusWvzu4GSt4Mt9oS2KIOkWh70WhQ3ktOUC40PgChklQN31X0EgAZDZD' ) search = name search = qp(search) result = graph.get('search?type=place&q=' + search + '¢er=' + location) page_id = result['data'][0]['id'] params = 'fields=phone,likes,current_location,about,website,food_styles,description,hours,awards,price_range,location,booking_agent,is_verified,offers,public_transit,founded,products,emails,parking' a = str(page_id) + '?' + params cache = {} cache['facebook'] = {} cache['google'] = {} cache['facebook'] = {'fb_page_url': 'http://facebook.com/' + page_id} params = params.split(',') for each in params: try: cache['facebook'][each] = str(graph.get(a)[each]) except: pass #Google Data url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + location + '&radius=5000&name=' + name + '&key=AIzaSyDAERlVmOrLWdq0pHF5fK3c2cHmCSvy55I' print url r = requests.get(url) google_result = json.loads(r.text) cache['google'] = google_result return HttpResponse(json.dumps(cache), content_type="application/json") elif request.method == 'POST': t = request.POST.get("task", "") a = Task(text=t, date=timezone.now()) a.save() return redirect('/')
class FacebookIngest(): def __init__(self, logger_instance, oauth_access_token=None): if oauth_access_token != None: try: self.graph = GraphAPI(oauth_access_token) except: raise Exception('Could not instantiate Facebook GraphAPI with provided access token') else: raise Exception('No facebook access token provided.') self.user_id = self.get_user_id() self.reverse_geocoder = ReverseGeoCode() self.logger = logger_instance def get_user_id(self): resp = self.graph.get('/v2.0/me?fields=id') return resp['id'] def get_location_of_residence(self): profile = self.graph.get('/v2.0/me?fields=location') return profile['location']['name'] def get_languages(self): languages = set() resp = self.graph.get('/v2.0/me?fields=languages') for l in resp['languages']: languages.add(l['name']) return list(languages) def get_tagged_places(self): countries = set() try: resp = self.graph.get('/v2.0/' + self.user_id + '/tagged_places') except: raise Exception('Error getting tagged_places from Facebook') for place_dict in resp["data"]: country = self.reverse_geocoder.reverse_geocode_country(place_dict["place"]["location"]["latitude"], place_dict["place"]["location"]["longitude"]) if country: countries.add(country) self.logger.error(str(datetime.now()) + ":" + "countries_returned: " + str(list(countries))) return list(countries)
class FbAPI(object): 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 get_token(self): return self.oath_access_token def get_posts(self, page_name, index = 0): post_page = self.graph.get(POSTS_STR % page_name, page = True, limit=25) data = next(islice(post_page, index, index+1))['data'] df = pd.DataFrame(data).fillna('') source_format = '%Y-%m-%dT%H:%M:%S' target_format = '%Y/%m/%d %H:%M:%S' datetime_parser = lambda d: (datetime.strptime(str(d)[:-5], source_format)).strftime(target_format) df['created_time'] = df['created_time'].apply(datetime_parser) return df.values.tolist(), list(df.columns) def get_likes(self, post_id): index = 0 like_list = self.graph.get(LIKES_STR % (post_id, ''), page = True, limit=25, summary = 1) response = next(islice(like_list, index, index+1)) data = response['data'] df = pd.DataFrame(data).fillna('') counts = int(response['summary']['total_count']) return df.values.tolist(), list(df.columns), counts def get_likes_export(self, post_id): query_url = "https://graph.facebook.com/%s/likes?summary=true&limit=1000&access_token=%s" % ( post_id, self.oath_access_token ) df = self.get_like_data_from_web(query_url) #print len(df.index) file_name = 'likes_lst_post_id_%s.csv' % post_id full_path = SAVE_PATH % file_name df.to_csv(full_path, index = False, encoding='utf-8') return full_path, file_name def get_like_data_from_web(self, query_url): web_response = urllib2.urlopen(query_url) json_obj = json.loads(web_response.read()) df = pd.DataFrame(json_obj['data']).fillna('') #print 'recived counts: %s' % str(len(df.index)) #cnt = 1 has_next = 'next' in json_obj['paging'].keys() #print has_next counts = json_obj['summary']['total_count'] print 'total counts %s' % counts #time.sleep(0.5) if has_next: #print 'recurcive %s' % str(cnt+1) df = df.append(self.get_like_data_from_web(json_obj['paging']['next']), ignore_index=True) return df
class FacebookAccessInput(Input): def __init__(self): Input.__init__(self, "Facebook Access Token", "", "") self.me = {} self.user_data_perms = ["publish_actions", "user_birthday"] self.extended_perms = ["read_stream"] def show(self): self.inform() Input.show(self) def validate(self): self.graph = GraphAPI(self.input) try: self.me = self.graph.get("me") perms = self.graph.get("me/permissions")["data"][0] self.check_perms(perms, self.user_data_perms) self.check_perms(perms, self.extended_perms) except: self.set_error("bad key") Input.validate(self) def check_perms(self, fb_perms, reqd_perms): for perm in reqd_perms: if not fb_perms.has_key(perm): self.set_error("[ ]%s unchecked" % perm) break def print_perms(self, perms): for perm in perms: djl_print(color_string(OKGREEN, "[x]%s" % perm)) def inform(self): prompt = "You need a %s. Get one now?" % self.category if len(self.err) > 1: prompt += " {error: %s}" % self.err if not confirm_yes_or_no(prompt + ": "): webbrowser.open("https://developers.facebook.com/tools/explorer") self.show_required_permissions() def show_required_permissions(self): djl_seperator() djl_print("1. Click the 'Get Access Token' button.") djl_print("2. Check the following permission: ") djl_print("- User Data Permissions:") self.print_perms(self.user_data_perms) djl_print("- Extended Permissions:") self.print_perms(self.extended_perms) djl_print("3. Click the 'Get Access Token' button.") djl_print("4. Copy and paste the generated Access Token below.") djl_seperator()
def test_timeouts(): graph = GraphAPI('<access token>', timeout=1) mock_request.return_value.content = json.dumps({}) 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 main(silent=True,save=False): global TOKEN counter = 0 graph = GraphAPI(TOKEN) #initialize facepy currentPage=graph.get('me/feed') # Get my latest posts # Get my Information myInfo = graph.get("me") myBirthdate = parser.parse(myInfo['birthday']).date() myID = myInfo['id'] if save: #if save, create file to save to with open('birthday'+str(myBirthdate.year)+'.csv','a') as f: writer = csv.writer(f) writer.writerow(['ID','Name']) nextPage = True while nextPage: data = currentPage['data'] #get list of posts for entry in data: # Terminating conditions # #1 --> Beyond my birthday. date = parser.parse(entry['created_time']).date() if date.month < myBirthdate.month or date.day < myBirthdate.day: nextPage = False print('Completed. Replied '+str(counter)+' posts.') return # Skipping Conditions # #1 if poster is myself, skip if entry['id'] == myID: continue #Else, check if birthday msg, post random reply if checkIfBirthdayMessage(entry['message']) == True: counter+=1 postReply(entry['id']) if not silent: print('Replied '+entry['from']['name']) if save: ID = entry['from']['id'] name = entry['from']['name'] with open('birthday'+str(myBirthdate.year)+'.csv','a') as f: writer = csv.writer(f) writer.writerow([ID,name]) #page currentPage = currentPage['paging']['next'] currentPage = nextPage.replace('https://graph.facebook.com/v2.0/','')
def get_reaction(source_no,source_id,token,after=""): global list_after_reaction if (after in list_after_reaction) and (after != ""): print("No more reaction1") list_after_reaction = ["1"] else: list_after_reaction.append(after) x = "/v2.10/"+source_id+"/reactions?limit=999&after="+after graph = GraphAPI(token) page = graph.get(x) for data in page['data']: author_id = data['id'] author_name = data['name'] reaction_action = data['type'] reaction_data['reaction'].append({ 'Source No': source_no, 'Source ID': source_id, 'Author Name': author_name, 'Author ID': author_id, 'Type': reaction_action }) try: paging = page['paging'] cursors = paging['cursors'] after = cursors['after'] get_reaction(source_no,source_id,token,after) except: print("No more reaction2") list_after_reaction = ["1"]
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 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=250" 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 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
class Facebook(object): ''' classdocs ''' def __init__(self,config): self.facebook = GraphAPI(config["token"]) try: #token=facepy.utils.get_extended_access_token(config["token"],config['app_id'],config['app_secret']) #self.facebook = GraphAPI(token[0]) me=self.facebook.get('me') print(json.dumps(me, indent=4)) #print ("token:"+str(token[0])) except: pass#self.facebook=None def uploadImage(self,messageStr,imagePath): print("uploading to facebook") tries=0 while(tries<5): try: print self.facebook.post( path = 'me/photos', source = open(imagePath), message=messageStr ) break except: print("facebook error, try #"+str(tries)) time.sleep(0.1) tries=tries+1 print("finnished uploading to facebook\n")
def main(): key = 'EAACEdEose0cBAPUfYkZCZB69YRMEb1nu95mUuYlt4gHItzggZCGF8YFKICaZA2XFzWqCsx3iAOmI8bKEofQWM7yjvMZCYZC7IPOWbPMjYx3hCDEPlUjvj2LVA4BIOAQMI37oFMD5T6M1fhBWpryyF8ZCEWRq0ZCEAOS8QeddrC3L0VKdb0h9Coc6kWZBnZBEaABEsZD' g = GraphAPI(key) res = g.get('/me/picture', False) facebook = fb.graph.api(key) print(res)
def home(request): perfis = Perfil.objects.filter(perfil_id=194) print(perfis) #https://developers.facebook.com/tools/explorer entre nesse link e pegue o token rs graph = GraphAPI( 'EAANqe5z7HqMBADqLetRWszNPTAbnfvxrELlhy3VuNHNHbxmiOJfGRtSUZAx7KvibptHYJoEEnNj65aMl4pOn1BI72spbtfmXL1T2mgageXVvcvQRctQa2Jlv4oR2GpFVisjAEcVRmiHa5lyEIcdSWJZCdkP46nJFOuwC2bUdXRfOdJcGDn7iDxPZBZBecQYZD' ) politica = [ 'lula', 'Jaburu', 'aiai', 'na', 'haddad', 'Brasil', 'povo', 'comunistas', '#elenao', 'Guedes', 'pobres', 'Temer', '#elenunca' ] posts = graph.get('me/posts') p = [] interessePolitica = [] for i in range(len(posts['data'])): if 'message' in posts['data'][i].keys(): p.append(posts['data'][i]['message']) for i in politica: for j in p: if i in j: if j not in interessePolitica: interessePolitica.append(j) p = Perfil() p.perfil_usuario = graph p.Perfil_interesse = politica p.perfil_mensagem = interessePolitica p.save() return render(request, 'home/home.html', { 'perfis': perfis, 'interessePolitica': interessePolitica }, {'politica': politica})
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')})
class FbConnector(): def __init__(self): self.token = fbauth.getAccessToken() self.graph = GraphAPI(self.token) def postImage(self, caption, filename): """Posts an image file into FB :param str caption: a valid string :param str filename: a valid path to an image file """ try: fimage = open(filename, 'rb') self.graph.post(path="me/photos", caption=caption, source=fimage) except: print 'Error submitting image' def postMessage(self, text): """Posts a message into FB :param str text: a valid string """ try: self.graph.post(path='me/feed', message=text) except: print 'There was an error posting the message' def getUsername(self): """Gets the current logged in username :rtype: str """ try: r = self.graph.get('me?fields=name') return r['name'] except: print 'Error retrieving 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 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 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.")
class Facebook(object): ''' classdocs ''' def __init__(self, config): self.facebook = GraphAPI(config["token"]) try: #token=facepy.utils.get_extended_access_token(config["token"],config['app_id'],config['app_secret']) #self.facebook = GraphAPI(token[0]) me = self.facebook.get('me') print(json.dumps(me, indent=4)) #print ("token:"+str(token[0])) except: pass #self.facebook=None def uploadImage(self, messageStr, imagePath): print("uploading to facebook") tries = 0 while (tries < 5): try: print self.facebook.post(path='me/photos', source=open(imagePath), message=messageStr) break except: print("facebook error, try #" + str(tries)) time.sleep(0.1) tries = tries + 1 print("finnished uploading to facebook\n")
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")
class PersonalProfile(): def __init__(self, request): # Initialize the Graph API with a valid access token (optional, # but will allow you to do all sorts of fun stuff). from allauth.socialaccount import SocialToken oauth_access_token= SocialToken.objects.get(account = request.user.username).token self.graph = GraphAPI(oauth_access_token) def userProfile(self): from py2neo import neo4j graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/") self.user = graph_db.create_node({ "name" : "Bob Robertson", "date_of_birth" : "1981-07-01", "occupation" : "Hacker" }) people = graph_db.create_node() people.create_relationship_to(self.user, "PERSON") def myposts(self): # Get my latest posts posts = self.graph.get('me/posts') def friends(self): for friend in friends: myfriend = Thing(friend) friendship = self.user.create_relationship_to(myfriend, "KNOWS")
def listings(request): access_token = User.objects.get(email=request.user.email, password="******") # print(user_obj.__dict__) # access_token = user_obj.first_name + user_obj.last_name if request.user.is_authenticated(): graph = GraphAPI(access_token) accounts = graph.get("me/accounts") args = {'fields': 'id, name, phone, access_token, single_line_address'} page_info = [] for i in accounts["data"]: page_id = i['id'] graph_data = graph.get(page_id, **args) page_info.append(graph_data) return render(request, 'listings.html', {'data': page_info})
def spam(): token="#" facebook=fb.graph.api(token) graph1 = GraphAPI(token) vid=input("Enter victim's id: ") query=str(vid)+"/photos/uploaded" r=graph1.get(query) idlist=[x['id'] for x in r['data']] idlist.reverse() print("There are "+ str(len(idlist)) +" spammable photos.") char1=raw_input("Do you want to spam? (y/n) ") count=0 if char1=='y': nos=input("Enter number of photos 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 photo facebook.publish(cat="likes",id=indid) #Likes each photo count=count+1 print("Notification number: "+str(count)+" on www.facebook.com/photo.php?fbid="+str(indid)) else: print("Not that many spammable photos available. No spam happening.") else : print("No spam happening then.")
def get_checkins(request): if not request.user.is_authenticated(): return HttpResponse(json.dumps({ 'my_checkins': [], 'friend_checkins': [] }), mimetype='application/json') social_auth = request.user.get_profile() graph = GraphAPI(social_auth.access_token) friends = sum([d['data'] for d in graph.get('me/friends', page=True)], []) friend_ids = [friend['id'] for friend in friends] friend_checkins = [{ 'facebook_id': ch.facebook_id, 'id': ch.screening_id } for ch in Checkin.objects.filter(facebook_id__in=friend_ids)] return HttpResponse(json.dumps({ 'my_checkins': [{ 'facebook_id': ch.facebook_id, 'id': ch.screening_id } for ch in Checkin.objects.filter(user=request.user)], 'friend_checkins': friend_checkins }), mimetype='application/json')
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 handle(self, *args, **kwargs): subscriptions = Subscription.objects.filter( provider__in=['socialfeed.providers.facebook_userfeed']) for subscription in subscriptions: if not all(key in subscription.config for key in ['app_id', 'app_secret', 'access_token']): continue access_token = '|'.join([subscription.config['app_id'], subscription.config['app_secret']]) input_token = subscription.config['access_token'] api = GraphAPI(access_token) result = api.get('/debug_token?input_token={}'.format(input_token)) self.stdout.write(''' Subscription: {subscription} Facebook App: {app} ({app_id}) Token expires: {expires} Token valid: {valid} Error: {error}\n '''.format(**{ 'subscription': subscription, 'app': result['data']['application'], 'app_id': result['data']['app_id'], 'valid': result['data']['is_valid'], 'expires': datetime.fromtimestamp( result['data']['expires_at']), 'error': result['data'].get('error', {}).get('message') }))
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_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 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 test_error_message_on_500_response(): graph = GraphAPI("<access token>") message = "Ad Sets may not be added to deleted Campaigns." mock_request.return_value.status_code = 500 mock_request.return_value.content = json.dumps( {"error": {"code": 1487634, "type": "Exception", "is_transient": False, "message": message}} ) try: graph.get("act_xxxx/adcampaigns") except GraphAPI.FacebookError as exc: eq_(exc.message, message) try: graph.post("act_xxxx/adcampaigns") except GraphAPI.FacebookError as exc: eq_(exc.message, message)
def get_fb_data(from_date, to_date, keyword): #pdb.set_trace() request_id = uuid.uuid4() #try: page_id = keyword access_token = "854568807915975|Vzdlg3iLBXkJGvN6t326Zf-rc54" graph = GraphAPI(access_token) page_date = graph.get(page_id) #page_date=str(page_date["founded"]) data = graph.get(page_id + '/posts', since=from_date, untill=to_date, page=True, retry=5) #data count = 0 for post in data: for p in post['data']: #print "post===============",p fb_message = "" share_count = "" for key in p: #print "key=====",key if 'shares' in key: share_count = p['shares']['count'] if 'message' in key: fb_message = str(p['message'].encode('ascii', 'ignore')) fb_obj = facebook_data( request_id=request_id, fb_post_id=p['id'], fb_post_message=fb_message, fb_post_from=p['from']['name'], fb_post_share_count=share_count, #fb_post_like_count = #fb_post_comment_count = fb_post_created_date=p['created_time']) fb_obj.save() comment_count = get_fb_comments(p['id'], graph) #print "fb_obj=====",fb_obj fb_obj.fb_post_comment_count = comment_count fb_obj.save() count += 1 return count, request_id
class FbPageAPI: def __init__(self, _access_token, limit=250): self.access_token = _access_token self.graph = GraphAPI(self.access_token) self.accounts = self._get_accounts(limit) def _get_accounts(self, limit=250): self.accounts = self.graph.get('me/accounts?limit=' + str(limit)) return self.accounts['data'] def get_accounts(self): return self.accounts['data'] def get_page_access_token(self, _page_id): for data in self.accounts: if _page_id == data['id']: page_access_token = data['access_token'] print('access_token: ', page_access_token) print('id: ', data['id']) print('name: ', data['name']) return page_access_token else: return None @staticmethod def post_in_page(page_access_token, page_id, image_file=None, message=None): page_graph = GraphAPI(page_access_token) print('Posting .....') if not message: message = '.' if image_file: image_file = open(image_file, 'rb') page_graph.post(path=page_id + '/photos', source=image_file, message=message) else: page_graph.post(path=page_id + '/feed', message=message) def create_new_page_directories(self, media_path): count = 1 # check for new directories for data in self.accounts: print(count, ' - ', 'id: ', data['id']) print(count, ' - ', 'name: ', data['name']) count += 1 page_id = data['id'] page_name = data['name'].replace(' ', '_') page_path = os.path.join(media_path, page_name) page_file = os.path.join(page_path, '__' + page_id + '__') if not os.path.exists(page_path): os.makedirs(page_path) if not os.path.isfile(page_file): with open(page_file, 'w') as fp: fp.write(page_id + '\n')
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 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_posts_data(page_id, access_token, tag_data_dict): graph = GraphAPI(access_token) #page_id= 'flipkart' data = graph.get( page_id + "/posts?fields=id,created_time,updated_time,message,description&limit=100", page=True, retry=5) page_post = models.Page.objects.get(page_id=page_id) #transaction.set_autocommit(False) for i in data: #print i['data'] for post_data in i['data']: print post_data if 'description' in post_data and 'message' in post_data: (post_data_save, post_data_save_status ) = models.Posts.objects.update_or_create( post_id=str(post_data['id']), defaults={ 'page_id': page_post, 'message': post_data['message'], 'description': post_data['description'], 'created_time': post_data['created_time'], 'updated_time': post_data['updated_time'] }) nl.nl_main_func(post_data['message'], str(post_data['id']), tag_data_dict) nl.nl_main_func(post_data['description'], str(post_data['id']), tag_data_dict) elif 'description' not in post_data and 'message' in post_data: (post_data_save, post_data_save_status ) = models.Posts.objects.update_or_create( post_id=str(post_data['id']), defaults={ 'page_id': page_post, 'message': post_data['message'], 'created_time': post_data['created_time'], 'updated_time': post_data['updated_time'] }) nl.nl_main_func(post_data['message'], str(post_data['id']), tag_data_dict) elif 'description' in post_data and 'message' not in post_data: (post_data_save, post_data_save_status ) = models.Posts.objects.update_or_create( post_id=str(post_data['id']), defaults={ 'page_id': page_post, 'description': post_data['description'], 'created_time': post_data['created_time'], 'updated_time': post_data['updated_time'] }) nl.nl_main_func(post_data['description'], str(post_data['id']), tag_data_dict) else: pass print(post_data_save, post_data_save_status)
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 test_get_unicode_url(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({}) response = graph.get('https://www.facebook.com/christophernewportuniversity') assert_true(mock_request.called) assert_equal({}, response)
def test_get_with_fpnum(): graph = GraphAPI('<access token>') mock_request.return_value.content = '{"payout": 0.94}' mock_request.return_value.status_code = 200 mock_request.return_value.headers = {} resp = graph.get('<paymend_id>') assert_equal(resp, {'payout': decimal.Decimal('0.94'), 'headers': {}})
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 and feed['data'] except (FacepyError, AssertionError), e: current_app.logger.error(e)