Ejemplo n.º 1
0
    def handle(self, *args, **options):
        if not os.path.isdir(TEMP_DIR):
            os.makedirs(TEMP_DIR, 0o700)

        self.stdout.write("Loading data from Facebook...")
        fbconsole.authenticate()
        # Use fbconsole.logout() to log out

        # Retrieve user data
        user = fbget_user()
        self.stdout.write("User '{name}', ID {id}, username {username}".format(**user))

        # Load accounts cache
        cache = {user['id']: user}
        for filename in glob.glob(os.path.join(PROFILE_DIR, '*.json')):
            profile = load_data(filename)
            if not profile or 'id' not in profile:
                self.stderr.write("Nothing loaded in file '{0}'".format(filename))
            cache[profile['id']] = profile
        if len(cache) > 1:
            print("Loaded {0} profiles from cache".format(len(cache)))

        # Enumerate friends
        for friend in fbconsole.iter_pages(fbconsole.get('/me/friends')):
            fid = friend['id']
            fname = friend['name'].encode('ascii', 'replace')
            if fid not in cache:
                self.stdout.write("Retrieve profile of {0}, (ID={1})".format(fname, fid))
                profile = fbconsole.get('/' + fid)
                if profile['id'] != fid:
                    self.stderr.write("{0} has two IDs: {1} and {2}".format(fname, fid, profile['id']))
                save_data(os.path.join(PROFILE_DIR, profile['id'] + '.json'), profile)
                cache[profile['id']] = profile
                self.stdout.write(".. done")
Ejemplo n.º 2
0
    def facebookName(self, speech, language):
        if (language == "de-DE"):  
	  def getFBPicture():
		fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access']
		fbconsole.authenticate()
		file = urllib2.urlopen('https://graph.facebook.com/%s?access_token=%s&fields=picture' % (fbconsole.get('/me')['id'], fbconsole.ACCESS_TOKEN))
		data = json.load(file)
		return data["picture"]
	
	  self.say("Ich checke ...")
          view = AddViews(self.refId, dialogPhase="Completion")         
          AnswerString =""
	  AnswerString = u"Du heißt: " + fbconsole.get('/me')['name']
	  AnswerString = AnswerString + "\nDu bist: " + fbconsole.get('/me')['gender']
	  AnswerString = AnswerString + "\nDeine Sprache : " + fbconsole.get('/me')['locale']
	  AnswerString = AnswerString + "\nDeine Uhrzeit ist : " + fbconsole.get('/me')['updated_time']
	  
	  FacebookImage = AnswerObject(title="Profile photo",lines=[AnswerObjectLine(image=getFBPicture())])	  
          FacebookInfo = AnswerObject(title='Your info',lines=[AnswerObjectLine(text=AnswerString)])

          
          view1 = 0
          view1 = AnswerSnippet(answers=[FacebookImage, FacebookInfo])
          view.views = [view1]
          self.say("Hier ist deine Info :")
          self.sendRequestWithoutAnswer(view)               
          self.complete_request()
Ejemplo n.º 3
0
def retrieve_friends():
    fbconsole.authenticate()
    friends = fbconsole.get('/me/friends', {'fields':'id,first_name,last_name'})
    next_url = friends.get('paging')
    friends = friends['data']
    while next_url:
        p = fbconsole.urlparse(next_url['next'])
        more_friends = fbconsole.get(p.path+'?'+p.query)
        next_url = more_friends.get('paging')
        more_friends = more_friends['data']
        if not more_friends:
            break
        friends.extend(more_friends)
    return friends
Ejemplo n.º 4
0
def retrieve_friends():
    fbconsole.authenticate()
    friends = fbconsole.get('/me/friends',
                            {'fields': 'id,first_name,last_name'})
    next_url = friends.get('paging')
    friends = friends['data']
    while next_url:
        p = fbconsole.urlparse(next_url['next'])
        more_friends = fbconsole.get(p.path + '?' + p.query)
        next_url = more_friends.get('paging')
        more_friends = more_friends['data']
        if not more_friends:
            break
        friends.extend(more_friends)
    return friends
Ejemplo n.º 5
0
def sync_address_book(friends, location, friend_list=u''):
    ab = ABAddressBook.sharedAddressBook()
    for f in friends:
        # filter out the location is not in new york
        try:
            user_entry = fbconsole.get('/%s' % (f['id']))
        except:
            continue
        if location:
            location_dict = user_entry.get('location')
            if not location_dict or not location_dict.get('name'):
                continue
            if not location in location_dict.get('name'):
                continue

        # create record only if it does not exists
        try:
            p = searchABBook(f['first_name'], f['last_name'])
        except SearchConflictException:
            # you can decide what to do if there is exactly the same first
            # name and last name in your existing address book
            continue
        if not p:
            p = ABPerson.alloc().init()
        img_data = NSData.dataWithContentsOfFile_(f['img_path'])
        p.setImageData_(img_data)
        p.setValue_forProperty_(f['first_name'], u'First')
        p.setValue_forProperty_(f['last_name'], u'Last')
        ab.addRecord_(p)
        print f['first_name'], f['last_name']
    ab.save()
