예제 #1
0
class FqlTask(BaseTask):
    """
    Encapsulates a single FQL query
    The optional `storage` and `cache` classes allow the contents
    of a FQL call to be stored and retrieved in lieu of re-running the query
    """
    def __init__(self, fql, access_token, storage=None, prefer_cache=False, store_results=True, override_name=None):
        self.fql = merge_spaces(fql)
        self.storage = storage
        self.prefer_cache = prefer_cache
        self.store_results = store_results
        self.graph_api = GraphAPI(access_token)

        super(FqlTask, self).__init__(override_name)


    def get_results(self):
        if self.prefer_cache:
            # Check the cache for the query
            cache_result = self.storage.retrieve(self.fql)
            if cache_result:
                return cache_result
        print 'running ' + str(self.fql)
        fql_results = self.graph_api.fql(self.fql)

        # TODO: if there was an error, look in the cache as a fallback
        if self.store_results and self.storage:
            # Store the results, using the storage class
            self.storage.store(
                query_type=self.name,
                query=self.fql,
                results=fql_results,
            )
        return fql_results
예제 #2
0
def magic(oauth, latlong, dist=1000, limit=5, verbose=False):
  g = GraphAPI(oauth)

  # search a bunch of stuff, until no more results
  # https://graph.facebook.com/search?type=location&center=[lat],[long]&distance=[dist]&access_token=[oauth]
  search = []
  params = {"type":"location", "center":latlong, "distance":dist, "access_token":oauth}
  while limit > 0:
    res = g.request("search", params)
    if len(res.keys()) == 0 or not res.get("paging"):
      break
    search += res["data"]
    params = dict(urlparse.parse_qsl(res["paging"]["next"].split("?")[1]))
    limit -= 1

  if verbose == True:
    pp.pprint(search)

  # filter
  places = g.fql("SELECT name, location, type, page_id FROM page where page_id in (%s)" % string.join([i["place"]["id"] for i in search], ", "))
  desired_place_types = ["RESTAURANT/CAFE", "BAR", "CLUB", "FOOD/BEVERAGES", "LOCAL BUSINESS"]
  limit = 1;
  filtered_places = {}
  for i in places:
    if i["type"].upper() in desired_place_types:
      name = i["name"]
      filtered_places[name] = i
      filtered_places[name]["data"] = []
      page = g.get_object(str(i["page_id"]) + "/picture", width="600")
      if page.get("url"):
        filtered_places[name]["photo_url"] = page["url"]
      del i["name"]

  if verbose == True:
    pp.pprint(filtered_places)

  # sort by places
  for i in search:
    if i["place"]["name"] in filtered_places:
      filtered_places[i["place"]["name"]]["data"].append(i)
      del i["place"]

      # get fb picture urls if can
      if i["type"] == "photo":
        photo = g.get_object(i["id"])
        if photo.get("images"):
          i["photo_url"] = photo["images"]

  if verbose == True:
    pp.pprint(filtered_places)

  return filtered_places
예제 #3
0
def grab_users_posts(facebook_id, start_date=None, end_date=None):
    """
    Grabs users posts from facebook and saves to database

    facebook_id -- users id in facebook
    start_date -- exclude posts created before this date, have to be datetime
    end_date -- exclude posts created after this date, have to be datetime
    """
    if start_date:
        assert type(start_date) is datetime
    if end_date:
        assert type(end_date) is datetime

    user_social_profile = UserSocialAuth.objects.get(uid=facebook_id)

    graph = GraphAPI(user_social_profile.extra_data['access_token'])

    graph.extend_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_API_SECRET)

    # TODO: create real pagination
    limit = 100500

    query = 'SELECT created_time, message, permalink FROM stream ' \
            'WHERE source_id = %(user_id)s and message != ""'

    if start_date:
        query += 'and created_time > %d' % int(time.mktime(start_date.timetuple()))
    if end_date:
        query += 'and created_time < %d' % int(time.mktime(end_date.timetuple()))

    query += ' LIMIT %(limit)d'
    res = graph.fql(query % {'user_id': facebook_id, 'limit': limit})

    for post in res:
        if Post.objects.filter(link=post['permalink']).exists():
            continue

        post = Post(user=user_social_profile.user,
                    created=datetime.fromtimestamp(post['created_time']),
                    content=post['message'],
                    link=post['permalink'],
                    )
        mood_stats = get_text_sentiment_analysis(post.content)
        post.mood = mood_stats['total']
        post.mood_positive = mood_stats['pos']
        post.mood_negative = mood_stats['neg']
        post.mood_neutral = mood_stats['neutral']

        post.save()

    return True
#!/usr/bin/env python
'''
This is a simple python script to fetch upcoming birthdays of your facebook friends and recieve the same on your cell phone via text message. Replace
'''
from facebook import GraphAPI
import datetime
from twilio.rest import TwilioRestClient
import twilio
gp=GraphAPI("xxxx")#replace xxxx with your facebook access token
date1= datetime.date.today() + datetime.timedelta(days=1) # days=2 will retrieve birthdays on the day after tomorrow and so on
date=date1.strftime("%m/%d")
month = date[5:7]
day =date[8:10]
print month , day
query='SELECT name,birthday_date FROM user WHERE uid IN(SELECT uid2 FROM friend WHERE uid1=me()) AND strlen(birthday_date) !=0 AND substr(birthday_date,0,5)="nnnn"'.replace("nnnn",date)
map= gp.fql(query)
if len(map['data']):
    text="Birthdays-%s\n".replace("%s",date)
    for i in range(len(map['data'])):
        text+=str(i+1) +"."+map['data'][i]['name']+" "
else:
    text="No Birthdays!"
twilioNumber="xxxx" #Your twilio number
sendTo="xxxx" #phone Number you want recieve texts on
accountSid="xxxx" #Your Twilio account Sid
authToken="xxxx" #Your Twilio account auth token
try:
    device = TwilioRestClient(accountSid,authToken)
    message = device.sms.messages.create(
        body=text,
        to=sendTo,