def __init__(self, config={}): """Configure the client.""" self._key = config['key'] self._secret = config['secret'] self._api = facebook.Facebook(self._key, self._secret)
def test10(self): import Image image1 = Image.new("RGB", (400, 300), (255, 255, 255)) filename = "image_file.jpg" image1.save(filename) global response_str fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login facebook.httplib.HTTP = Mock('httplib.HTTP') http_connection = Mock('http_connection') facebook.httplib.HTTP.mock_returns = http_connection http_connection.send.mock_returns_func = self.send def _http_passes(): return [200,] http_connection.getreply.mock_returns_func = _http_passes def read(): response = {"stuff":"stuff"} response_str = simplejson.dumps(response) return response_str http_connection.file.read.mock_returns_func = read response = {"session_key":"key","uid":"my_uid","secret":"my_secret","expires":"my_expires"} response_str = simplejson.dumps(response) res = fb.auth.getSession() result = fb.photos.upload(image=filename,aid="aid",caption="a caption") self.assertEquals(str(result["stuff"]),"stuff") os.remove(filename)
def login(self): self.fb = facebook.Facebook('22745cc1f71dd2697ea3167cf89c0fba', '7401614618034bdd36f56ddd6f26ce2d') self.fb.auth.createToken() self.fb.login() self.fb.auth.getSession() self.userID = self.fb.users.getLoggedInUser()
def test1(self): f = facebook.Facebook(api_key=my_api_key, secret_key=my_secret_key) f.login = self.login self.assertEquals(f.api_key, my_api_key) self.assertEquals(f.secret_key, my_secret_key) self.assertEquals(f.auth_token, None) self.assertEquals(f.app_name, None) self.assertEquals(f.callback_path, None) self.assertEquals(f.internal, None)
def stream_publish(user, **kwargs): session = session_for_user(user) if not session: raise ValueError, "No session." fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) fb.session_key = session.session_id fb.session_key_expires = 0 return fb.stream.publish(**kwargs)
def test4(self): global response_str response = 'abcdef' response_str = simplejson.dumps(response) fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login fb.auth.createToken() self.assertEquals(str(fb.auth_token),"abcdef") url = fb.get_login_url(next="nowhere", popup=True, canvas=True) self.assertEquals(url, 'http://www.facebook.com/login.php?canvas=1&popup=1&auth_token=abcdef&next=nowhere&v=1.0&api_key=%s'%(my_api_key,))
def __init__(self, probe, probe_time, probe_id): Updater.__init__(self, probe, probe_time, probe_id) # Blacklist source info self.src = "facebook.com" self.tp = "blacklist" # Get Facebook creds creds = json.loads(open("facebook-creds").read()) self.fb = facebook.Facebook(creds["id"], creds["secret"])
def login (self): self.fb = facebook.Facebook (self.api_key, self.secret, self.session_code) self.session = self.fb.auth.getSession () self.uid = self.fb.users.getInfo ([self.fb.uid])[0]['uid'] path = self.local_data_dir + "/auth.pickle" utils.save_auth_status (path, self.session) if self.uid not in self.user_ids: self.user_ids.append (self.uid) self.status_changed (defs.IS_LOGIN) self.refresh_hanedler = gobject.timeout_add (self.refresh_interval * 1000, self._refresh)
def test7(self): global response_str response = 'abcdef' response_str = simplejson.dumps(response) fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login fb.auth.createToken() self.assertEquals(str(fb.auth_token),"abcdef") url = fb.get_authorize_url(next="next",next_cancel="next_cancel") self.assertEquals(url, 'http://www.facebook.com/authorize.php?api_key=%s&next_cancel=next_cancel&v=1.0&next=next' % (my_api_key,))
def test6(self): global response_str response = 'abcdef' response_str = simplejson.dumps(response) fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login fb.auth.createToken() # self.failUnlessRaises(RuntimeError,fb._add_session_args) response = {"session_key":"key","uid":"my_uid","secret":"my_secret","expires":"my_expires"} response_str = simplejson.dumps(response) fb.auth.getSession() args = fb._add_session_args()
def login(self): api_key = '22745cc1f71dd2697ea3167cf89c0fba' secret_key = '7401614618034bdd36f56ddd6f26ce2d' self.fb = facebook.Facebook(api_key, secret_key) self.fb.auth.createToken() self.fb.login() time.sleep(15) self.fb.auth.getSession() session_key = self.fb.session_key secret = self.fb.secret self.userID = self.fb.users.getLoggedInUser() return True
def terminal(args): fb = facebook.Facebook() if args['messages']: show_unread_messages(fb) if args['notifications']: show_notifications(fb) if args['online']: show_friends_online(fb) if args['post']: post_on_wall(fb, args['post']) if args['query']: custom_FQL(fb, args['query'].lower()) if args['spy_friend']: show_friend_online_status(fb, args['spy_friend'])
def test8(self): class Request: def __init__(self,post,get,method): self.POST = post self.GET = get self.method = method global response_str response = {"session_key":"abcdef","uid":"my_uid","secret":"my_secret","expires":"my_expires"} response_str = simplejson.dumps(response) req = Request({},{'installed':1,'fb_page_id':'id','auth_token':'abcdef'},'GET') fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login res = fb.check_session(req) self.assertTrue(res)
def test3(self): global response_str response = {'stuff':'abcd'} response_str = simplejson.dumps(response) fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login fb.auth.createToken() self.assertEquals(str(fb.auth_token['stuff']),"abcd") fb.login() response = {"session_key":"key","uid":"my_uid","secret":"my_secret","expires":"my_expires"} response_str = simplejson.dumps(response) res = fb.auth.getSession() self.assertEquals(str(res["expires"]),response["expires"]) self.assertEquals(str(res["secret"]),response["secret"]) self.assertEquals(str(res["session_key"]),response["session_key"]) self.assertEquals(str(res["uid"]),response["uid"])
def fb_login(request): """ This function will render the view for the successful Facebook login page. """ try: import facebook from django.conf import settings # if the request contains valid facebook cookies, then process fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) fb_data = fb.validate_cookie_signature(request.COOKIES) if not fb_data: raise Exception( "Facebook support enabled, but no facebook user logged in") # add some extra data to the facebook object fb.session_key = fb_data['session_key'] fb.uid = fb_data['user'] logging.debug( "Request contains Facebook cookie signature (from FBConnect) = %s", fb_data) fb_userdata = fb.users.getInfo( fb.uid, ['first_name', 'last_name', 'profile_url', 'pic_square']) logging.debug("User Data for logged in user = %s", fb_userdata) user = User.findOrCreate('facebook', fb.uid) # TODO: update the user details user.screenName = "%s %s" % (fb_userdata[0]['first_name'], fb_userdata[0]['last_name']) user.profileImageUrl = fb_userdata[0]['pic_square'] user.accessToken = fb.session_key user.put() social_auth.persistUserSession(request, user) return render_to_response(request, 'social_auth/facebook_login_ok.html') except (Exception), inst: logging.error("Error validating facebook user: %s", inst) return render_to_response(request, 'social_auth/facebook_login_fail.html')
def before_handler(self, **kwargs): log.debug("FacebookTool: before_handler") global facebook if facebook is None: try: import facebook except ImportError: log.error("Facebook is not available") self.api_key = self.config.get("facebook.apikey") self.secret_key = self.config.get("facebook.secret") fb = facebook.Facebook(api_key=self.api_key, secret_key=self.secret_key) cherrypy.request.facebook = fb fb.in_canvas = (request.params.get('fb_sig_in_canvas') == '1') # Check if we already have a session if fb.session_key and (fb.uid or fb.page_id): return True if request.method == 'POST': params = fb.validate_signature(request.params) else: if 'installed' in request.params: fb.added = True if 'fb_page_id' in request.params: fb.page_id = request.params['fb_page_id'] if 'auth_token' in request.params: fb.auth_token = request.params['auth_token'] try: fb.auth.getSession() except facebook.FacebookError, e: log.error("FBTool: Unable to get session") fb.auth_token = None return False return True params = fb.validate_signature(request.params)
def fb_check_session(request): """ This method is used to check that the facebook session is still valid for the currently logged in user """ import facebook from django.conf import settings # if the request contains valid facebook cookies, then process fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) fb_data = fb.validate_cookie_signature(request.COOKIES) if not fb_data: raise Exception( "Facebook support enabled, but no facebook user logged in") return render_to_response(request, 'social_auth/facebook_login_ok.html')
def restore_auth_status(path, api_key, secret): if os.path.exists(path): f = open(path, 'r') try: auth = pickle.load(f) except: f.close() logging.debug("pickle load failed") return False f.close() fb = facebook.Facebook(api_key, secret) fb.session_key = auth["session_key"] fb.uid = auth["session_key"].split('-')[1] fb.secret = auth["secret"] return fb else: "pickle auth not exist" return None
def test2(self): args = {"arg1":"a","arg2":"b","arg3":"c"} hasher = md5_constructor(''.join(['%s=%s' % (x, args[x]) for x in sorted(args.keys())])) hasher.update("acdnj") f = facebook.Facebook(api_key="abcdf", secret_key="acdnj") f.login = self.login digest = f._hash_args(args) self.assertEquals(hasher.hexdigest(),digest) hasher = md5_constructor(''.join(['%s=%s' % (x, args[x]) for x in sorted(args.keys())])) hasher.update("klmn") # trunk code has error hash.updated instead of hash.update digest = f._hash_args(args,secret="klmn") self.assertEquals(hasher.hexdigest(),digest) hasher = md5_constructor(''.join(['%s=%s' % (x, args[x]) for x in sorted(args.keys())])) f.secret = "klmn" hasher.update(f.secret) # trunk code has error hash.updated instead of hash.update digest = f._hash_args(args) self.assertEquals(hasher.hexdigest(),digest)
def get_fb_client(): import facebook # Replace these with your app's credentials api_key = '6a21799fd685071120c650f8a8a50952' secret_key = '6ba652d87a0c3fca014d1bcf96c52c28' client = facebook.Facebook(api_key, secret_key) try: # Try to read cached credentials from the session-key file. # If authorization fails, you should delete this file and start of. handle = open('session-key', 'r') client.uid, client.session_key, client.secret = [ line.strip() for line in handle ] handle.close() except IOError: client.auth.createToken() client.login() print 'Log in to the app in your browser, then press enter.' raw_input() client.auth.getSession() handle = open('session-key', 'w') print >> handle, client.uid print >> handle, client.session_key print >> handle, client.secret handle.close() if not int(client.users.hasAppPermission('xmpp_login')): import webbrowser webbrowser.open( client.get_url('authorize', ext_perm='xmpp_login', api_key=client.api_key, v='1.0')) print 'Grant the extended permission to the app in your browser, then press enter.' raw_input() return client
def get_facebook_client(): client = facebook.Facebook(APP_KEY, APP_SECRET) try: # Try to read cached credentials from the cookies file. # If authorization fails, you should delete this file and start over. handle = open('cookies.txt', 'r') client.uid, client.access_token, client.session_key, client.secret = [ line.strip() for line in handle ] handle.close() except IOError: code = getCode() client.access_token = getAccessToken(code) client.session_key = getSessionKey(client.access_token, code) client.secret = getSessionSecret(client.access_token) client.uid = getUid(client.access_token) handle = open('cookies.txt', 'w') print >> handle, client.uid print >> handle, client.access_token print >> handle, client.session_key print >> handle, client.secret handle.close() return client
def setUp(self): super(FacebookTest, self).setUp() self.facebook = facebook.Facebook(key_name='x') appengine_config.FACEBOOK_APP_ID = 'my_app_id' appengine_config.FACEBOOK_APP_SECRET = 'my_secret'
def __call__(self): cherrypy.request.facebook = facebook.Facebook( cherrypy.request.app.config['facebook']['api_key'], cherrypy.request.app.config['facebook']['secret_key']) cherrypy.request.facebook.redirect = self.redirect
def solve_facebook(t, limit=10): attrs = [ 'name', 'sex', 'status', 'pic', 'birthday', 'first_name', 'last_name', 'pic_big', 'pic_small', 'pic_square ', 'pic', 'affiliations', 'profile_update_time', 'religion', 'birthday', 'birthday_date', 'meeting_sex', 'username', 'website', 'profile_blurb', 'verified', 'allowed_restrictions', 'profile_url', 'locale', 'online_presence', 'is_app_user', 'about_me', 'quotes', 'books', 'movies', 'tv', 'music', 'is_blocked', ] # facebook attr userid X if t[1].islower() and t[1] in attrs and re.search( '[0-9]+', t[2]).group() == t[2] and t[3][0].isupper(): import facebook try: fb = facebook.Facebook(Secrets.get('facebook_key_1'), Secrets.get('facebook_key_2')) fb.session_key = Secrets.get('facebook_key_3') attrs = [t[1]] info = fb.users.getInfo([int(t[2])], attrs) except: return [] #raise Exception('TupletsError: missing or wrongs keys for Facebook, or attribute "%s" invalid!' % t[1]) #return [ [1,t[0],t[1],t[2], 'FACEBOOK_KEY_ERROR' ] ] if len(info) > 0 and t[1] in info[0] and info[0][t[1]] != None: if t[1] == 'status': if len(info[0][t[1]]['message']) == 0: return [] info[0][t[1]] = info[0][t[1]]['message'] if t[1] == 'affiliations': return [[1, t[0], t[1], t[2], aff['name']] for aff in info[0][t[1]]] if t[1] == 'profile_update_time': return [[1, t[0], t[1], t[2], time.ctime(int(info[0][t[1]]))]] if t[1] == 'religion' and len(info[0][t[1]]) == 0: return [] if bool(info[0][t[1]]) != info[0][t[1]] and list( info[0][t[1]]) == info[0][t[1]] and len(info[0][t[1]]) > 0: return [[1, t[0], t[1], t[2], metting_sex] for metting_sex in info[0][t[1]]] if str(info[0][t[1]]) == info[0][t[1]] and len(info[0][t[1]]) == 0: return [] return [[1, t[0], t[1], t[2], str(info[0][t[1]])]] # otherwise return []
def test5(self): class Request: def __init__(self, post, get, method): self.POST = post self.GET = get self.method = method req = Request({'fb_sig_in_canvas': 1}, {}, 'POST') fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login res = fb.check_session(req) self.assertFalse(res) req = Request({'fb_sig': 1}, {}, 'POST') res = fb.check_session(req) self.assertFalse(res) req = Request({'fb_sig': fb._hash_args({'in_canvas': '1', 'added': '1', 'expires': '1', 'friends': 'joe,mary', 'session_key': 'abc', 'user': '******'}), 'fb_sig_in_canvas': '1', 'fb_sig_added': '1', 'fb_sig_expires': '1', 'fb_sig_friends': 'joe,mary', 'fb_sig_session_key': 'abc', 'fb_sig_user': '******'}, {}, 'POST') res = fb.check_session(req) self.assertTrue(res) fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login req = Request({'fb_sig': fb._hash_args({'in_canvas': '1', 'added': '1', 'expires': '1', 'friends': '', 'session_key': 'abc', 'user': '******'}), 'fb_sig_in_canvas': '1', 'fb_sig_added': '1', 'fb_sig_expires': '1', 'fb_sig_friends': '', 'fb_sig_session_key': 'abc', 'fb_sig_user': '******'}, {}, 'POST') res = fb.check_session(req) self.assertTrue(res) fb = facebook.Facebook(my_api_key, my_secret_key) fb.login = self.login req = Request({'fb_sig': fb._hash_args({'in_canvas': '1', 'added': '1', 'expires': '1', 'friends': '', 'session_key': 'abc', 'page_id': 'id'}), 'fb_sig_in_canvas': '1', 'fb_sig_added': '1', 'fb_sig_expires': '1', 'fb_sig_friends': '', 'fb_sig_session_key': 'abc', 'fb_sig_page_id': 'id'}, {}, 'POST') res = fb.check_session(req) self.assertTrue(res)
def main(): opts, args = parse_args() config = ConfigParser() if opts.credentials: config.read(opts.credentials) FB_API_KEY = config.get('facebook', 'api key') FB_SECRET_KEY = config.get('facebook', 'secret key') print 'API KEY:', FB_API_KEY print 'SECRET KEY:', FB_SECRET_KEY fb = facebook.Facebook(FB_API_KEY, FB_SECRET_KEY) if os.path.exists(CCACHE): auth = pickle.load(open(CCACHE)) fb.session_key = auth['session_key'] fb.secret = auth['secret'] fb.uid = auth['uid'] else: tok = fb.auth.createToken() fb.login() print >> sys.stderr, 'Waiting...' sys.stdin.readline() auth = fb.auth.getSession() pickle.dump(auth, open(CCACHE, 'w')) if not fb.uid: raise ApplicationError('Login failed.') notes = fb.fql.query( 'SELECT note_id, created_time, updated_time, title, content FROM note WHERE uid=%d' % fb.uid) name = fb.users.getInfo(fb.uid, 'first_name')[0]['first_name'] feed = ET.Element(atomElement('feed')) addSubElement(feed, atomElement('title'), attrs={'type': 'text'}, text='Notes for %s' % name) addSubElement(addSubElement(feed, atomElement('author')), atomElement('name'), text=name) addSubElement(feed, atomElement('generator'), text='Blogger') for note in notes: entry = addSubElement(feed, atomElement('entry')) addSubElement(entry, atomElement('id'), text='http://www.facebook.com/notes.php?id=%s' % note['note_id']) addSubElement(entry, atomElement('title'), attrs={'type': 'text'}, text=note['title']) addSubElement(entry, atomElement('category'), attrs={ 'scheme': CATEGORY_KIND, 'term': POST_KIND }) addSubElement(entry, atomElement('published'), text=fmtTime(note['created_time'])) addSubElement(entry, atomElement('updated'), text=fmtTime(note['updated_time'])) addSubElement(entry, atomElement('author'), text=name) addSubElement(entry, atomElement('content'), attrs={'type': 'html'}, text=note['content'].replace('\n', '<br/>')) ET.ElementTree(feed).write(sys.stdout) return fb
import facebook import sys from auval.watcher import * YOUR_API_KEY = '34fc282cb0e81f80666828404745b31c' YOUR_SECRET_KEY = '1aabc0c42c09234bf77b16ec7c0df825' SESSION_KEY = 'f6a8c6f1b8974d5e35cac528-411158' SESSION_SECRET = 'fde8e3fc97ce96b6e89b28b10d571b94' fb = facebook.Facebook(YOUR_API_KEY, YOUR_SECRET_KEY) fb.session_key = SESSION_KEY fb.secret = SESSION_SECRET box_prob = SharedVar('/vision/box/results/probability') box_enabled = SharedVar('/vision/box/settings/enabled') downward_path = SharedVar('/vision/camera/downward') watcher = VarWatcher(box_prob) box_enabled.set(True) while 1: watcher.wait_for_change() watcher.watch_var(box_prob) if box_prob.get() > 0.9 and box_enabled.get(): box_enabled.set(False) box_prob.set(0.0) res = fb.photos.upload(downward_path.get()) print "Photo uploaded!" print res['link'] sys.exit()
import urllib import facebook import sys print ("Hello World, this is python") if (len(sys.argv) == 2): token = sys.argv[1] print "Token is "+token facebook = facebook.Facebook(token) facebook.postOnWall("Playing with facebook from Graph API is fun :)") else: print "Usage: "+sys.argv[0]+" token"