Ejemplo n.º 6
0
    def newsFeed(self, speech, language):
                statuses = 15 #how many statuses you want to fetch
                limit = 0
                error = 0          
		if (language == "de-DE"):
			statusString = ""			
			view = AddViews(self.refId, dialogPhase="Completion")
			self.say("Ich checke ...")
			for post in fbconsole.iter_pages(fbconsole.get('/me/home')):
				if(error == 1):
					error = 0
				else :
					limit = limit + 1
				try: 
					post['message']
					ansewer = post['from']['name'] + " schrieb : " + post['message'] 
					print "INFO Getting status : ", limit
					statusString = statusString + ansewer + "\n\n"
					
					#self.say(ansewer)
				except KeyError as (strerror):     
					#print "Key error({0})".format(strerror)
					error = 1
					continue			
				if(limit == statuses): 
					break
					
			facebookStatuses = AnswerObject(title='Statuses :',lines=[AnswerObjectLine(text=statusString)])
			view1 = 0
			view1 = AnswerSnippet(answers=[facebookStatuses])
			view.views = [view1]
			self.sendRequestWithoutAnswer(view) 	
			self.complete_request()		
Ejemplo n.º 7
0
Archivo: demo.py Proyecto: nitzzz/new
    def post(self):
        result = flask.request.form['expression']
	status = fbconsole.post('/me/feed', {'message':result})
	likes = fbconsole.get('/'+status['id']+'/likes')
        flask.flash(result)
        fbconsole.logout()
        return self.get()
Ejemplo n.º 8
0
def fetch(url):
    result = fbconsole.get(url)
    if 'paging' in result:
        return list(fbconsole.iter_pages(result))
    if 'data' in result:
        return result['data']
    return result
Ejemplo n.º 9
0
def sync_address_book(friends, location, friend_list=u''):
    ab = ABAddressBook.sharedAddressBook()
    for f in friends:
        # filter out the location is not in new york
        try:
            user_entry = fbconsole.get('/%s' % (f['id']))
        except:
            continue
        if location:
            location_dict = user_entry.get('location')
            if not location_dict or not location_dict.get('name'):
                continue
            if not location in location_dict.get('name'):
                continue

        # create record only if it does not exists
        try:
            p = searchABBook(f['first_name'], f['last_name'])
        except SearchConflictException:
            # you can decide what to do if there is exactly the same first
            # name and last name in your existing address book
            continue
        if not p:
            p = ABPerson.alloc().init()
        img_data = NSData.dataWithContentsOfFile_(f['img_path'])
        p.setImageData_(img_data)
        p.setValue_forProperty_(f['first_name'], u'First')
        p.setValue_forProperty_(f['last_name'], u'Last')
        ab.addRecord_(p)
        print f['first_name'], f['last_name']
    ab.save()
Ejemplo n.º 10
0
def about_me():
    fb.AUTH_SCOPE = ['publish_stream', 'user_photos', 'friends_photos']
    fb.authenticate()
    me = fb.get('/me')
    about = ''
    for key, value in me.iteritems():
        about += '%s -> %s <br>' % (key, value)
    return about
Ejemplo n.º 11
0
def fbget_user():
    """Get current Facebook user"""
    user = load_data(os.path.join(TEMP_DIR, 'me.json'))
    if user is not None:
        return user
    user = fbconsole.get('/me')
    save_data(os.path.join(TEMP_DIR, 'me.json'), user)
    save_data(os.path.join(PROFILE_DIR, user['id'] + '.json'), user)
    return user
Ejemplo n.º 12
0
def post_status(message):
    """Delete the old status then post a new one."""

    global LAST_POST_ID
    global GROUP_ID

    # check if logged in
    try:
        fbconsole.get("/me")
    except:
        authenticate()

    # delete the old status
    if LAST_POST_ID is not None:
        fbconsole.delete("/"+LAST_POST_ID)

    #make new status
    post = fbconsole.post("/" + GROUP_ID + "/feed",{"message":message})
    LAST_POST_ID = post['id']
Ejemplo n.º 13
0
def post_status(message):
    """Delete the old status then post a new one."""

    global LAST_POST_ID
    global GROUP_ID

    # check if logged in
    try:
        fbconsole.get("/me")
    except:
        authenticate()

    # delete the old status
    if LAST_POST_ID is not None:
        fbconsole.delete("/" + LAST_POST_ID)

    #make new status
    post = fbconsole.post("/" + GROUP_ID + "/feed", {"message": message})
    LAST_POST_ID = post['id']
Ejemplo n.º 14
0
    def get_posts(self, days=3):

        day = datetime.datetime.now().day

        for post in fb.iter_pages(fb.get('/me/feed')):
            d, m, y = get_date_from_post(post)
            if day - d > days:
                break
            else:
                yield post
Ejemplo n.º 15
0
    def get_posts(self, days=3):

        day = datetime.datetime.now().day

        for post in fb.iter_pages(fb.get('/me/feed')):
            d, m, y = get_date_from_post(post)
            if day - d > days:
                break
            else:
                yield post
Ejemplo n.º 16
0
def getFBTitle(photoid):
    try:
        print "/%s" % photoid
        data = fbconsole.get("/%s" % photoid)
    except urllib2.HTTPError as e:
        print e.read()
        return None
    try:
        return data["name"], data["from"]["name"], data["link"]
    except Exception:
        return "Unnamed picture", data["from"]["name"], data["link"]
        print "FB error #2"
Ejemplo n.º 17
0
def getFBTitle(photoid):
    try:
        print "/%s" %photoid
        data = fbconsole.get("/%s" %photoid)
    except urllib2.HTTPError as e:
        print e.read()
        return None
    try:
        return data["name"], data["from"]["name"], data["link"]
    except Exception:
        return "Unnamed picture", data["from"]["name"], data["link"]
        print "FB error #2"
