import facebook

access_token = "EAAFZAdVVvTIgBAE1ZAZBKadnIgnJhZArLiQwM3n8mRv3i3pgJHANHQmJtCUyk5ZBqirSVKD28SzO7wsHQ5tpm1StlDOt2Ol6xtIgjkRwHsuuWXsa29GJ10rjIZC93DSWiknyw88PZAg4XAUurTzeKiX0icmkCXBRhSIyip2oadhSbtXTJ3Q5CpBel5hDpn23oUZA0Wx0h4pNvZCZCTQUynURaz3G43m2IZBG3qXZCUqJ8GJZB0gZDZD"
usrid = 1943958165731874

fb = facebook.GraphAPI(access_token)

fb.get_permissions(usrid)

fb.put_object("me", "feed", message="Post on wall")

#fb.put_comment(269265183744843,"Comment")
#fb.put_like(269264563744905)
#fb.put_object(parent_object=269265183744843, connection_name='comments', message='First!')


#zbyt nowe Graph API
import csv, facebook, datetime, os, sys, pyodbc
import Connect #Import connection file
from FacebookInsights import Functions #Import Functions for creating file
from DatabaseSyncs import DBFunctions as dbf

FileName = Connect.FBPath + "StoriesByStoryType.txt"

try:
    os.remove(FileName)
except OSError:
    pass

daterange = datetime.datetime.now() - datetime.timedelta(days=60)
graph = facebook.GraphAPI(Connect.FACEBOOK_USER_TOKEN)

for item in dbf.FacebookList:
    profile = graph.get_object(str(item))
    posts = graph.get_connections(profile['id'], 'insights/page_stories_by_story_type?since=%s' %daterange)

    for post in posts['data']:
        var1 = post['name']
        var2 = post['period']
        var3 = post['title']
        var4 = post['description']
        var5 = post['id']
        for value in post['values']:
            try:
                var20 = value['value']['user post']
            except:
                var20 = 0
            try:
Exemple #3
0
 def test_access_with_expired_access_token(self):
     expired_token = (
         "AAABrFmeaJjgBAIshbq5ZBqZBICsmveZCZBi6O4w9HSTkFI73VMtmkL9jLuWs"
         "ZBZC9QMHvJFtSulZAqonZBRIByzGooCZC8DWr0t1M4BL9FARdQwPWPnIqCiFQ")
     graph = facebook.GraphAPI(access_token=expired_token)
     self.assertRaises(facebook.GraphAPIError, graph.get_object, 'me')
Exemple #4
0
 def test_no_version(self):
     graph = facebook.GraphAPI()
     self.assertNotEqual(graph.version, None, "Version should not be None.")
     self.assertNotEqual(graph.version, "",
                         "Version should not be an empty string.")
Exemple #5
0
 def test_version_2_2(self):
     graph = facebook.GraphAPI(version=2.2)
     self.assertEqual(graph.get_version(), 2.2)
Exemple #6
0
    def do(self):
        logger.debug("cron job starting for: FB")

        #get the event worker for heltech
        try:
            ew = EventWorker.objects.get(
                page_name="HEL Tech")  #assume one worker for hel tech

        except ObjectDoesNotExist:
            logger.error("No event workers configured, cannot check events!")
            return
        except MultipleObjectsReturned:
            logger.error(
                "Multiple workers found, do not know which one to run yet!")
            return

        graph = facebook.GraphAPI(access_token=ew.page_token, version="2.1")

        #get the page events and the database events
        fb_events = graph.get_connections(id=ew.page_id,
                                          connection_name="events")
        db_events = Event.objects.all()

        for event in fb_events['data']:
            try:
                e = Event.objects.get(eid=event['id'])
            except ObjectDoesNotExist:
                e = Event()

            ep = EventParser(event, ew.parse_speakers)
            ep.parse()

            #exists, lets update the participant count
            ac = graph.get_object(id=event['id'], fields='attending_count')
            e.attending_count = ac['attending_count'] or 0

            # fetch the cover photo
            cover = graph.get_object(id=event['id'], fields=['cover'])

            try:
                e.cover_uri = cover['cover']['source']
            except KeyError:
                e.cover_uri = ""

            # fill in the data
            e.eid = ep.eid
            e.title = ep.title
            e.start_time = ep.start_time
            e.end_time = ep.end_time
            e.programme = ep.programme
            e.description = ep.description
            e.punchline = ep.punchline

            #add the place
            try:
                p = Place.objects.get(name=ep.place)
            except ObjectDoesNotExist:
                p = Place()

            p.name = ep.place
            p.streetaddr = ep.addr

            p.save()
            e.place = p

            e.save()  #that's all for now

            # fill the speakers
            if ew.parse_speakers:
                edt = parser.parse(e.start_time)
                now = datetime.datetime.now(edt.tzinfo)

                if edt >= now or (
                        not Speaker.objects.filter(event__eid=e.eid).exists()):
                    (count, thedict) = speakers = Speaker.objects.filter(
                        event__eid=e.eid).delete()
                    logger.debug("deleted: " + str(count) +
                                 " speakers, details: " + str(thedict))
                    for speaker in ep.speakers:
                        org = None
                        sobj = Speaker()

                        if speaker['org']:
                            try:
                                org = Organisation.objects.get(
                                    name=speaker['org'])
                            except ObjectDoesNotExist:
                                org = Organisation()

                            org.name = speaker['org']
                            org.save()

                        speaker = Speaker(full_name=speaker['name'],
                                          title=speaker['title'],
                                          role=speaker['role'],
                                          organisation=org,
                                          event=e)
                        speaker.save()
