class Facebook(object): ''' classdocs ''' def __init__(self,config): self.facebook = GraphAPI(config["token"]) try: #token=facepy.utils.get_extended_access_token(config["token"],config['app_id'],config['app_secret']) #self.facebook = GraphAPI(token[0]) me=self.facebook.get('me') print(json.dumps(me, indent=4)) #print ("token:"+str(token[0])) except: pass#self.facebook=None def uploadImage(self,messageStr,imagePath): print("uploading to facebook") tries=0 while(tries<5): try: print self.facebook.post( path = 'me/photos', source = open(imagePath), message=messageStr ) break except: print("facebook error, try #"+str(tries)) time.sleep(0.1) tries=tries+1 print("finnished uploading to facebook\n")
def queue(sender, instance, created, **kwargs): name = instance.name graph = GraphAPI(USER_TOKEN) message = """ Dia %(date)s às %(hour)s o Evento %(name)s %(short)s %(long)s %(link)s """ % {'name': instance.name, 'link': instance.link, 'date': instance.date.strftime('%d/%m/%Y'), 'hour': instance.date.strftime('%H:%M'), 'short': instance.short_description, 'long': instance.full_description, } if instance.link: graph.post( path = PAGE_ID + '/feed', link = instance.link, message = message) else: graph.post( path = PAGE_ID + '/photos', source = open( MEDIA_ROOT + "/" + str(instance.image)), message = message)
class FacebookBackend(ShareBackend): """Implements Facebook backend""" def __init__(self, *args, **kwargs): super(FacebookBackend, self).__init__(*args, **kwargs) # Create a Facebook social graph API using facepy. from facepy import GraphAPI self.api = GraphAPI() self.api.oauth_token = self.consumer_token def _share(self): """Implements sharing on Facebook by making wall posts.""" # send the message # TODO add support for icons to posts and messages response = self.api.post(path='me/feed', message=self.excerpt, picture=self.image_url or None, caption = self.image_url_title, link = self.url or None, name=self.url_title, description=self.url_description) if response is None: raise ShareError, "Facebook post to feed failed." def _send_message(self): """Implements send a message to a facebook user""" # Facebook accepts an array of name/id objects. response = self.api.post(path='/me/outbox', message = self.message, picture=self.image_url or None, link = self.url or None, to=self.to) if response is None: raise ShareError, "Facebook outbox Failure"
def test_post_with_files(): graph = GraphAPI("<access token>") mock_request.return_value.content = "true" mock_request.return_value.status_code = 200 graph.post(path="me/photos", source=open("tests/fixtures/parrot.jpg"))
def check_answer(request): given_answer = request.POST['answer'] user_level = request.POST['level'] curr_level = level.objects.get(number=user_level) if curr_level.answer == given_answer: token = request.facebook.user.oauth_token.token graph = GraphAPI(token) profile_id = request.facebook.user.facebook_id try: graph.post(path=str(profile_id) + '/feed', message='I just crossed level ' + str(user_level) + ' in Recstacy\'s Caught In The Chronicle.', caption='Caught In The Chronicle', link='chronicle.recstacy.in') except: pass ui = userInfo.objects.get(user=request.facebook.user) ui.max_level = curr_level.number + 1 ui.save() try: next_level = level.objects.get(number=curr_level.number + 1) except: return HttpResponse('Adding More Levels. Stay Tuned') return HttpResponseRedirect('/level/' + next_level.slug + '/') else: return HttpResponseRedirect(request.META['HTTP_REFERER'])
def get_facebook_info(): user_data = web.input(code=None) if not user_data.code: dialog_url = ( "http://www.facebook.com/dialog/oauth?" + "client_id=" + app_id + "&redirect_uri=" + post_login_url + "&scope=email, read_stream" ) return "<script>top.location.href='" + dialog_url + "'</script>" else: graph = GraphAPI() response = graph.get( path="oauth/access_token", client_id=app_id, client_secret=app_secret, redirect_uri=post_login_url, code=code, ) data = parse_qs(response) graph = GraphAPI(data["access_token"][0]) graph.post(path="me/feed", message="Your message here")
class FbConnector(): def __init__(self): self.token = fbauth.getAccessToken() self.graph = GraphAPI(self.token) def postImage(self, caption, filename): """Posts an image file into FB :param str caption: a valid string :param str filename: a valid path to an image file """ try: fimage = open(filename, 'rb') self.graph.post(path="me/photos", caption=caption, source=fimage) except: print 'Error submitting image' def postMessage(self, text): """Posts a message into FB :param str text: a valid string """ try: self.graph.post(path='me/feed', message=text) except: print 'There was an error posting the message' def getUsername(self): """Gets the current logged in username :rtype: str """ try: r = self.graph.get('me?fields=name') return r['name'] except: print 'Error retrieving name'
def upload_photo(paras): oauth_access_token = paras['token'] id_album = fetch_album(paras['url_album']) src1 = paras['src1'].lstrip("/") src2 = paras['src2'].lstrip("/") compressPhoto(src1, src2) desc = paras['desc'] real_desc = "" items = re.findall(r'<span>(.*?)</span>', desc) for item in items: real_desc += item.replace("<br>", "\n") graph = GraphAPI(oauth_access_token) ret = graph.post( path = '%s/photos'%id_album, source = open(src1, 'rb'), message = real_desc ) ret = graph.post( path = '%s/photos'%id_album, source = open(src2, 'rb'), ) os.remove(src1) os.remove(src2) print json.dumps({'status' : 0, 'msg' : ret})
def Upload(): with open(r"C:\autismomeme\authcode.txt", "r") as myfile: authcode = myfile.read() graph = GraphAPI(authcode) graph.get("/autsimomeme/photos") graph.post(path="/autsimomeme/photos", message="", source=open(("temp.jpg"), "rb")) return
def writeComment(page_token_in, comment, dest_id, link_in = ""): pg = GraphAPI(page_token_in) pg.post( path = dest_id + '/comments', message = comment, link = link_in )
def facebook_post_video(sender, instance, created, **kwargs): '''Once video is created, if facebook connect and video public is set to True Video link would then be posted to Facebook page of user ''' video = instance user = instance.uploader if user and created: profile = UserProfile.objects.get(user=user) if profile.facebook_connect and video.is_public: user_social = UserSocialAuth.objects.get(user=user, provider='facebook') extra_data = eval(str(user_social.extra_data)) access_token = extra_data['access_token'] graph = GraphAPI(access_token) domain = Site.objects.get_current().domain url = 'http://%s/%s' % (domain, video.slug) img_url = 'http://%s/%s' % (domain, 'media/gfx/logo.png') graph.post( path='me/links', picture=img_url, message= "Hi Guys! Posted a new video, %s. Check it out on the AWESOME %s site!" % (video.title, Site.objects.get_current().name), link=url, )
def postMessage(token_in, text, link_in = ""): g = GraphAPI(token_in) g.post( path =group_id + '/feed', message = text, link = link_in )
class Facebook(object): ''' classdocs ''' def __init__(self, config): self.facebook = GraphAPI(config["token"]) try: #token=facepy.utils.get_extended_access_token(config["token"],config['app_id'],config['app_secret']) #self.facebook = GraphAPI(token[0]) me = self.facebook.get('me') print(json.dumps(me, indent=4)) #print ("token:"+str(token[0])) except: pass #self.facebook=None def uploadImage(self, messageStr, imagePath): print("uploading to facebook") tries = 0 while (tries < 5): try: print self.facebook.post(path='me/photos', source=open(imagePath), message=messageStr) break except: print("facebook error, try #" + str(tries)) time.sleep(0.1) tries = tries + 1 print("finnished uploading to facebook\n")
def uploadPicture(picturePath): token = settings.ACCESS_TOKEN try: graph = GraphAPI(token) # Get my latest posts #print graph.get('me/posts') # Post a photo graph.post( path='me/photos', #source = picturePath source=open(picturePath, 'rb') #source = open('hslls.bmp', 'rb') ) except: print("-------------------") print("") print("Change access token") print("") print("-------------------") #uploadPicture("")
def test_post_with_files(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'true' mock_request.return_value.status_code = 200 graph.post(path='me/photos', source=open('tests/fixtures/parrot.jpg'))
def f_post(picture): graph = GraphAPI("CAAXMV1IDjZBoBAC0Be3HMvZA0lPPub735gJiSpwSqGmLTZBrZAqTki8tfqKAUUkAeMoKsKTZBT7nxgIj98S2rXdJk0l9UDnRxCyVi9DvSE5lniRBoUrZC7dx5b1NE5gQO3w6VFB1wqwf9G5OGNS56wGyDWHwBAomLDdTJfIWYX6nk6IetNq73ZC9ps9JuCPoOHOAf8vqjR1eAZDZD") # print graph.get('me/posts') graph.post( path = 'me/photos', # source = open('test.jpg', 'rb') source = picture )
def facebook_post(file_name, opt): access_token = '' graph = GraphAPI(access_token) if opt == 1: msg = 'Watching ' + file_name + ' on VLC Media Player' else: msg = 'Listening to ' + file_name + ' on VLC Media Player' print msg graph.post('me/feed', message=msg)
def test_post_with_files(): graph = GraphAPI('<access token>') mock_request.return_value.content = 'true' graph.post( path = 'me/photos', source = open('tests/fixtures/parrot.jpg') )
def facebook_post(file_name,opt): access_token='' graph=GraphAPI(access_token) if opt==1: msg='Watching '+file_name+' on VLC Media Player' else: msg='Listening to '+file_name+' on VLC Media Player' print msg graph.post('me/feed',message=msg)
def postVideo_page(title, message, path, pageName): graph = GraphAPI(getPageToken(pageName)) try: graph.post(path="me/videos", source=open(path), title=title, description=message) except Exception as e: return dict(success=False, message=e) return dict(success=True, message='video posted correctly')
def post_to_facebook(sender, instance, *args, **kwargs): if not instance.post_on_facebook: return False try: access_token = settings.FACEBOOK_ACCESS_TOKEN except AttributeError: raise ImproperlyConfigured('FACEBOOK_ACCESS_TOKEN does not exist.') graph = GraphAPI(access_token) graph.post(**instance.facebook_message) instance.disable_post_on_facebook()
def check_lotteries(): lotteries = Lottery() for lottery in lotteries.get_incompleted(): graph = GraphAPI(lottery['page_token']) page = graph.get(lottery['post_id']) if page.get('likes', 0) >=lottery['likes_to_finish']: fb_page = GraphAPI(lottery['page_token']) post = graph.post(path='%s/feed' % lottery['page_id'], message='success') post = graph.post(path='%s/feed' % lottery['page_id'], message='test cel')
def publish_birthday_post(): template = request.args.get('template', "Happy Birthday!") token = 'CAACEdEose0cBADN2nkNzrau9tJpHElFZCzZBWTQHBrVSAdn5jRxafsWYuZCxiubNcMZC7yGwPx4yIR9HFH1GueFlfamAd5bZAiLqZChCEPQpkZAzqMHkrJhqudzVo7PqZCpGnvM7z3mPZAbr9TbYEZBxWJBVJzeW9lhPmKJVAhzWso8PlzozJo9JGiZBoR9agQxZB2bfa8uSvBZA7N7zR9CfJhlR1' graph = GraphAPI( token, version='2.5', timeout=30 ) path = "/me/feed?message=%s" % template graph.post(path) return render_template('submit.html', message=template)
def handle(self, *args, **options): potential_posts = SocialPost.objects.filter( is_posted=False, time_to_post__lte=timezone.now(), ) twitter_app_creds = SocialApp.objects.filter(provider='twitter')[0] twitter_key = twitter_app_creds.client_id twitter_secret = twitter_app_creds.secret for post in potential_posts: user = post.user if post.social_network == 'facebook': token = None try: token = SocialToken.objects.get( account__user=user, app__provider='facebook' ).token except: logger.exception('[%s] Error getting social token for %s!' % (site_settings.site_url(), post.social_network,)) if token: try: graph = GraphAPI(token) graph.post( path='%s/links' % (site_settings.facebook_page_id()), link=post.url, message='%s %s' % (post.message, post.url), ) post.is_posted = True post.posted_on = timezone.now() post.save() logger.info('[%s] Post to %s successful' % (site_settings.site_url(), post.social_network,)) except: logger.exception('[%s] Post to %s failed' % (site_settings.site_url(), post.social_network,)) if post.social_network == 'twitter': token = None try: token = SocialToken.objects.get( account__user=user, app__provider='twitter' ) except: logger.exception('[%s] Error getting social token for %s!' % (site_settings.site_url(), post.social_network,)) if token: try: auth = tweepy.OAuthHandler(twitter_key, twitter_secret) auth.set_access_token(token.token, token.token_secret) api = tweepy.API(auth) api.update_status('%s %s' % (post.message, post.url)) post.is_posted = True post.posted_on = timezone.now() post.save() logger.info('[%s] Post to %s successful' % (site_settings.site_url(), post.social_network,)) except: logger.exception('[%s] Post to %s failed' % (site_settings.site_url(), post.social_network,))
def post_worker(): while True: # this will block the thread indefinetly until an item is popped post_params = post_queue.get() # get the poster's data from our db poster_data = db.posters.find_one({'id': post_params['poster_id']}) if poster_data is None: log.exception('poster_id not valid') else: # get post details url = (post_params['url'] if 'url' in post_params.keys() else '') title = (post_params['title'] if 'title' in post_params.keys() else '') content = (post_params['content'] if 'content' in post_params.keys() else '') # if bitly access token is defined shorten the link if len(url) > 0 and 'BITLY_TOKEN' in os.environ.keys(): try: b = bitly_api.Connection(access_token=os.environ['BITLY_TOKEN']) shortie = b.shorten(url) url = shortie['url'] except Exception, e: log.exception('Could not shorten the link using bit.ly - %s', e) # facebook-needed params if all(param in poster_data.keys() for param in ['fb_tok', 'fb_page']): try: graph = GraphAPI(poster_data['fb_tok']) graph.post( path = 'v2.2/%s/feed' % poster_data['fb_page'], message = '%s: %s %s' % (title, content, url), retry = 10 ) except Exception, e: log.exception('Could not post new plan to facebook page - %s', e) # twitter-needed params if all(param in poster_data.keys() for param in ['tw_tok', 'tw_tsec', 'tw_con', 'tw_csec']): try: tweet_content = '%s: %s' % (title, content) # shorten our content - max size should be 118, not including the link which will be # shortened by twitter if bit.ly is not enabled if len(tweet_content) > 118: tweet = '%s... %s' % (tweet_content[0:114], url) else: tweet = '%s %s' % (tweet_content, url) t = Twitter(auth=OAuth(consumer_key=poster_data['tw_con'], consumer_secret=poster_data['tw_csec'], token=poster_data['tw_tok'], token_secret=poster_data['tw_tsec'])) t.statuses.update(status=tweet) except Exception, e: log.exception('Could not post new plan to twitter feed - %s', e)
def create_album(paras): oauth_access_token = paras['token'] id_group = fetch_group(paras['id_group']) name = paras['name_album'] message = paras['msg_album'] graph = GraphAPI(oauth_access_token) graph.post( path = '/%s/albums'%id_group, name = name , message = message, #privacy = {} ) print json.dumps({'status' : 0})
def upload_photo(paras): oauth_access_token = paras['token'] id_album = fetch_album(paras['url_album']) src1 = paras['src1'].lstrip("/") src2 = paras['src2'] desc = paras['desc'] graph = GraphAPI(oauth_access_token) graph.post( path = '%s/photos'%id_album, source = open(src1, 'rb'), message = desc ) print {'status' : 0}
def facebook_graph_add_reading(user, reading): if not settings.DEV: try: oauth = user.oauth_set.get(provider='facebook') graph_data = ( 'http://skimreads.com/readings/%s/permalink/' % reading.slug) graph = GraphAPI(oauth.access_token) graph.post( path = 'me/skimreads:add', reading = graph_data ) except ObjectDoesNotExist: pass
class FacebookService: def __init__(self): app_id = config.app_id_facebook app_secret = config.app_secret_facebook access_token = utils.get_application_access_token(app_id, app_secret) self.graphAPI = GraphAPI(access_token) def postToWall(self, message): self.graphAPI.post('rasberrycoffee/feed', message=message + ' ' + self.__getStamp()) def __getStamp(self): return datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")
def from_album_invite(request, album_id=None): if request.method == 'POST': from facepy import GraphAPI from urllib2 import urlopen # Check if publish_stream permissions are set social_user = request.user.social_auth.all().get(user=request.user, provider = 'facebook') access_token = social_user.extra_data['access_token'] graph_permissions = 'https://graph.facebook.com/me/permissions?access_token='+access_token permission_content = urlopen(graph_permissions).read() json_content = json.loads(permission_content) data = json_content['data'] # 0 if no permission, 1 if yes publish_stream = data[0]['publish_stream'] # If so, invite friend if publish_stream: friend_name = strip_tags(request.POST['friend_name']) friend_id = strip_tags(request.POST['hash']) album = Experiences.objects.get(pk=album_id) graph = GraphAPI(access_token) message = 'Hey '+friend_name+'. I invited you to our private album: '+\ album.title+' on Memeja. -'+request.user.username picture = 'http://www.memeja.com/static/images/intro_logo.gif' link = 'http://memeja.com/login/facebook' name = 'See it here' graph.post(path=friend_id+"/feed", retry=1, message=message, picture=picture, link=link, name=name) with open(os.path.join(settings.STATIC_ROOT, 'registration_track.txt'), "a") as text_file: text_file.write(' **'+request.user.username+' invited '+friend_name+'\n') # Invitation invite = InvitationKey.objects.create_invitation(request.user, album) invite.key = friend_id # replace key with uid of INVITED user invite.save() messages.add_message(request, messages.SUCCESS, 'You successfully invited '+friend_name, extra_tags="text-success") return HttpResponseRedirect('/%s/' % album_id) else: # If not, send them to auth dialog ##### AUTH DIALOG ##### messages.error(request, 'Please first <a href="/login/facebook2">click to enable permissions</a>, then invite again', extra_tags='safe') return HttpResponseRedirect('/%s/' % album_id)
class Facebook: graph = "" api_token_list = ["EAAEGVfJehVABADQboSAmxsCBb64Drfs6JQ8NaOJ8ogD68bIZBTPapSZAqZApZBSSvkhbcddhF7srS5Hh1aAuddKlQRZB2UyqHs3ZCs6lYjK4ySlJb2DguxnsvczIaMh7ZC0ZBvN1I4mHoFGEwzNpkpegda9slYK1vFZAjKOGDJeio93033c2WTLZAt", "EAAEGVfJehVABAHny3mZBn8JV5NjfG1nHnKCgxBaZBsmZBpsC5WF1tKl6uFZC5O4ZCJkWdpgZAsJqb1k8WdpX6k9QlBMWZCKtKQf9eIjL7tVZASRy2LUT5cmYNEKoVr7zwPn6IYhyWZCZBP0lf9ZCkZB3scZCNOwX8AXamPZAgrw9ZC8k1zT0B4jltZAP1YQx", "EAAEGVfJehVABAEQ2qAXrAJgRQ5ZAkwudQC3KZBw96UzbS4cksaoXOB9EVGbljQ92WIet5Is0CUTQDKqDPsI4AnZAgyI3DuUWuL6UQinUue84dYQo5MhJsdiZC7Us4n026Y6kjvMhAZB8F8WsxSwh3T3xwBQ6EqnD1CW5Sm2sYXG96jAyVIYKt", "EAAEGVfJehVABAKZA5HHZBX3v1o8qEwqSINygSwgWrD7lQMrA3yCWKE6FlpWzLIkn5ZCAOplFRlWZCQhhIb6cIZCXun77IrUwJA8gzCY9eZC7PLZB7BQXkYg4P0NZClMWlJxFnFLHlHzZC5vKywoEspZCFOBwmDAq835gQBtpK9onTXIPHTfrAZCxH26", "EAAEGVfJehVABAKZB8yogkB7vwzMdcuYRHEjDQu5EwoNgXOjOey5LaPBDYhFnzZCoiyZCDeWekn5fS1rHHvAZAXBAfkRk6RgKfkfNRULLsamtc2aP5QwsUTtUdeMjZC2ZB4LVRA3HS1984zSNZCIjBAfMQlHM93TNnjJS8zZABPgTJo19OGz81aAJ"] api_token = api_token_list[randint(0, 4)] def __init__(self): self.graph = GraphAPI(self.api_token) def get_user_id_form_message(self, json): return json['messaging'][0]['sender']['id'] def get_message_text(self, json): return json['messaging'][0]['message']['text'] def get_user_data(self, facebook_id): return {'profile_pic': 'https://scontent.xx.fbcdn.net/v/t1.0-1/23031354_103638190408641_2437891292324580905_n.jpg?oh=63b362fc756b2e733336e95f0a4625dc&oe=5A7175B9', 'locale': 'nl_NL', 'gender': 'male', 'id': '103636133742180', 'headers': {'Cache-Control': 'private, no-cache, no-store, must-revalidate', 'Connection': 'keep-alive', 'Content-Type': 'application/json; charset=UTF-8', 'x-fb-rev': '3422078', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Pragma': 'no-cache', 'Date': 'Thu, 02 Nov 2017 11:04:19 GMT', 'x-fb-trace-id': 'A7RTUulgFML', 'ETag': '"a76ec7f2451f48af7bb25030d25ee3b976d9e172"', 'Access-Control-Allow-Origin': '*', 'facebook-api-version': 'v2.10', 'X-FB-Debug': 'mgeNOpGAu/DOQZ+Pm/sFEXbvhoIEjm0RTGN6xVMRjWxZa+9q+DxOGgq2zja5bBASsNF7Df5rfYb9qLr7PC6dwQ==', 'Content-Length': '234', 'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'}, 'last_name': 'Wouters', 'first_name': 'Ton', 'timezone': 1} def send_message(self, facebook_id, message): self.graph.post(path='me/messages', recipient={"id": facebook_id}, message={"text": message}) def send_sender_action(self, facebook_id, action): self.graph.post(path='me/messages', recipient={"id": facebook_id}, sender_action=action) def send_mark_as_read(self, facebook_id): self.send_sender_action(facebook_id, "mark_seen") def turn_typing_on(self, facebook_id): self.send_sender_action(facebook_id, "typing_on") def get_user_token_from_optin_request(self, json): return json['messaging'][0]['optin']['ref'] def turn_typing_off(self, facebook_id): self.send_sender_action(facebook_id, "typing_off") def get_application_user_by_facebook_id(self, facebook_id): user = IntentParser.get_conversation_by_token(facebook_id, True) # if not user.name: # user.name = self.get_user_first(facebook_id) # user.surname = self.get_user_last(facebook_id) # return user
def save(self): """ Posts the content into a Facebook album. """ _uuid = uuid.uuid4() provider = self.user.social_auth.get(provider='facebook') graph = GraphAPI(provider.extra_data['access_token']) logger.debug('[%s] Posting %d photos into album %s' % ( _uuid, self.book.bookimage_set.all().count(), self.cleaned_data['album'] )) page_auth = graph.get( "%s?fields=access_token" % settings.FACEBOOK_FAN_APP_ID ) page_graph = GraphAPI(page_auth['access_token']) responses = [] for image in self.book.bookimage_set.all(): response_image = page_graph.post( path="%s/photos" % self.cleaned_data['album'], source=open(image.image.path), message=self.cleaned_data['description'], ) logger.debug("[%s] Posting image %r to album result: %r" % ( _uuid, image, response_image )) response_feed = page_graph.post( path="%s/feed" % settings.FACEBOOK_FAN_APP_ID, link="%s%s" % ( settings.FACEBOOK_IMAGE_POST_URL, response_image['id'] )) logger.debug("[%s] Posting image %r to feed result: %r" % ( _uuid, image, response_feed )) responses.append({ 'image_post': response_image, 'feed_post': response_feed, }) return responses
class Facebook(BasicApi): def setup(self, **kwargs): self.load(kwargs) def load(self, data): self.token = data.get('token') self.api = GraphAPI(self.token) def save(self): return {'token': self.token} def post(self, **kwargs): if 'text' in kwargs: self.api.post('me/feed', message=kwargs['text'])
def graph_user(self): graph = GraphAPI('%s|%s' % (settings.SOCIAL_AUTH_FACEBOOK_KEY, settings.SOCIAL_AUTH_FACEBOOK_SECRET)) return graph.post('%s/accounts/test-users' % settings.SOCIAL_AUTH_FACEBOOK_KEY, installed='true', permissions=','.join(settings.SOCIAL_AUTH_FACEBOOK_SCOPE))
def setup_module(module): """ Create a Facebook test user. """ global TEST_SIGNED_REQUEST graph = GraphAPI('%s|%s' % (TEST_APPLICATION_ID, TEST_APPLICATION_SECRET)) user = graph.post('%s/accounts/test-users' % TEST_APPLICATION_ID, installed = True, permissions = ['publish_stream, read_stream'] ) TEST_SIGNED_REQUEST = SignedRequest( user = SignedRequest.User( id = user['id'], age = range(0, 100), locale = 'en_US', country = 'Norway' ), oauth_token = SignedRequest.OAuthToken( token = user['access_token'], issued_at = datetime.now(), expires_at = None ) ).generate(TEST_APPLICATION_SECRET)
def test_error_message_on_500_response(): graph = GraphAPI("<access token>") message = "Ad Sets may not be added to deleted Campaigns." mock_request.return_value.status_code = 500 mock_request.return_value.content = json.dumps( {"error": {"code": 1487634, "type": "Exception", "is_transient": False, "message": message}} ) try: graph.get("act_xxxx/adcampaigns") except GraphAPI.FacebookError as exc: eq_(exc.message, message) try: graph.post("act_xxxx/adcampaigns") except GraphAPI.FacebookError as exc: eq_(exc.message, message)
def handler(event, context): tmp_filename = event.get('tmp_filename', '') s3_bucket_name = event['s3_bucket_name'] access_token_key = event['access_token_key'] message = event['message'] username = event['username'] category = event['category'] is_image = event.get('is_image', False) multimedia = event.get('multimedia', '') api = GraphAPI(access_token_key) data = {'message': message} if multimedia: if is_image: data['path'] = 'me/photos' elif not is_image and multimedia: api.url = 'https://graph-video.facebook.com' data['path'] = 'me/videos' source = get_s3_multimedia_content(multimedia, s3_bucket_name, tmp_filename) data['source'] = source else: data['path'] = 'me/feed' if category == 'profile' else f'{username}/feed' response = api.post(**data) return response
def handle(text, mic, profile): print "I'm Busy.py" token = "CAACEdEose0cBAOs8kQn5iLHkd3ZCObZCEZC7IAfXZBt8ZCFyx9ESVP6N3JNDki9cQZApw2GLg6m2vNjhIiK9hjwtt88bs5O58D1cZBPTo5RnFafSOvOODQsLhnXN8jjezYTfZA1b2qARsH9AR9zmuEaTRaauktr1Tj4rhDZARMPI1ViAh3GK6iWcbwhWCZCuFRkI7v7TR5TiSEgPmCKbnUKXXe" graph = GraphAPI(token) postid = graph.post(path = 'me/feed',message = "I'm busy") print postid mic.say("Busy mode on")
def publish_to_fb_wall(image_path): token = '%s|%s' % (settings.FB_APP_KEY, settings.FB_APP_SECRET) graph = GraphAPI(token) result = graph.post( path='me/photos', source=open(image_path, 'rb') )
def post_on_wall(user_id,message,access_token): #rows=db(db.Users.user_id==user_id).select(db.Users.ALL) #row=rows[0] #access_token=row.access_token graph=GraphAPI(access_token) message=message.split("-") message='/'.join(message) #print graph.post(path=user_id+'/feed',message=message,access_token=access_token) '''try: print graph.post(path='me/feed',message=message,access_token=access_token) print "SENT MESSAGE "+message except: print "Could not send message "+message print "ERROR",sys.exec_info()[0] pass''' print graph.post(path='me/feed',message=(user_id+" From Purposeful Facebook Networks :D "+message),access_token=access_token) print "psoted "+message +" on "+user_id
def post_in_page(page_access_token, page_id, image_file=None, message=None): page_graph = GraphAPI(page_access_token) print('Posting .....') if not message: message = '.' if image_file: image_file = open(image_file, 'rb') page_graph.post(path=page_id + '/photos', source=image_file, message=message) else: page_graph.post(path=page_id + '/feed', message=message)
def create(cls): application_graph = GraphAPI('%s|%s' % (TEST_APP_ID, TEST_APP_SECRET)) user = application_graph.post("%s/accounts/test-users" % TEST_APP_ID, installed='true', permissions='publish_stream,read_stream', ) return cls(user['id'], user['access_token'])
def main(): if "code" not in request.values.keys(): dialog_url=("http://www.facebook.com/dialog/oauth?"+"client_id="+fb_app_id+"&redirect_uri="+post_login_url+"&scope=publish_actions") return redirect(dialog_url) else: code=request.values.get("code") graph=GraphAPI() response=graph.get( path='oauth/access_token', client_id=fb_app_id, client_secret=fb_app_secret_key, redirect_uri=post_login_url, code=code ) data=parse_qs(response) graph=GraphAPI(data['access_token'][0]) graph.post(path='me/feed',message='test post') return data['access_token'][0]
def postVideo_wall(title, message, path): graph = GraphAPI(facebook_token) try: video_id = graph.post(path='me/videos', source=open(path), title=title, description=message) except Exception as e: return dict(success=False, message=e) return dict(success=True, message='video posted correctly')
def test_post(): graph = GraphAPI("<access token>") mock_request.return_value.content = json.dumps({"id": 1}) mock_request.return_value.status_code = 200 graph.post(path="me/feed", message="He's a complicated man. And the only one that understands him is his woman") mock_request.assert_called_with( "POST", "https://graph.facebook.com/me/feed", files={}, verify=True, timeout=None, data={ "message": "He's a complicated man. And the only one that understands him is his woman", "access_token": "<access token>", }, )
def get(self): findRequest = GroupPosts.query() thisGroupPostList = findRequest.fetch() for thisGroupPost in thisGroupPostList: findRequest = MyGroupIDS.query( MyGroupIDS.strReference == thisGroupPost.strReference) thisGroupIDList = findRequest.fetch() myGraph = GraphAPI(thisGroupPost.strApiKey) for thisGroupID in thisGroupIDList: try: myGraph.post(path=str(thisGroupID.strGroupID) + '/feed', message=thisGroupPost.strMyPost) thisGroupID.isWorking = True except: thisGroupID.isWorking = False
def recognize(path, access_token, cookies, fb_dtsg): """ Face recognition using Facebook's recognize method Args: path : file path of the photo to be processed access_token : Facebook user access token cookies : Facebook cookies fb_dtsg : special Facebook token required for face recognition Returns: arr : array of recognitions with the name of recognized people and the certainity of each recognition """ URL = "https://www.facebook.com/photos/tagging/recognition/?dpr=1" graph = GraphAPI(access_token) # Uploading the picture to Facebook post_id = graph.post(path='me/photos', source=open(path, 'rb'))['id'] headers = { 'x_fb_background_state': '1', 'origin': 'https://www.facebook.com', 'accept-encoding': 'gzip, deflate, lzma', 'accept-language': 'en-US,en;q=0.8', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2723.2 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded', 'accept': '*/*', 'referer': 'https://www.facebook.com/', 'cookie': cookies, 'dnt': '1', } arr = [] payload = "" # Since the POST sometimes returns a blank array, retrying until a payload is obtained while not payload: data = 'recognition_project=composer_facerec&photos[0]=' + post_id + '&target&is_page=false&include_unrecognized_faceboxes=false&include_face_crop_src=true&include_recognized_user_profile_picture=true&include_low_confidence_recognitions=true&__a=1&fb_dtsg=' + fb_dtsg req = requests.post(URL, data=data, headers=headers) payload = json.loads(req.text.replace('for (;;);', ''))['payload'] if payload: break for recog in payload[0]['faceboxes']: name = recog['recognitions'] if name: arr.append({ 'name': name[0]['user']['name'], 'certainity': name[0]['certainty'] }) # Deleting the uploaded picture graph.delete(path=post_id) return arr
def sendFacebookPost(self, smpost, section, url, photo_url, fb_default_photo): try: print smpost.post_facebook.encode('ascii', 'ignore') #follow these steps: http://stackoverflow.com/questions/17620266/getting-a-manage-page-access-token-to-upload-events-to-a-facebook-page #Facebook needs the following permissions: # status_update, manage_pages # Initialize the Graph API with a valid access token (optional, # but will allow you to do all sorts of fun stuff). # Get token from here: https://developers.facebook.com/docs/opengraph/howtos/publishing-with-app-token/ # appGraph = GraphAPI('72296391616|_vtz8ShgOfzLSgKeDw2quIS1pCc') GRAPH_KEY = section.facebook_key graph = GraphAPI(GRAPH_KEY) # This should not expire PAGE_ID = section.facebook_page_id ### Now actually post to Facebook if photo_url and url: graph.post( path=PAGE_ID + '/feed', message=smpost.post_facebook, #+ url, link=url, #type= "photo", picture=photo_url, #picture = io.BytesIO(requests.get(photo_url).content), ) elif photo_url: graph.post( path=PAGE_ID + '/photos', message=smpost.post_facebook, type="photo", source=io.BytesIO(requests.get(photo_url).content), ) elif url: graph.post( path=PAGE_ID + '/feed', message=smpost.post_facebook, link=url, picture=fb_default_photo, ) else: graph.post( path=PAGE_ID + '/feed', message=smpost.post_facebook, ) except (FacepyError, FacebookError, OAuthError, SignedRequestError, requests.exceptions.RequestException) as e: smpost.log_error(e, section, True)
def test_delete(): graph = GraphAPI(TEST_ACCESS_TOKEN) # Generate a random message (Facebook rejects duplicate messages within a short time frame) message = ''.join( random.sample( 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(), 10)) response = graph.post(path='me/feed', message=message) assert graph.delete(response['id']) is True
def test_post(): graph = GraphAPI('<access token>') mock_request.return_value.content = json.dumps({'id': 1}) graph.post( path='me/feed', message= 'He\'s a complicated man. And the only one that understands him is his woman' ) mock_request.assert_called_with( 'POST', 'https://graph.facebook.com/me/feed', files={}, data={ 'message': 'He\'s a complicated man. And the only one that understands him is his woman', 'access_token': '<access token>' })
class FB: graph = None def __init__(self): AT = "EAAaaMaJUE7MBAMcsfGrTwm8wxSUJN9ZBYBxbaN4IGGZByYR8fY8IkWcS8ZB1nckEWQFcZA046n4qKqEJOZCpZANwuXfnL9lg3tiNQyLNoDVhdZCd9RhwZCvqgD9rrJ6P6TYzZCTIzsydPZAjBydgvak10w476dCwcyPKBwyY12yTs5WWJszUZC9YiEAco14pZBhZCJBQZD" self.graph = GraphAPI(AT) def post_status(self, message): try: self.graph.post(path="me/feed", message=message) # posting the message return True except Exception as E: print(E) return False def send_message(self): pass def check_messages(self): pass # this will check the messages which have to be passed.
def test_error_message_on_500_response(): graph = GraphAPI('<access token>') message = 'Ad Sets may not be added to deleted Campaigns.' mock_request.return_value.status_code = 500 mock_request.return_value.content = json.dumps({ 'error': { 'code': 1487634, 'type': 'Exception', 'is_transient': False, 'message': message, } }) try: graph.get('act_xxxx/adcampaigns') except GraphAPI.FacebookError as exc: eq_(exc.message, message) try: graph.post('act_xxxx/adcampaigns') except GraphAPI.FacebookError as exc: eq_(exc.message, message)
def post_in_page(page_access_token, page_id, image_file=None, message=None): """ Method to post the media and text message to your page you manage. :param page_access_token: valid api token :param page_id: Your page id :param image_file: Image File along with path :param message: Text :return: None """ try: page_graph = GraphAPI(page_access_token) print('Posting .....') if image_file: image_file = open(image_file, 'rb') if message: page_graph.post(path=page_id + '/photos', source=image_file, message=message) else: page_graph.post(path=page_id + '/photos', source=image_file) else: if not message: message = 'Hello everyone!!' page_graph.post(path=page_id + '/feed', message=message) print('Posted Successfully !! ..') except Exception as error: print('Posting failed .. ', str(error))
def post_fb(DESIRED_STATUS, POST_IMAGE_URL=None): """ :param DESIRED_STATUS: 포스팅할 메시지. :param POST_IMAGE_URL: 포스팅할 사진 (선택사항) :return: None """ # 'https://developers.facebook.com/' 에서 2개월 장기 토큰을 생성해야함 YOUR_ACCESS_TOKEN = "{YOUR_ACCESS_TOKEN}" access_token = YOUR_ACCESS_TOKEN apiConnection = GraphAPI(access_token) # 포스팅이 안되면 토큰 권한 확인 # print(apiConnection.get(path="/me/permissions")) # 사진 업로드는 있으면 하고 없으면 말고 if POST_IMAGE_URL is None: apiConnection.post(path='me/feed', message=DESIRED_STATUS) else: print( apiConnection.post(path='me/photos', url=POST_IMAGE_URL, caption=DESIRED_STATUS))
def get_facebook_advrevenues(app_id, access_token, date_min, date_max, *args, **kwargs): app_id = app_id metrics = [ 'fb_ad_network_revenue', 'fb_ad_network_request', 'fb_ad_network_cpm', 'fb_ad_network_click', 'fb_ad_network_imp', 'fb_ad_network_filled_request', 'fb_ad_network_fill_rate', 'fb_ad_network_ctr', 'fb_ad_network_show_rate', 'fb_ad_network_video_guarantee_revenue', 'fb_ad_network_video_view', 'fb_ad_network_video_view_rate', 'fb_ad_network_video_mrc', 'fb_ad_network_video_mrc_rate', 'fb_ad_network_bidding_request', 'fb_ad_network_bidding_response' ] breakdowns = ['country', 'placement'] graph = GraphAPI(access_token) query_id = None fb_data = None try: fb_data = graph.post( "/{}/adnetworkanalytics/?metrics={}&since={}&until={}&breakdowns={}&aggregation_period=day&ordering_column=time&ordering_type=ascending&access_token={}" .format(app_id, str(metrics), date_min, date_max, str(breakdowns), access_token)) query_id = fb_data['query_id'] except Exception as e: print(e) while query_id: try: fb_data = graph.get( "/{}/adnetworkanalytics_results/?query_ids=['{}']&access_token={}" .format(app_id, query_id, access_token)) if fb_data['data'][0]['status'] == 'complete': query_id = None except Exception as e: query_id = None print(e) time.sleep(1) try: audience_analytics = transform_facebook_data( fb_data['data'][0]['results']) if fb_data else None except Exception as e: print(e) return None return audience_analytics