Ejemplo n.º 18
0
    def _events(self):
        """Yields events after last saved event from OffTheGrid's FB page"""
        try:
            latest_event = Event.objects.latest('start_time')
            last_update = latest_event.start_time
        except Event.DoesNotExist:
            last_update = timezone.make_aware(datetime.min,
                                              timezone.get_default_timezone())

        self.stdout.write('Pulling events from OffTheGrid facebook page')
        fbconsole.ACCESS_TOKEN = '{}|{}'.format(FB_APP_ID, FB_APP_SECRET)
        events = fbconsole.get('/OffTheGridSF/events')['data']

        for event in events:
            if parse(event['start_time']) > last_update:
                yield event
Ejemplo n.º 19
0
    def facebookFriends(self, speech, language):
        if (language == "de-DE"):   
           AnswerString = "" 
           view = AddViews(self.refId, dialogPhase="Completion")
           fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access']
	   fbconsole.authenticate()

	   for post in fbconsole.iter_pages(fbconsole.get('/me/friends')):
	     AnswerString = AnswerString + post['name'] + "\n"

	   self.say("Das sind deine Freunde:")
           FacebookFriends = AnswerObject(title='Deine Freunde :',lines=[AnswerObjectLine(text=AnswerString)])
           view1 = 0
           view1 = AnswerSnippet(answers=[FacebookFriends])
           view.views = [view1]
           self.sendRequestWithoutAnswer(view)               
           self.complete_request()
Ejemplo n.º 20
0
	def newsFeed(self, speech, language):
                statuses = 10 #how many statuses you want to fetch
                limit = 0
                error = 0
		if (language == "en-US"):	  
			for post in fbconsole.iter_pages(fbconsole.get('/me/home')):
				if(error == 1):
					error = 0
				else :
					limit = limit + 1
				try: 
					post['message']
					ansewer = post['from']['name'] + " wrote : " + post['message'] 
					print ansewer 
					self.say(ansewer)
				except KeyError as (strerror):     
					#print "Key error({0})".format(strerror)
					error = 1
					continue			
				if(limit == statuses): 
					break
Ejemplo n.º 21
0
    def handle(self, *args, **kwargs):
        for fb_event in self._events():
            details = fbconsole.get('/{}'.format(fb_event['id']))

            if 'end_time' not in details:
                details['end_time'] = details['start_time']

            event = Event(name=details['name'],
                          location=details['location'].strip(),
                          start_time=parse(details['start_time']),
                          end_time=parse(details['end_time']),
                          fb_id=details['id']
                          )
            event.save()

            event_description = details['description'].lower()
            vendors = [vendor for vendor in Vendor.objects.all()
                       if vendor.name.lower() in event_description]
            if vendors:
                event.vendors.add(*vendors)

            self.stdout.write('New event added! {}'.format(event.name))
Ejemplo n.º 22
0
    def __init__(self, id_, name, bestScore, bestWave, time):
        self._id = id_
        self._name = name
        self._score = 0
        self._wave = 0
        self._bestScore = bestScore
        self._bestWave = bestWave
        self._bestTime = time

        self._hangar = []
        self._inventory = []    

        if self._name == None:
            result = fb.get('/me', {'fields':'name'})
            self._name = result['name']

        BytesIO = pygame.compat.get_BytesIO()
        self._profilePicture = pygame.Surface((50, 50))
        self._profilePicture.fill(Config.colors['blue'])
        profile_pic_url = fb.graph_url('/{uid}/picture'.format(uid=self._id))
        with urllib.request.urlopen(profile_pic_url) as raw_img:
            self._profilePicture = pygame.image.load(BytesIO(raw_img.read()))
Ejemplo n.º 23
0
    def facebookFriendRequests(self, speech, language):
        if (language == "de-DE"):   
	    fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access', 'manage_notifications', 'read_requests']
	    fbconsole.authenticate()
	    self.say("Ich checke ...")
	    AnswerString = "" 
	    view = AddViews(self.refId, dialogPhase="Completion")          
	    error = 0
	    number = 0
	    while (error != 1):
	      try:
		  AnswerString = AnswerString + fbconsole.get('/me/friendrequests')['data'][number]['from']['name'] + "\n"
		  number = number + 1
	      except IndexError:
		  error = 1
                
	    if (number == 0):
	     self.say("Du hast keine Freundschaftsanfragen!")
	     self.complete_request()
	  
	    if (number == 1):
	     self.say("Du hast eine neue Freundschaftsanfrage!")
	     FacebookRequests = AnswerObject(title='Friend request from :',lines=[AnswerObjectLine(text=AnswerString)])
	     view1 = 0
	     view1 = AnswerSnippet(answers=[FacebookRequests])
	     view.views = [view1]
	     self.sendRequestWithoutAnswer(view)               
	     self.complete_request()
	  
	    self.say("Du hast %s neue Freundschaftsanfragen!" % (number))
	    FacebookRequests = AnswerObject(title='Friend requests from :',lines=[AnswerObjectLine(text=AnswerString)])
	    view1 = 0
	    view1 = AnswerSnippet(answers=[FacebookRequests])
	    view.views = [view1]
	    self.sendRequestWithoutAnswer(view)               
	    self.complete_request()