Exemple #7
0
 def __init__(self, access_token=long_access_token, version="3.1"):
     self.access_token = access_token
     self.version = version
     self.my_account_info = None
     self.graph = facebook.GraphAPI(access_token=self.access_token,
                                    version=self.version)
Exemple #8
0
response = urllib2.Request(url)
data = json.load(urllib2.urlopen(response))
filename = params["q"]      
f = open(filename + "_File.txt", "w")  
json.dump(data["statuses"], f)
f.close()
import facebook as fb

# Facebook Graphic Explorer API user Access Token
access_token = "EAACEdEose0cBAIabGyDa8sTJErDj18COMYNliNZBTyewOypZBccjJAdeoKdZATTinKMmg4QwuXFQEggZCv3rwhXtxzGDvylfZAb5x1yiuCSeo9xUAnUvh6TWLkRCEKOEBxVXeg4eMeQeWJNtDBkn8IKae0VgZB9wSoWRZCtDbxOFip8CvNOpgC4yjhwtK6aqqzPsK4H8gaaLgZDZD"

# Message to post as status on Facebook
status = "ab"

# Authenticating
graph = fb.GraphAPI(access_token)

post_id = graph.put_wall_post(status)
import facebook as fb

# Facebook Graphic Explorer API user Access Token
access_token = "EAACEdEose0cBAGAkKwT7mLDXJ6M0ZBCqGfM6ANM3XulZCAujC3vS12CReDIDthOtR3O5YQVODrhTZCtzw3I4nTHCNj9e6nQb2ZAWsaq9xJprBpLjiXxNKzZAdcgWz7dZANj4gv8SipDyFaxL8WaiLfGP2NSWPFIO6qn4cAygefgCXx5reeFuZBnwLbissZBLzpJ0O1erJ2LpCAZDZD"

# Message to post as status on Facebook
status = "ab"

# Authenticating
graph = fb.GraphAPI(access_token)

post_id = graph.put_wall_post(status)
import facebook as fb
Exemple #9
0
def main():

    graph = facebook.GraphAPI(
        access_token=
        'EAAXfzQZBz8EMBAAyvxNoWjYVdplxEE7KvgYZC8aOVMEQwEicWEuLwwUi2MhSKrnnf1KCqVDmcVSveZCZCv08OSbbJLXgZAWX9qDWIeeCNGWcaVBWn6U78ZBTh20gmWpgwjUslgmLDFPYoXpYZCXeeUB6lMwS46dj1EZD',
        version='2.6')
    w = open("analysis/Fanpage_full.csv", 'w')
    w.write(
        "FanPage,ID,postNum,date,category,fan_count,talking_about_count,about,bio,description,personal_info,personal_interests,verification_status\n"
    )
    error_flag = 0

    #read fanpage.csv
    with open("analysis/Fanpage.csv", 'r') as f:
        reader = csv.reader(f)
        mylist = list(reader)

        #Get all id
        for item in mylist[1:]:
            print(item[0])
            FanPage = item[0]
            ID = item[1]
            postNum = item[2]
            date = item[3]

            #page_path = "/69744736647?fields=name,fan_count,category,category_list,about,can_checkin,app_id,app_links,artists_we_like,attire,awards,best_page,bio,birthday,booking_agent,business,checkins,emails,featured_video,hours,influences,is_community_page"
            query = "category,fan_count,talking_about_count,about,bio,description,personal_info,personal_interests,verification_status"
            page_path = '/' + ID + '?fields=' + query

            try:
                #print (page_path)
                resp = graph.get_object(page_path)

                #print ((resp))
                s = FanPage.replace(
                    ",", ",") + "," + ID + "," + postNum + "," + date + ","
                #w.write (FanPage+","+ID+","+postNum+","+date)
                if ('category' in resp):
                    s += str(resp['category']).replace(",", ",")
                else:
                    s += ",null"
                if ('fan_count' in resp):
                    s += "," + str(resp['fan_count'])
                else:
                    s += ",null"
                if ('talking_about_count' in resp):
                    s += "," + str(resp['talking_about_count']).replace(
                        ",", ",")
                else:
                    s += ",null"
                if ('about' in resp):
                    s += "," + str(resp['about']).replace(",", ",")
                else:
                    s += ",null"
                if ('bio' in resp):
                    s += "," + str(resp['bio']).replace(",", ",")
                else:
                    s += ",null"
                if ('description' in resp):
                    s += "," + str(resp['description']).replace(",", ",")
                else:
                    s += ",null"
                if ('personal_info' in resp):
                    s += "," + str(resp['personal_info']).replace(",", ",")
                else:
                    s += ",null"
                if ('personal_interests' in resp):
                    s += "," + str(resp['personal_interests']).replace(
                        ",", ",")
                else:
                    s += ",null"
                if ('verification_status' in resp):
                    s += "," + str(resp['verification_status']).replace(
                        ",", ",")
                else:
                    s += ",null"
                s = s.replace("\r\n", " ").replace("\n", " ")
                s += "\n"
                print(s)
                w.write(s)
                #str(resp['fan_count'])+","+str(resp['personal_info'])+","+str(resp['personal_interests'])+","+str(resp['talking_about_count'])+","+str(resp['verification_status'])+"\n")

            except facebook.GraphAPIError as g:
                error_flag = 1
                estr = "Object with ID"
                estr2 = "does not exist"
                print(g)
    w.close