Ejemplo n.º 24
0
    def get(self):
        global own_likes
        global friend_tuples
        global my_loc
        user = fbconsole.get('/me')
	name = user['first_name']
        uid = user['id']
        client = tornado.httpclient.HTTPClient()
        friend_tuples = fbconsole.fql("SELECT name,uid FROM user WHERE uid IN "
                                        "(SELECT uid2 FROM friend WHERE uid1 = me())")
        own_likes = fbconsole.fql("SELECT page_id FROM page_fan WHERE uid = %s" % uid)
        own_locale = fbconsole.fql("SELECT current_location FROM user WHERE uid = %s" % uid)
        my_loc = own_locale[0]['current_location']['name']

        #gather own locale
        city = own_locale[0]['current_location']['city']
        city = city.replace(' ',',')
    #    client = tornado.httpclient.AsyncHTTPClient()
        
   #     client.fetch("http://api.eventful.com/rest/events/search?" + \
   #                 urllib.urlencode({"app_key": "5zPbkgmCjXhLpHT9", "keywords":"movies", "location":city}),
    #                callback=self.on_movie_response)

        self.render("main.html", name = name);
Ejemplo n.º 25
0
def last_post():
    fb.AUTH_SCOPE = ['publish_stream']
    fb.authenticate()
    data = fb.get('/me/feed')
    return data['data'][0]['message']
Ejemplo n.º 26
0
def get_msgs(fb, path):
    return fb.get(path)
Ejemplo n.º 27
0
    def post(self):
        global movies
        global own_likes
        global friend_tuples
        global my_loc
        global first_stats
        global second_stats
        global third_stats
        global _myemail

		#attempt at splash screen
		#self.render("intertitle.html");
		
        my_date = self.get_argument('friend_name')

        target_uid = -1;
        for item in friend_tuples:
            if item['name'] == my_date:
                target_uid = item['uid']
                break
        print ("User id is %s" % target_uid)

        #gather the date's likes, represented by object_id

        aboutme = fbconsole.get('/me')
        _myemail = aboutme['email']

        my_likes = fbconsole.get('/me/likes')

        friend_likes = fbconsole.get('/%s/likes' % target_uid)

        my_like_count = {}
        friend_like_count = {}

        for item in my_likes['data']:
            cat = str(item['category'])
            if cat in my_like_count:
                my_like_count[cat] += 1
            else:
                my_like_count[cat] = 1 

        for item in friend_likes['data']:
            cat = str(item['category'])
            if cat in friend_like_count:
                friend_like_count[cat] += 1
            else:
                friend_like_count[cat] = 1

        my_top_category = ""
        friend_top_category = ""

        for item in sorted(my_like_count, key = my_like_count.get, reverse=True):
            if item == "Community" or item == "Interest": # too vague
                continue
            else:
                if item == "Tv show":
                    item = "television"
                elif item == "Professional sports team":
                    item = "Sport"
                elif item == 'Local business' or item == "Restaurant/cafe":
                    item = "Restaurant"
                elif item == "Food/beverages":
                    item = "food"
                elif item == "Musician/band":
                    item = "band"
                my_top_category = item
                break

        for item in sorted(friend_like_count, key = friend_like_count.get, reverse=True):
            if item == "Community" or item == "Interest": # too vague
                continue
            else:
                if item == "Tv show":
                    item = "television"
                elif item == "Professional sports team":
                    item = "Sport"
                elif item == 'Local business' or item == "Restaurant/cafe":
                    item = "Restaurant"
                elif item == "Food/beverages":
                    item = "food"
                elif item == "Musician/band":
                    item = "band"
                friend_top_category = item
                break
            
        print my_top_category

        #print "My top category is %s" % my_top_category
        #print "My date's top category is %s" % friend_top_category

        venues = []
        client = foursquare.Foursquare(client_id=FSQOauthToken, client_secret=FSQOauthSecret)
        first_place = []

        #self.write("<p> Here are the top locations for my preference, which is %s</p>" % my_top_category)
        data = client.venues.explore(params={'near' : my_loc, 'query': my_top_category})
        for it in data["groups"]:
            for item in it["items"]:
                heapq.heappush(venues, (item["venue"]["stats"]["checkinsCount"], item["venue"]))
        largest = heapq.nlargest(10, venues)
        for loc in largest:
            first_place.append(loc[1])
       
        venues = []
        second_place = {}
        data = client.venues.explore(params={'near' : my_loc, 'query':  friend_top_category })
        for it in data["groups"]:
            for item in it["items"]:
                heapq.heappush(venues, (item["venue"]["stats"]["checkinsCount"], item["venue"]))
        largest = heapq.nlargest(10, venues)
        for loc in largest:
            print loc[1]['name']
            if loc[1]['name'] != first_place[0]['name']:
                second_place = loc[1]
                break

        if not second_place:
            second_place = first_place[1]

        venues = []
        third_place = {}
        data = client.venues.explore(params={'near' : my_loc, 'section':'food' }) 
        for it in data["groups"]:
            for item in it["items"]:
                heapq.heappush(venues, (item["venue"]["stats"]["checkinsCount"], item["venue"]))
        largest = heapq.nlargest(10, venues)
        for loc in largest:
            if loc[1]['name'] != first_place[0]['name'] and second_place and loc[1]['name'] != second_place['name']:
                third_place = loc[1]
                break

        if not third_place:
            third_place = first_place[2]

        first_stats = {} 
        first_stats['name'] = first_place[0]['name']
        first_stats['address'] = first_place[0]['location']['address']
        first_stats['phone'] = 'N/A'
        if 'contact' in first_place[0] and 'formattedPhone' in first_place[0]['contact']:
            first_stats['phone'] = first_place[0]['contact']['formattedPhone']
        if 'url' in first_place[0]:
            first_stats['website'] = first_place[0]['url'] 
        else:
            first_stats['website'] = 'N/A'
        first_stats['lat'] = first_place[0]['location']['lat']
        first_stats['lng'] = first_place[0]['location']['lng']

        second_stats = {} 
        second_stats['name'] = second_place['name']
        second_stats['address'] = second_place['location']['address']
        second_stats['phone'] = 'N/A'
        if 'contact' in second_place and 'formattedPhone' in second_place['contact']:
        	second_stats['phone'] = second_place['contact']['formattedPhone']
        if 'url' in second_place:
            second_stats['website'] = second_place['url'] 
        else:
            second_stats['website'] = 'N/A'
        second_stats['lat'] = second_place['location']['lat']
        second_stats['lng'] = second_place['location']['lng']

        third_stats = {} 
        third_stats['name'] = third_place['name']
        third_stats['address'] = third_place['location']['address']
        third_stats['phone'] = 'N/A'
        if 'formattedPhone' in third_place and 'phone' in third_place['contact']:
        	third_stats['phone'] = third_place['contact']['formattedPhone']
        if 'url' in third_place:
            third_stats['website'] = third_place['url'] 
        else:
            third_stats['website'] = 'N/A'
        third_stats['lat'] = third_place['location']['lat']
        third_stats['lng'] = third_place['location']['lng']


        first_text = client.venues(first_place[0]['id'])['venue']['tips']['groups'][0]['items'][0]['text']
        second_text = client.venues(second_place['id'])['venue']['tips']['groups'][0]['items'][0]['text']
        third_text = client.venues(third_place['id'])['venue']['tips']['groups'][0]['items'][0]['text']

        self.render("options.html",
                name1 = first_stats['name'],
                addr1 = first_stats['address'],
                phone1 = first_stats['phone'],
                web1 = first_stats['website'],
                tip1 = first_text,
                name2 = second_stats['name'],
                addr2 = second_stats['address'],
                phone2 = second_stats['phone'],
                web2 = second_stats['website'],
                tip2 = second_text,
                name3 = third_stats['name'],
                addr3 = third_stats['address'],
                phone3 = third_stats['phone'],
                web3 = third_stats['website'],
                tip3 = third_text);
Ejemplo n.º 28
0
    def facebookName(self, speech, language):
        if (language == "en-US"):
	  self.say(fbconsole.get('/me')['name'])
	  self.complete_request()
Ejemplo n.º 29
0
import fbconsole
import sys

fbconsole.AUTH_SCOPE = ['friends_about_me', 'friends_likes']
fbconsole.authenticate()
for url in sys.argv[1:]:
    print list(fbconsole.iter_pages(fbconsole.get(url)))
Ejemplo n.º 30
0
    def run(self):
        fbconsole.AUTH_SCOPE = ['user_photos', 'friends_photos', 'user_videos']
        fbconsole.authenticate()

        print "Getting mutual friends"
        mutual_friends = fbconsole.get('/me/mutualfriends/%s' % \
            self.target)
        friendlist = "(%s)" % ','.join(
            ["'%s'" % user['id'] for user in mutual_friends['data']]
        )
        time.sleep(1)
        print "Getting albums"
        albums = fbconsole.fql("""
            SELECT aid, name, owner FROM album WHERE owner IN %s
            """ % friendlist)
        for album in albums:
            time.sleep(1)
            sys.stdout.write('.')
            sys.stdout.flush()
            photos = fbconsole.fql("""
                SELECT src_big, link, caption, images, pid, created
                FROM photo 
                WHERE pid IN (
                    SELECT pid 
                    FROM photo_tag 
                    WHERE pid IN (
                        SELECT pid 
                        FROM photo 
                        WHERE aid = '%s'
                    )
                    AND subject = '%s'
                )
                """ % (album['aid'], self.target)
                )
            if len(photos) > 0:
                print "\nIn: '%s' by %d:" % (album['name'], album['owner'])
                for photo in photos:
                    biggest_image = 0
                    biggest_dim = 0
                    for i, image in enumerate(photo['images']):
                        if biggest_dim < image['height']:
                            biggest_dim = image['height']
                            biggest_image = i
                    image_url = photo['images'][biggest_image]['source']
                    file_part = image_url.split('/')[-1]
                    file_path = "%s/%s" % (self.destination, "%s_%s_%s" % \
                        (album['owner'], album['aid'], file_part))                            
                    print "Retrieving %s" % image_url
                    try:
                        # Grab the photo.
                        response = urllib2.urlopen(image_url)
                        image_data = response.read()
                        newfile = open(file_path, 'w')
                        newfile.write(image_data)
                        newfile.flush()
                        newfile.close()
                        # Set file modification/creation time to the original 
                        # upload date.
                        if photo['created'] > 666666:
                            print "creation date is %d" % photo['created']
                            os.utime(file_path, 
                                (photo['created'], photo['created']))
                    except urllib2.HTTPError as (e):
                        print "Error received during image grab: %s" % e.read()