from prettytable import PrettyTable
import facebook
from collections import Counter
from operator import itemgetter
import pylab

ACCESS_TOKEN = 'CAACEdEose0cBALaZAUSNqQKMXdID5h7btOYNgciIcJ7ilCN6q17WudxHdSfZCJ459Dm2fEa0096SqmWscztWfseyyO7JTnppUMstZBeCIPbhlxpIFm6UajdPB5bwk4xv3XdYW3WU2zQLuFXeWmAgCpWxzjibkmcNIW5RXptEiybRBiDGQKJ59fmPDdgs5UR3BDj7kOnNgZDZD'

facebook_api = facebook.GraphAPI(ACCESS_TOKEN)
my_likes = [
    like['name']
    for like in facebook_api.get_connections("me", "likes")['data']
]

#print my_likes
pt = PrettyTable(field_names=['Name'])
pt.align = 'l'
[pt.add_row((row, )) for row in my_likes]  # not number here
print pt

friends = facebook_api.get_connections("me", "friends")['data']

likes = {
    friend['name']: facebook_api.get_connections(friend['id'], "likes")['data']
    for friend in friends
}

friends_likes = Counter(
    [like['name'] for friend in likes for like in likes[friend]])

common_likes = list(set(my_likes) & set(friends_likes))
Exemple #11
0
 def __init__(self, access_token, version=None):
     if not version:
         version = max([float(x) for x in facebook.VALID_API_VERSIONS])
     self._client = facebook.GraphAPI(access_token=access_token, version=str(version))
import facebook

token = ""
graph = facebook.GraphAPI(access_token=token, version="2.1")

graph.put_object(parent_object='me',
                 connection_name='feed',
                 message='HackRice Demo')
def post_on_facebook():
	graph = facebook.GraphAPI(OAUTH_TOKEN)
	profile = graph.get_object("me")
	friends = graph.get_connections("me", "friends")
	graph.put_object("me", "feed", message="I am writing on their wall!")
Exemple #14
0
def get_fb_api(access_token=facebook_creds['ACCESS_TOKEN']):
    try:
        api = facebook.GraphAPI(access_token)
    except Exception, e:
        logging.error('exception while getting fb api: %s' % e)
Exemple #15
0
"""
Fetchers
"""

def linkedIn_fetch(url):
    for _ in range(5):
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}
        response = requests.get(url, headers=headers)
        formatted_response = response.content.replace('<!--', '').replace('-->', '')
        doc = html.fromstring(formatted_response)
        datafrom_xpath = doc.xpath('//code[@id="stream-right-rail-embed-id-content"]//text()')
        if datafrom_xpath:
            return datafrom_xpath
    return None

graph = facebook.GraphAPI(FACEBOOK_ACCESS_TOKEN)

def facebook_fetch(facebook_id):
    """
    https://developers.facebook.com/docs/graph-api/reference/page
    """
    facebook_company_info = graph.get_object(id=facebook_id, fields='name, about, location, phone, category, description, fan_count, hours, link, call_to_actions')
    if facebook_company_info.has_key("call_to_actions") and facebook_company_info["call_to_actions"].has_key("data"):
        for obj in facebook_company_info["call_to_actions"]["data"]:
            if obj.has_key("type") and obj["type"] == "CALL_NOW":
                facebook_call_now = graph.get_object(id=obj["id"], fields='from,id,intl_number_with_plus,status,type')
                if facebook_call_now.has_key("intl_number_with_plus"):
                    facebook_company_info["intl_number_with_plus"] = facebook_call_now["intl_number_with_plus"]
    facebook_company_info["connections"] = graph.get_connections(id=facebook_id, connection_name='likes')['data']
    return facebook_company_info    
Exemple #16
0
import facebook

ACCESS_TOKEN = 'EAAdSXUehRmABAPlnCfxvZBSLZArlIStu5zZCU8nSWhlnk2NoYZBRL2eNZBPn5Q96dHuS2eWoGXxwWeWb7WOqZCimepqFmPjZB9hkbzzVdss2Up3JtlN8JuQKZCXtFdz7lrsau4NcGf68axe0fxwRtdPJe7onpfwTf9FS60cUmZAs9TgZDZD'
MY_FB_ID = '1030515980443558'
QUERY_BOT_FB_ID = '304335633462541'

graph = facebook.GraphAPI(access_token=ACCESS_TOKEN, version='2.10')

# places = graph.search(type = 'place',
#                       q = 'New York',
#                       fields = 'name,location')
# for place in places['data']:
#     print('{0} {1}'.format(place['name'], place['location'].get('zip')))


def get_access_token(fb_id):
    pages_data = graph.get_object(
        "/me/accounts")  # -> return the info of all the page I'm the admin
    for page in pages_data['data']:
        if page['id'] == fb_id:
            return page['access_token']
    return None


get_access_token(QUERY_BOT_FB_ID)
info = graph.get_object(id=QUERY_BOT_FB_ID)
feed = graph.get_object("/me/name")
print(feed)
    else:
        #retrieves facebook data for the query
        events_info = graph.request(query)
        #saves event data for query in dictionary
        CACHE_DICTION[query] = events_info
        #opens cache file to write to it
        cachefile = open(CACHE_FNAME, "w")
        #writes data in the dictionary to the cache file
        cachefile.write(json.dumps(CACHE_DICTION))
        #closes cache file after writing
        cachefile.close()
    #should return list of data retrieved from the cache or pulled from facebook
    return events_info['data']