Ejemplo n.º 31
0
    created_time_formatted = created_time.strftime('%d.%m.%Y %H:%M:%S')
    text_file.write("Timestamp: " + created_time_formatted);
    global_date_file.write(created_time_formatted + "\r\n")
    text_file.close()
    image_url = photo['images'][0]['source']
    urlretrieve(image_url, photo_path)

# BBB Fan Page: 111612552283016

fbconsole.AUTH_SCOPE = ['manage_pages', 'user_photos']
fbconsole.authenticate()
 
#page_id = raw_input("enter the id of the page:")
page_id = '111612552283016'
 
page = fbconsole.get('/'+page_id)
 
dirname = os.path.join(os.path.dirname(__file__), page.get('name'))
if not os.path.exists(dirname):
    os.mkdir(dirname)
 
albums = fbconsole.get('/'+page_id+'/albums', {'limit':500})
print "Found", len(albums), "albums"

global_date_file = open(os.path.join(os.path.dirname(__file__), 'dates.txt'), "w")
 
for album in albums.get('data', []):
    album_dirname = os.path.join(dirname, album.get('name'))
    print "\r\n###############################################################################"
    print "Downloading album", album.get('name') + "(" + str(album.get('count')) + " photos)"
    print "###############################################################################"
Ejemplo n.º 32
0
    subFolder="home"
  elif sys.argv[3] == 'h':
    subFolder="home"
  elif sys.argv[3] == 'm':
    subFolder="feed"
  else:
    subFolder="home"
#==== input control ====

if sys.argv[1] == 'p':
  status = fbconsole.post("/me/feed", {"message":sys.argv[2]})
elif sys.argv[1] == 'r':



  for post in fbconsole.iter_pages(fbconsole.get('/me/'+subFolder)):
    #==== MESSAGE ====
    print ''
    dedented_text = textwrap.dedent(post.get('message',defMsgs)).strip()
    print colorstr(textwrap.fill(dedented_text,width=40, initial_indent=' '+post.get('from',defMsgs).get('name',defMsgs)+":", subsequent_indent='    '),'YELLOW')
    #print post.get('comments',defComments)
    #print len(post.get('comments',defComments))
    #print post.get('comments',defComments)
    if post.get('comments',defComments).get('count',defMsgs) != 0:
      #==== PICTURE ====
      if post.get('picture',defPic)!='no pic':    
        #paraList = [' ','--term-width','--colors',post.get('picture',defPic)]                     
        #run('jp2p',paraList)
        paraList = [' ',post.get('picture',defPic),'-s','-o','tmp.jpg']
        print paraList        
        run('curl',paraList);
Ejemplo n.º 33
0
 def __init__(self):
     self.setup()
     self.me_id = fb.get("/me")['id']
Ejemplo n.º 34
0
#!/usr/bin/python
import fbconsole
fbconsole.APP_ID = '177876045644347'
fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access']
fbconsole.authenticate()
me = fbconsole.get('/me')
my_id = me['id']
statuses = fbconsole.fql("SELECT status_id,message FROM status WHERE uid=me()")
for status in statuses:
    s = fbconsole.get('/%s' % status['status_id'])
    print my_id+'_'+s['id']
    print s['message'] 
    print('#######################################################################################')
Ejemplo n.º 35
0
#!/usr/bin/python
import fbconsole
fbconsole.APP_ID = '177876045644347'
fbconsole.AUTH_SCOPE = [
    'publish_stream', 'publish_checkins', 'read_stream', 'offline_access'
]
fbconsole.authenticate()
me = fbconsole.get('/me')
my_id = me['id']
statuses = fbconsole.fql("SELECT status_id,message FROM status WHERE uid=me()")
for status in statuses:
    s = fbconsole.get('/%s' % status['status_id'])
    print my_id + '_' + s['id']
    print s['message']
    print(
        '#######################################################################################'
    )
Ejemplo n.º 36
0
    def update_facebook(self):
        """get the facebook access token for use with fbconsole by
        programmatic login to the facebook OAuth. Helpful resources:

        http://developers.facebook.com/docs/authentication/server-side/
        """

        for account in models.Account.objects.filter(type__exact="facebook"):
            other = json.loads(account.other)

            try:
                app_id = other["app_id"]
                client_secret = other["client_secret"]
                scope = other["scope"]
                email = other["email"]
                password = other["password"]
            except KeyError:
                msg = "every facebook Account must specify an "
                msg += "app_id, client_secret, scope, email, and password "
                msg += "in the `other` attribute json"
                raise KeyError(msg)

            # the state is a random string that is used in subsequent requests
            state = ''.join((random.choice(string.ascii_lowercase+string.digits)
                             for i in range(20)))

            # open the mechanize browser
            br = self.setup_browser()

            # 1. redirect the "user" to the OAuth dialog
            url = "https://www.facebook.com/dialog/oauth?" + urllib.urlencode({
                "client_id": app_id,
                "redirect_uri": "http://staging.datascopeanalytics.com/www",
                "scope": ','.join(scope),
                "state": state,
            })
            br.open(url)

            # 2. "user" is prompted to authorize your application
            br.select_form(nr=0)
            br.form["email"] = email
            br.form["pass"] = password
            response = br.submit()

            # 3. Once the user is redirected back to our app, parse out the
            #    code generated by facebook
            auth_url = urlparse.urlparse(response.geturl())
            oauth = urlparse.parse_qs(auth_url.query)
            assert oauth["state"][0] == state, "%s != %s" % (
                oauth["state"][0], state,
            )
            code = oauth["code"][0]

            # 4. Exchange the code for a user access token for this user's data
            url="https://graph.facebook.com/oauth/access_token?"
            url += urllib.urlencode({
                "client_id": app_id,
                "redirect_uri": "http://staging.datascopeanalytics.com/www",
                "client_secret": client_secret,
                "code": code,
            })
            br.open(url)
            response = br.response()
            oauth = urlparse.parse_qs(response.read())
            access_token = oauth["access_token"][0]

            # authenticate on facebook
            fbconsole.APP_ID = app_id
            fbconsole.AUTH_SCOPE = scope
            fbconsole.ACCESS_TOKEN = access_token

            if self.options["debug"]:
                print "ACCESS_TOKEN:", fbconsole.ACCESS_TOKEN

            # get all the posts for last year
            now = datetime.datetime.now()
            last_year = now - datetime.timedelta(days=365)
            opts = {
                "fields": "id,name", 
                "since": str(int(time.mktime(last_year.timetuple()))),
            }
            statuses = fbconsole.get("/132503850149625/posts", opts)


            # aggregate status count by date
            counter = Counter()
            fmt_str = "%Y-%m-%dT%H:%M:%S+0000"
            for status in statuses["data"]:
                t = datetime.datetime.strptime(status["created_time"], fmt_str)
                self.update_counter(counter, t)

            # insert data into the database
            self.update_db(account, counter)
Ejemplo n.º 37
0
    def update_facebook(self):
        """get the facebook access token for use with fbconsole by
        programmatic login to the facebook OAuth. Helpful resources:

        http://developers.facebook.com/docs/authentication/server-side/
        """

        for account in models.Account.objects.filter(type__exact="facebook"):
            other = json.loads(account.other)

            try:
                app_id = other["app_id"]
                client_secret = other["client_secret"]
                scope = other["scope"]
                email = other["email"]
                password = other["password"]
            except KeyError:
                msg = "every facebook Account must specify an "
                msg += "app_id, client_secret, scope, email, and password "
                msg += "in the `other` attribute json"
                raise KeyError(msg)

            # the state is a random string that is used in subsequent requests
            state = ''.join(
                (random.choice(string.ascii_lowercase + string.digits)
                 for i in range(20)))

            # open the mechanize browser
            br = self.setup_browser()

            # 1. redirect the "user" to the OAuth dialog
            url = "https://www.facebook.com/dialog/oauth?" + urllib.urlencode(
                {
                    "client_id": app_id,
                    "redirect_uri":
                    "http://staging.datascopeanalytics.com/www",
                    "scope": ','.join(scope),
                    "state": state,
                })
            br.open(url)

            # 2. "user" is prompted to authorize your application
            br.select_form(nr=0)
            br.form["email"] = email
            br.form["pass"] = password
            response = br.submit()

            # 3. Once the user is redirected back to our app, parse out the
            #    code generated by facebook
            auth_url = urlparse.urlparse(response.geturl())
            oauth = urlparse.parse_qs(auth_url.query)
            assert oauth["state"][0] == state, "%s != %s" % (
                oauth["state"][0],
                state,
            )
            code = oauth["code"][0]

            # 4. Exchange the code for a user access token for this user's data
            url = "https://graph.facebook.com/oauth/access_token?"
            url += urllib.urlencode({
                "client_id": app_id,
                "redirect_uri": "http://staging.datascopeanalytics.com/www",
                "client_secret": client_secret,
                "code": code,
            })
            br.open(url)
            response = br.response()
            oauth = urlparse.parse_qs(response.read())
            access_token = oauth["access_token"][0]

            # authenticate on facebook
            fbconsole.APP_ID = app_id
            fbconsole.AUTH_SCOPE = scope
            fbconsole.ACCESS_TOKEN = access_token

            if self.options["debug"]:
                print "ACCESS_TOKEN:", fbconsole.ACCESS_TOKEN

            # get all the posts for last year
            now = datetime.datetime.now()
            last_year = now - datetime.timedelta(days=365)
            opts = {
                "fields": "id,name",
                "since": str(int(time.mktime(last_year.timetuple()))),
            }
            statuses = fbconsole.get("/132503850149625/posts", opts)

            # aggregate status count by date
            counter = Counter()
            fmt_str = "%Y-%m-%dT%H:%M:%S+0000"
            for status in statuses["data"]:
                t = datetime.datetime.strptime(status["created_time"], fmt_str)
                self.update_counter(counter, t)

            # insert data into the database
            self.update_db(account, counter)
Ejemplo n.º 38
0
import fbconsole as fb
import shutil # for moving files
fb.APP_ID = '741896972509458'  #if you face error then reinstall fbconsole or logout
fb.AUTH_SCOPE = ['publish_stream','publish_actions','manage_pages','photo_upload','user_photos']
fb.logout() #helps to update token by deleting it. 
fb.authenticate() 




#tokens = []
pnames = []
for i in range(len(fb.get('/me/accounts')['data'])):
    #tokens.append(fb.get('/me/accounts')['data'][i]['access_token'])
    pnames.append(fb.get('/me/accounts')['data'][i]['name'])

for i in range(len(pnames)):
    print i,': ',pnames[i]

pageno = input('Enter page no.')