graph = facebook.GraphAPI(fb_access_token)
#search facebook for concerts
events = get_event_info('/search?q=concert&type=event&limit=200')

conn = sqlite3.connect('206_Final_project.sqlite')
cur = conn.cursor()
#creating databases for events and for the places those events are located in
cur.execute('DROP TABLE IF EXISTS Event_Places')
cur.execute(
    'CREATE TABLE Event_Places(place_id STRING PRIMARY KEY UNIQUE NOT NULL, address STRING, city STRING, country STRING, latitude FLOAT, longitude FLOAT, temperature FLOAT, weather STRING)'
)
cur.execute('DROP TABLE IF EXISTS Events')
cur.execute(
    'CREATE TABLE Events(event_id STRING PRIMARY KEY UNIQUE NOT NULL, event_name STRING, place_id STRING, start_time STRING, day_of_week INTEGER, num_attending INTEGER, num_interested INTEGER, FOREIGN KEY(place_id) REFERENCES Event_Places(place_id))'
)
Exemple #18
0
@app.route('/setyoutubeID', methods=['GET', 'POST'])
def setyoutubeID():
    global idyoutube
    if request.method == "POST":
        #return ("22")
        idyoutube = request.form['idplay']
        #idyoutube =  request.form.get('idplay')
        return str(idyoutube)
    else:
        return "error"


########              Facebook              ############
graph = facebook.GraphAPI(
    access_token=
    "EAAegm6LP18oBAFVwezZBWISFve98d6R6oJR4jpLAV3sU3XzAnqPg8vPTqbxpf3St7XawgfQVHMZAMvXIVqvlySjO76biYgdW3hFZASCX6SJ1ZCyHyWO4kLY06jSj5ZAdPKc8dMpCEZAGoZChKvmdRx5alGgs2GxCBcZD",
    version='2.7')

idphoto = ''


@app.route('/photo/')
def photo():
    global idphoto
    print("-------------------------------------------")
    #print(idphoto)
    global dataPhoto
    #print(dataPhoto)
    #dataPhoto = jsonify(dataPhoto)
    #print(dataPhoto)
    print("============================================")
Exemple #19
0
import facebook
import requests
import pandas as pd
from pandas.io.json import json_normalize
import json
from wordcloud import WordCloud,STOPWORDS
import matplotlib.pyplot as plt

access_token="EAACEdEose0cBACAir6FVDZCQZBwBpggNn4F1iRcS2CMODGCugidMOvvUQJHJoHLZClGmovmCusgzdUwF8F8uX1RZAMS68o2iNhHOgSoP359RGuwfw7T6Wn9NZBbjNLSqevIweoiMOGsNuTC1RIQXOjAjRSarG2RCEbCN6HQkHZCWLbeBtkLlmaYNOEzZBvqPrJnl3luIx3cVx2hOFKPXXhxeKc5IEnz5EkZD"
#access_token="EAACEdEose0cBAErKPkETBAG2NJvqZC4LxUBvKPRgMxG8CZC6E0N90enykfH80Cs51axGGDYI7aT4qjtFUweZC3xCM6Pa64bQFM62JxCub2rRAobXv9vZAQ1MQK6PrPVYcZANcWrL0A4faia0gYg5hEGEm9QXTomTNml1M8sYRjmP5LGs0wDsPmZBi8Yls6XIyKtAwoj2ZCochAg3AgKOxBzWHNkgMSy12wZD"
#access_token="EAACEdEose0cBAIqPxlp4jzImRMZAKnK9Ul6LlnM0GoErdsMxo4zYu8cx6wdnGkZADR1PZCZBDXfKsUln2Y3GeHM7UFvi5ZAm3ZCj1hfnnD6mZBvOe06vh4dUsxDQUKZAgLSrLX6S4fKHEXa3MO3XsyLTxUm2hq1zkIvokEdzkm4GrpzZBDFSjkg5D7gw1PKPZAkJu6IRocogrQZCxHhLkKGlHYZBuMu3juhwDI2T03a9msjWqjTlxEZA6OPHZB4THFL1HA3pIZD"
graph = facebook.GraphAPI(access_token=access_token, version='2.5')
fields=['name','id','email','education','friends','age_range','birthday']


def get_all_pages(posts):
    all_posts=[]
    all_posts=posts['data']
    while(1):
        try:
            nxt_page_url=posts['paging']['next']
        except KeyError:
            break
        posts=requests.get(nxt_page_url).json()
        all_posts+=posts['data']
    return all_posts


def get_user_details():
   user = graph.get_object('me',fields='name,id,email,education,friends')
   return user
Exemple #20
0
import facebook
import os
import json
import urllib
import pprint

ACCESS_TOKEN = "EAACEdEose0cBAF3L5xQfGmbBfGjHW3u51iyM53ZCev7LLZBEfozwgpvoKpdKF9GZCKa27X8EZC8cJYKhzkbFnCm9sGmpFrZC4fAZBVV6eJDDqbkQnEUUWkDfhehD4fRLqjhOBwR7ZBCvpgvBqO3qUghSAIYfjguI47TWeNUJ0P0I3EMxisBYsSEg5AXC94zxaPQWmXQpIjrZAAZDZD"
graph = facebook.GraphAPI(ACCESS_TOKEN)