print 'Accessing ',pnames[pageno]
fb.ACCESS_TOKEN = fb.get('/me/accounts')['data'][pageno]['access_token']
#ACCESS_TOKEN = get('/me/accounts')['data'][0]['access_token']
#print fb.ACCESS_TOKEN
#print fb.get('/me')
Ejemplo n.º 39
0
    def loadData(self, preload):
        preload.isLoading = True
        try:
            fb.authenticate()
            print('Authenticating to Facebook...', end=' ')
            result = fb.get('/me', {'fields':'id,name'})
            user_id = result['id']
            user_name = result['name']
            print('Complete')
            
            # fake user data
            # user_id = '100001868030396'
            # user_name = 'Krerkkiat Chusap'
            # 
            # user_id = '252287594960325'
            # user_name = 'Test User #1'
            # 
            # user_id = '247059255488681'
            # user_name = 'Test User #2'

            # login to our server
            print('Authenticating to our server...', end=' ')
            login_data = bytes('{"type":"action", "value":"login", "uid":"%s"}' % user_id, 'utf-8')
            result = ConnectionManager.send(login_data)
            if ConnectionManager.isSuccessfulResponse(result):
                user = result['data']['user']
                hangar = result['data']['hangar']
                self._pilot = Pilot(user_id, user_name, user['score'], user['wave'], user['time'])
                print('Complete')
            else:
                print('Fail')
                SceneManager.exit()

            # fetch and register resource_register_data
            print('Loading resource register data...', end=' ')
            result = ConnectionManager.send('''{"type":"action","value":"get","target":"resource_register_data"}''')
            if ConnectionManager.isSuccessfulResponse(result):
                print('Complete')
                print('Registering resource register data...', end=' ')
                for key in result['data']:
                    if key == 'surface':
                        self.regisSurfaces(result['data']['surface'])
                    elif key == 'sound':
                        pass
                    elif key == 'background_music':
                        pass
                    elif key == 'background_image':
                        pass
                print('Complete')

            # register local surface
            print('Registering local resource register data...', end=' ')
            SurfaceManager.register('upBtn', os.path.join(Config.assetsRoot, 'ui', 'up_btn.png'), convert_alpha=True)
            SurfaceManager.register('downBtn', os.path.join(Config.assetsRoot, 'ui', 'down_btn.png'), convert_alpha=True)
            SurfaceManager.register('leftBtn', os.path.join(Config.assetsRoot, 'ui', 'left_btn.png'), convert_alpha=True)
            SurfaceManager.register('rightBtn', os.path.join(Config.assetsRoot, 'ui', 'right_btn.png'), convert_alpha=True)
            print('Complete')
        except urllib.error.URLError as e:
            print('[Error]: Can not connect to server:', e.reason, e)
            preload.nextScene = None
            SceneManager.exit()
        except Exception as e:
            print('[Error]: Unexpected exception:', e.reason, e)
            preload.nextScene = None
            SceneManager.exit()
        preload.isLoading = False
Ejemplo n.º 40
0
cuts = ["no"]

myname = ""

postid = ""

liked = []

while(1):
    #ser.write("hello")
    #print "hello"
    #time.sleep(0.2)
    line = ser.readline()
    print "heard: "+line
    if line.startswith(".h"):
        info = fbconsole.get('/me')
        myname = info["first_name"]
        print "hello "+myname
        ser.write(".h"+myname+"\n")
        waitforack(ser, "h")
    if line.startswith(".f"):
        newsfeed = fbconsole.get('/me/home')
        newsfeedData = newsfeed["data"]
        nfDataClean = newsfeedData
        it = iter(nfDataClean)
        #for i in range(0, len(newsfeedData)-2): #last entry is paging stuff
        try:
            while 1:
                newsItem = it.next()
                #print newsItem["id"]
                if newsItem["type"] in bannedTypes:
Ejemplo n.º 41
0
fbconsole.authenticate()
sys.stdout = sys.__stdout__

sys.stderr.write(mystdout.getvalue())

connectors = [
    "accounts", "activities", "adaccounts", "albums", "apprequests", "books",
    "checkins", "events", "family", "feed", "friendlists", "friendrequests",
    "friends", "games", "groups", "home", "inbox", "interests", "likes",
    "links", "locations", "messagingfavorites", "movies", "music",
    "mutualfriends", "notes", "notifications", "outbox", "payments",
    "permissions", "photos", "picture", "posts", "scores", "statuses",
    "tagged", "television", "updates", "videos"
]

fb_data = fbconsole.get("/me")

for connector in connectors:
    sys.stderr.write("Loading: " + connector + "\t")
    try:
        connected_data = fbconsole.get("/me/" + connector)
        fb_data[connector] = connected_data
        sys.stderr.write("success\n")
    except urllib2.HTTPError:
        sys.stderr.write("HTTPError: Maybe permissions\n")
    except ValueError:
        sys.stderr.write("ValueError: Probably not decodable to JSON\n")

fbconsole.logout()

print json.dumps(fb_data, sort_keys=True, indent=4)
Ejemplo n.º 42
0
	  def getFBPicture():
		fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access']
		fbconsole.authenticate()
		file = urllib2.urlopen('https://graph.facebook.com/%s?access_token=%s&fields=picture' % (fbconsole.get('/me')['id'], fbconsole.ACCESS_TOKEN))
		data = json.load(file)
		return data["picture"]