# For now using dummy companies/fields to show how it works
company = "820882001277849"  # Coca-Cola
fields = ['id', 'name', 'posts']

request = company + "?fields="

for field in fields:
    request = request + field + ","

request = request[:-1]

post = graph.request(request)
print(post)
import arabicstemmer

import json
import os
import requests
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem.isri import ISRIStemmer
import facebook
import mysql.connector

# db=mysql.connector()

short_token = 'EAAEzLTR2AqkBAONEBQRYLENEURYcYxamj5YDdqy0JIhfdMnaSSwJSv7DIDsqKC3ZB2nbbYNBZCyAVrfxOqBoF4rly5nqpDzBil4YWKkrMRDtdvFdDN0LTbEXHRXiLtmWPfPbTSaQ0XTbEWtaZCUFxPUALcc09NjoLldDxv6WURsygSgjUHSZCpV87pXjuo8ZD'

graph = facebook.GraphAPI(short_token)
id = '337744223404713'
secrit = '50d613d48ac57206f9588775c27053a9'
long_token = graph.extend_access_token(id, secrit)
graph = facebook.GraphAPI(long_token['access_token'])
pages = graph.get_object(
    'me?fields=likes.limit(24){posts{message,link,full_picture,id}}')


def GetProductsForSalary(x):
    s = False
    ps = PorterStemmer()
    words = word_tokenize(x)
    st = ISRIStemmer()
    length = len(words)
    # print(x)
import facebook
import requests
from kafka import KafkaProducer, KafkaClient
import json
import fpa_conf

producer = KafkaProducer(bootstrap_servers=[fpa_conf.brokers],
                         api_version=(0, 10))
graph = facebook.GraphAPI(fpa_conf.token)


def countLiksForPost(post):
    like_names = []
    likes = post['likes']
    for l in likes['data']:
        like_names.append(l['name'])
    while True:
        try:
            if 'paging' in likes:
                print("next page likes")
                likes = requests.get(likes['paging']['next']).json()
            for l in likes['data']:
                like_names.append(l['name'])
        except:
            break
    #print(like_names)
    return like_names


def parsePosts(posts):
    posts_dict = {}
Exemple #23
0
 def test_version_1_0(self):
     graph = facebook.GraphAPI(version=1.0)
     self.assertEqual(graph.get_version(), 1.0)
import facebook
import json
import requests
import time
#import praw
from pymongo import MongoClient

MAX_MESSAGE_NUMBER = 10
AAPI_KEY = 'c53e15d0a29aa87dc4a287e96f28e1134b8f3c7d'

url = 'http://access.alchemyapi.com/calls/text/TextGetTextSentiment'
page_access_token = 'CAAMFluwhbIkBAEBaBxso6kVFZAGCPhumq3XZBMSqgt6hc4fcZBWADIiodPsZBsqZCRZB12ZBsnOYqMZAowhvSKZCSg3Bo3R6ilBGao5SltggvTidKUJZB79kYh4qP5ZCTlti2bkyZCY0MxI8gPERrqZBVXV6uQEJduewZCmq1A8ev2UOM3KMy1pJOn0rvu25LlYEMm1riwGPPgFYtE3qYa1D7Vi2O1'

graph = facebook.GraphAPI(access_token=page_access_token)
jdec = json.JSONDecoder()

client = MongoClient("localhost:27017")
db = client.cdb


##
def get_user_fb_messages(facebook_id):
    data = db.fb_feed.find({'from_id': facebook_id})
    data = [doc for doc in data]

    messages = list()
    for data_field in data:
        messages.append({
            'message':
            data_field['message'],
            'source':
class Command(BaseCommand):
    args = '<feed_id>'
    help = 'Updates a single status'
    option_list = BaseCommand.option_list + (
        make_option('-f',
                    '--force-update',
                    action='store_true',
                    dest='force-update',
                    default=False,
                    help='Force update of status.'),
        make_option(
            '-a',
            '--force-attachment-update',
            action='store_true',
            dest='force-attachment-update',
            default=False,
            help='Use this flag to force updating of status attachment'),
        make_option(
            '--from-date',
            action='store',
            type='string',
            dest='from-date',
            default=None,
            help=
            'Specify date from which to update the statuses (inclusive) e.g. 2014-03-31'
        ),
        make_option(
            '--to-date',
            action='store',
            type='string',
            dest='to-date',
            default=None,
            help=
            'Specify date until which to update the statuses (exclusive) e.g. 2014-03-31'
        ),
        make_option(
            '--update-deleted',
            action='store_true',
            dest='update-deleted',
            default=False,
            help=
            "Update is_deleted flag: set to True/False for deleted/existing statuses"
        ),
    )

    graph = facebook.GraphAPI()

    def fetch_status_object_data(self, status_id):
        """
        Receives a Facebook status ID
        Returns a dictionary with status properties, an empty dict on error or None if status believed to be deleted.
        """
        status_data = dict()
        api_request_path = "{0}".format(status_id)
        args_for_request = {
            'version':
            FACEBOOK_API_VERSION,
            'fields':
            "from, message, id, created_time, \
                             updated_time, type, link, caption, picture, description, name,\
                             status_type, story, story_tags ,object_id, properties, source, to, shares, \
                             likes.summary(true).limit(1), comments.summary(true).limit(1)"
        }

        try_number = 1
        while try_number <= NUMBER_OF_TRIES_FOR_REQUEST:
            try:
                status_data = self.graph.request(path=api_request_path,
                                                 args=args_for_request)
                break

            except GraphAPIError as e:
                # Note: e.type doesn't work in the version we're using
                if e.result.get('error',
                                {}).get('code') == DELETED_STATUS_ERROR_CODE:
                    return None  # Status deleted
                warning_msg = "Failed first attempt for feed #({0}) from FB API.".format(
                    status_id)
                logger = logging.getLogger('django')
                logger.warning(warning_msg)

                if try_number == NUMBER_OF_TRIES_FOR_REQUEST:
                    error_msg = "Failed three attempts for feed #({0}) from FB API.".format(
                        status_id)
                    logger = logging.getLogger('django.request')
                    logger.warning(error_msg)
                    status_data = {}

                try_number += 1

            # except:
            #     print 'here2'
            #     sys.exc_info()

        if not status_data:
            print 'empty dict for status returned'
        return status_data

    def get_picture_attachment_json(self, attachment):
        api_request_path = "{0}/".format(attachment.facebook_object_id)
        args_for_request = {
            'version': FACEBOOK_API_VERSION,
            'fields': "id, images, height, source"
        }
        try_number = 1
        while try_number <= NUMBER_OF_TRIES_FOR_REQUEST:
            try:
                photo_object = self.graph.request(path=api_request_path,
                                                  args=args_for_request)
                return photo_object
            except:
                warning_msg = "Failed first attempt for attachment #({0}) from FB API.".format(
                    attachment.id)
                logger = logging.getLogger('django')
                logger.warning(warning_msg)
                try_number += 1
        error_msg = "Failed three attempts for feed #({0}) from FB API.".format(
            attachment.id)
        logger = logging.getLogger('django.request')
        logger.warning(error_msg)
        return {}

    @staticmethod
    def insert_status_attachment(status, status_object_defaultdict):
        # print 'insert attachment'
        attachment_defaultdict = defaultdict(str, status_object_defaultdict)
        attachment = Facebook_Status_Attachment(
            status=status,
            name=attachment_defaultdict['name'],
            caption=attachment_defaultdict['caption'],
            description=attachment_defaultdict['description'],
            link=attachment_defaultdict['link'],
            facebook_object_id=attachment_defaultdict['object_id'],
            type=attachment_defaultdict['type'],
            picture=attachment_defaultdict['picture'])
        attachment.save()
        # add all media files related to attachment

    def update_status_attachment(self, attachment, status_object_defaultdict):
        # print 'update attachment'
        attachment_defaultdict = defaultdict(str, status_object_defaultdict)
        if attachment_defaultdict['link']:
            # Update relevant attachment fields
            attachment.name = attachment_defaultdict['name']
            attachment.caption = attachment_defaultdict['caption']
            attachment.description = attachment_defaultdict['description']
            attachment.link = attachment_defaultdict['link']
            attachment.facebook_object_id = attachment_defaultdict['object_id']
            attachment.type = attachment_defaultdict['type']
            attachment.picture = attachment_defaultdict['picture']
            # get source for picture attachments
            if attachment.type == 'photo':
                print '\tgetting picture source'
                photo_object = self.get_picture_attachment_json(attachment)
                selected_attachment_object = sorted(photo_object['images'],
                                                    key=lambda x: x['height'],
                                                    reverse=True)[0]
                attachment.source = selected_attachment_object['source']
                attachment.source_width = selected_attachment_object['width']
                attachment.source_height = selected_attachment_object['height']
            elif attachment.type == 'video':
                print '\tsetting video source'
                attachment.source = attachment_defaultdict['source']
            attachment.save()
        else:
            # if has no link field - then there's no attachment, and it must be deleted
            # print 'deleting attachment'
            attachment.delete()

    def create_or_update_attachment(self, status_object,
                                    status_object_defaultdict):
        """
        If attachment exists, create or update all relevant fields.
        """
        # print 'create_or_update attachment'
        if status_object_defaultdict['link']:
            attachment, created = Facebook_Status_Attachment.objects.get_or_create(
                status=status_object)
            # print 'I have an attachment. Created now: %s; Length of data in field link: %d; \
            #     field picture: %d;  id: %s' % (created, len(status_object_defaultdict['link']),
            #                                    len(str(status_object_defaultdict['picture'])), status.status_id)
            # self.update_status_attachment(attachment, status_object_defaultdict)
            self.update_status_attachment(attachment,
                                          status_object_defaultdict)
        else:
            pass
            # print 'i don''t have an attachment; Link field: %s; Picture field: %s; id: %s' % (
            #     str(status_object_defaultdict['link']), str(status_object_defaultdict['picture']), status.status_id)

    def update_status_object_in_db(self, options, status_object,
                                   retrieved_status_data):
        """
        Receives a single status_object object as retrieved from facebook-sdk, and inserts the status_object
        to the db.
        """
        # Create a datetime object from int received in status_object
        current_time_of_update = datetime.datetime.strptime(
            retrieved_status_data['updated_time'],
            '%Y-%m-%dT%H:%M:%S+0000').replace(tzinfo=timezone.utc)

        status_object_defaultdict = defaultdict(lambda: None,
                                                retrieved_status_data)
        if status_object_defaultdict['message']:
            message = status_object_defaultdict['message']
        else:
            message = ''
        if status_object_defaultdict['likes']:
            like_count = status_object_defaultdict['likes']['summary'][
                'total_count']
        else:
            like_count = 0
        if status_object_defaultdict['comments']:
            comment_count = status_object_defaultdict['comments']['summary'][
                'total_count']
        else:
            comment_count = 0
        if status_object_defaultdict['shares']:
            share_count = status_object_defaultdict['shares']['count']
        else:
            share_count = 0
        if status_object_defaultdict['status_type']:
            type_of_status = status_object_defaultdict['status_type']
        else:
            type_of_status = None
        if status_object_defaultdict['story']:
            story = status_object_defaultdict['story']
        else:
            story = None
        if status_object_defaultdict['story_tags']:
            story_tags = status_object_defaultdict['story_tags']
        else:
            story_tags = None

        published = datetime.datetime.strptime(
            status_object_defaultdict['created_time'],
            '%Y-%m-%dT%H:%M:%S+0000').replace(tzinfo=timezone.utc)

        try:

            if ((status_object.updated <= current_time_of_update)
                    or options['force-update'] or
                (options['update-deleted'] and status_object.is_deleted)):
                # If post_id exists but of earlier update time, fields are updated.
                print 'update status_object'
                status_object.content = message
                status_object.like_count = like_count
                status_object.comment_count = comment_count
                status_object.share_count = share_count
                status_object.status_type = type_of_status  # note that fb has type AND status_type fields, here is status_type
                status_object.updated = current_time_of_update
                status_object.story = story
                status_object.story_tags = story_tags
                status_object.is_comment = status_object.set_is_comment
                if status_object.is_deleted and options['update-deleted']:
                    status_object.is_deleted = False
                    self.stdout.write('Status no longer marked deleted')

                # update attachment data
                self.create_or_update_attachment(status_object,
                                                 status_object_defaultdict)
            elif options['force-attachment-update']:
                # force update of attachment only, regardless of time
                print 'Forcing update attachment'
                status_object.save()
                self.create_or_update_attachment(status_object,
                                                 status_object_defaultdict)
                # If post_id exists but of equal or later time (unlikely, but may happen), disregard
                # Should be an else here for this case but as it is, just disregard
        except AttributeError:
            # If status_id is NoneType, and does not exist at all, create it from data.
            print 'create status_object'
            status_object = Facebook_Status(
                feed_id=retrieved_status_data['from']['id'],
                status_id=retrieved_status_data['id'],
                content=message,
                like_count=like_count,
                comment_count=comment_count,
                share_count=share_count,
                published=published,
                updated=current_time_of_update,
                status_type=type_of_status,
                story=story,
                story_tags=story_tags)

            status_object.is_comment = status_object.set_is_comment

            if status_object_defaultdict['link']:
                # There's an attachment
                status_object.save()
                self.insert_status_attachment(status_object,
                                              status_object_defaultdict)
        finally:
            # save status_object object.
            status_object.save()

    def set_deleted_status_in_db(self, status):
        """Set is_deleted flag to True and save status"""
        status.is_deleted = True
        status.save()

    def fetch_status_data(self, status):
        """
        Returns a Dict object with Status data, by Status ID, empty Dict if not working,
        None if status deleted.
        """

        status_dict = dict()
        is_skip = False
        if status.feed.feed_type == 'PP':
            try:
                # Set facebook graph access token to most up-to-date user token in db
                token = User_Token.objects.first()
                self.graph.access_token = token.token

            except AttributeError:
                # exception - trying to set an empty token (NoneType) as graph.access_token
                # Fallback: Set facebook graph access token to app access token
                self.graph.access_token = facebook.get_app_access_token(
                    settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY)
                if status.feed.requires_user_token:
                    # If the Status's Feed is set to require a user-token, and none exist in our db, the feed is skipped.
                    print 'feed %d requires user token, skipping.' % status.id
                    is_skip = True

                    # Get the data using the pre-set token

        elif status.feed.feed_type == 'UP':  # feed_type == 'UP' - User Profile
            # Set facebook graph access token to user access token
            token = User_Token.objects.filter(
                feeds__id=status.id).order_by('-date_of_creation').first()
            if not token:
                print 'No Token found for User Profile %s' % status
                is_skip = True
            else:
                print 'using token by user_id: %s' % token.user_id
                self.graph.access_token = token.token

        else:  # Deprecated or malfunctioning profile ('NA', 'DP')
            print 'Profile %s is of type %s, skipping.' % (status.id,
                                                           status.feed_type)
            is_skip = True

        if not is_skip:
            status_dict = self.fetch_status_object_data(status.status_id)
        return status_dict

    def handle(self, *args, **options):
        """
        Executes updatestatus manage.py command.
        Receives either one status ID and updates the data for that status,
        or no status ID and therefore retrieves all Statuses and updates their data one by one.

        Options exist for running within a given date range.
        """

        list_of_statuses = list()
        # Case no args - fetch all feeds
        if len(args) == 0:
            criteria = {}
            if options['from-date'] is not None:
                criteria['published__gte'] = dateutil.parser.parse(
                    options['from-date'])
            if options['to-date'] is not None:
                criteria['published__lt'] = dateutil.parser.parse(
                    options['to-date'])
            db_statuses = Facebook_Status.objects_no_filters.filter(
                **criteria).order_by('-published')
            list_of_statuses = list(db_statuses)

        # Case arg exists - fetch status by id supplied
        elif len(args) == 1:
            status_id = args[0]
            try:
                status = Facebook_Status.objects_no_filters.get(
                    status_id=status_id)
                list_of_statuses.append(status)

            except Facebook_Status.DoesNotExist:
                warning_msg = "Status #({0}) does not exist.".format(status_id)
                logger = logging.getLogger('django')
                logger.warning(warning_msg)
                raise CommandError('Status "%s" does not exist' % status_id)

        # Case invalid args
        else:
            raise CommandError('Please enter a valid status id')

        self.stdout.write('Starting to update {0} statuses'.format(
            len(list_of_statuses)))

        # Iterate over list_of_statuses
        for i, status in enumerate(list_of_statuses):
            self.stdout.write('Working on status {0} of {1}: {2}.'.format(
                i + 1, len(list_of_statuses), status.status_id))
            status_data = self.fetch_status_data(status)
            self.stdout.write('Successfully fetched status: {0}.'.format(
                status.pk))

            if status_data:
                self.update_status_object_in_db(
                    options,
                    status_object=status,
                    retrieved_status_data=status_data)
                self.stdout.write('Successfully written status: {0}.'.format(
                    status.pk))
                info_msg = "Successfully updated status: {0}.".format(
                    status.pk)

            elif status_data is None:  # Status deleted
                if options['update-deleted']:
                    self.set_deleted_status_in_db(status)
                    info_msg = 'Successfully marked status deleted: {0}.'.format(
                        status.pk)
                    self.stdout.write(info_msg)
                else:
                    self.stdout.write(
                        'Ignoring deleted status: {0} (use --update-deleted to update DB).'
                        .format(status.pk))
                    info_msg = 'Ignoring deleted status: {0}.'.format(
                        status.pk)

            else:
                self.stdout.write(
                    'No data was retrieved for status: {0}.'.format(status.id))
                info_msg = "Did not successfully update status: {0}.".format(
                    status.pk)

            logger = logging.getLogger('django')
            logger.info(info_msg)

        info_msg = "Successfully saved all statuses to db"
        logger = logging.getLogger('django')
        logger.info(info_msg)
        self.stdout.write('Successfully saved all statuses to db.')
Exemple #26
0
import facebook
""">pip install facebook-sdk"""

graph = facebook.GraphAPI(access_token="", version="2.12")


def procurarLugares(local):
    # Procura por lugares na região da avenida paulista, colocamos a longitude e latitude.
    print(local)
    places = graph.search(type='place', center=local, fields='name,location')

    # para cada local ele retorna um objeto, na qual podemos exebir na tela suas informações
    for place in places['data']:
        print('%s %s' % (place['name'].encode(), place['location'].get('zip')))


"""
Av Paulista= -23.5629, -46.6544

Faculdade = -23.525765, -46.649121

"""


def putRegiao():
    latitude = input("Digite a latitude desejada: ")
    longitude = input("Digite a longitude Desejada :")
    local = latitude + "," + longitude
    procurarLugares(local)

'''maxy will be helping us in commenting on the posts
code: Yogitha Polavarapu'''
#import random
import facebook
#token generated from facebook you can get this from https://developers.facebook.com/tools/explorer/145634995501895/
token = '<insert token here>'
graph = facebook.GraphAPI(token)

#feed = graph.get_connections("me", "home")
# first parameter is the id of the user, you can execute the second one in graph API
feed = graph.get_connections("649761338441252",
                             "feed?{story,message,from,name}&limit=10")
#replies=["ThankYou","Thanks","Thanks a lot","Thanks a bunch","Gracias"]

for var in range(0, 10):
    retrieve = feed["data"][var]
    Details = retrieve["from"]
    Name = Details["name"]
    graph.put_like(post["id"])
    #lets you know the name of the person in the console
    print "->from " + Name
    #and the message he poseted
    print "->->" + post["message"]
    #	message= [random.randint(0, len(replies))]
    #posts as a comment
    graph.put_object(post["id"],
                     "comments",
                     message="<insert your message> " + fromName)
    print message
Exemple #28
0
                 msg=access_token.encode('utf-8'),
                 digestmod=hashlib.sha256)
    return h.hexdigest()


# load the credentials
home = str(Path.home()
           )  #gets path to home directory; supposed to work for Win and Mac
keyFilename = 'facebook_api_keys.txt'
apiKeyPath = home + '/' + keyFilename

try:
    with open(apiKeyPath, 'rt', encoding='utf-8') as fileObject:
        fileStringList = fileObject.read().split('\n')
        app_id = fileStringList[0]
        app_secret = fileStringList[1]
        access_token = fileStringList[2]
        print(
            'id: ', app_id
        )  # delete this line once the script is working; don't want printout as part of the notebook
        print(
            'secret: ', app_secret
        )  # delete this line once the script is working; don't want printout as part of the notebook
        print('access token: ', access_token)
except:
    print(keyFilename + ' file not found - is it in your home directory?')

# see https://facebook-sdk.readthedocs.io/en/latest/api.html
api = facebook.GraphAPI(access_token=access_token)
postargs = {"appsecret_proof": genAppSecretProof(app_secret, access_token)}
Exemple #29
0
 def test_get_app_access_token(self):
     token = facebook.GraphAPI().get_app_access_token(
         self.app_id, self.secret)
     # Since "unicode" does not exist in Python 3, we cannot check
     # the following line with flake8 (hence the noqa comment).
     assert (isinstance(token, str) or isinstance(token, unicode))  # noqa
 def __init__(self, user):
     self.user = user
     self.uid = user['uid']
     self.graph = facebook.GraphAPI(user['access_token'])