def post_to_facebook(post_id): post = Post.objects.get(pk=post_id) if post.post_to_facebook: print("post_to_facebook activated") site = Site.objects.all()[0] page_access_token = get_fb_page_access_token() graph = GraphAPI(page_access_token) params = {"link": "http://{}{}".format(site.domain, post.get_absolute_url())} graph.post("{}/feed".format(settings.FACEBOOK_PAGE_ID), params=params) print("{} posted to facebook".format(post.id))
def create_event(request): if 'facebook_id' in request.session: c = {} c['facebook_id'] = request.session['facebook_id'] c['first_name'] = request.session['first_name'] c['last_name'] = request.session['last_name'] facebook_id = request.session['facebook_id'] facebook_user = FacebookUser.objects.filter(facebook_id=facebook_id)[0] if 'loc' in request.session and 'event' in request.session and 'restaurant' in request.session: location = Location.objects.filter(reference=request.session['loc'])[0] event = Event.objects.filter(event_id=request.session['event'])[0] restaurant = Restaurant.objects.filter(reference=request.session['restaurant'])[0] del request.session['loc'] del request.session['event'] del request.session['restaurant'] graph = GraphAPI(request.session['access_token']) event_name = "Trip to " + location.name description = "We will be going to " + location.name + ". " + "We will then be going to " + event.name + ". Then we will eat at " + restaurant.name +". This event has been created with PlanMyNY." sample_event = graph.post('me/events', params={"name":event_name, "description":description, "location":"New York City","start_time":"2014-02-09T16:00-5:00", "end_time":"2014-02-09T23:00-5:00", "privacy_type":"FRIENDS"}) event_id = sample_event['id'] c['event_link'] = "http://www.facebook.com/events/" + event_id trip = Trip.create(facebook_user,location,event,restaurant,c['event_link']) trip.save() return render_to_response("success.html", c) else: return redirect("profile/") else: return redirect("/")
def worker(): while 1: item = queue.get() print 'job running' #print item email_stories = [] params = {'access_token': item['access_token']} graph = GraphAPI(item['access_token']) #full list of following ids unchunked = [following['fb_id'] for following in item['following']] #divide full list into array of arrays of 50 chunks = [unchunked[i:i+49] for i in range(0, len(unchunked), 49)] #make graph call for each set of 50 for chunk in chunks: params['batch'] = json.dumps([{'method': 'GET', 'relative_url': '/'+c} for c in chunk]) try: fb_results = graph.post('/', params=params) except FacebookClientError: try: fb_results = graph.post('/', params=params) except FacebookClientError: #fb didn't like this, continue continue #iterate over all of the results from facebook if fb_results: for fb_result in fb_results: if not fb_result: continue if not fb_result.get('body'): print fb_result continue parsed_body = json.loads(fb_result['body']) if not parsed_body.get('id'): print parsed_body print params continue if not parsed_body: #SENTRY ERROR LOG HERE #client.captureMessage('Cannot json decode') #sometimes facebook gives us a false body to f**k with us #so lets just skip it ''' { 'body': 'false', 'headers': [{ 'name': 'Access-Control-Allow-Origin', 'value': '*' }, { 'name': 'Cache-Control', 'value': 'private, no-cache, no-store, must-revalidate' }, { 'name': 'Connection', 'value': 'close' }, { 'name': 'Content-Type', 'value': 'text/javascript; charset=UTF-8' }, { 'name': 'ETag', 'value': '"7cb6efb98ba5972a9b5090dc2e517fe14d12cb04"' }, { 'name': 'Expires', 'value': 'Sat, 01 Jan 2000 00:00:00 GMT' }, { 'name': 'Pragma', 'value': 'no-cache' }], 'code': 200 }, ''' continue #grab our fb db result from item following list from db for followed in item['following']: if followed['fb_id'] == parsed_body['id']: #got our match, compare relationship statuses if 'relationship_status' in parsed_body and \ parsed_body['relationship_status'] in relationship_codes and \ int(relationship_codes[parsed_body['relationship_status']]) != int(followed['rel_status_id']): #got a change! #make and add message to email stories message = parsed_body['name']+' is now '+parsed_body['relationship_status'].lower() email_stories.append({ 'id': parsed_body['id'], 'message': message }) #email_stories.append(message); #add DB notification notification = Notification( user_id=item['user_id'], followed_id=followed['followed_id'], message=message, rel_status_id=int(relationship_codes[parsed_body['relationship_status']]), timestamp=int(time.time()), fb_id=followed['fb_id'] ) session.add(notification) #update row session.query(Followed) \ .filter_by(id=followed['followed_id']) \ .update({Followed.rel_status_id: int(relationship_codes[parsed_body['relationship_status']])}) elif 'relationship_status' not in parsed_body and \ int(relationship_codes['Not set']) != int(followed['rel_status_id']): #got a change from listed to not listed message = parsed_body['name']+' has hidden their relationship status.' email_stories.append({ 'id': parsed_body['id'], 'message': message }) #email_stories.append(message) #add DB notification notification = Notification( user_id=item['user_id'], followed_id=followed['followed_id'], message=message, rel_status_id=int(relationship_codes['Not set']), timestamp=int(time.time()), fb_id=followed['fb_id'] ) session.add(notification) #update row session.query(Followed) \ .filter_by(id=followed['followed_id']) \ .update({Followed.rel_status_id: int(relationship_codes['Not set'])}) #send email if item['email_opt'] and email_stories: subject = today.strftime('People have changed their relationships - SingleYet %m/%d/%Y') body = 'You have new SingleYet notifications!\n\n' #body = body+'\n'.join(email_stories) html_body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/></head><body><div style="background-color: #1B1B1B;color: #fff;font-family: \'Helvetica Neue\',Helvetica,Arial,sans-serif;padding:3px 10px;font-size: 20px;color: #999;font-weight:200;margin-bottom: 15px;"><img src="http://singleyet.com/img/logo_sm.png" width="20"/> SingleYet?</div><strong>People have been changing their relationship statuses</strong><p>Check to see who is <em>single</em> and message them!</p><table width="320" cellspacing="7" style="margin: 10px 0 20px;">' for story in email_stories: body += '\n'+story['message'] html_body += '<tr><td width="50"><img src="https://graph.facebook.com/%(id)s/picture"/></td><td width="270"><p style="font-size:13px;color:#333;font-family: \'Helvetica Neue\',Helvetica,Arial,sans-serif;"> %(message)s<br/><a style="text-decoration: none;color:#08C;font-size:13px;font-family: \'Helvetica Neue\',Helvetica,Arial,sans-serif;" href="https://facebook.com/messages/%(id)s" target="_blank">Message</a></p></td></tr>' % {'id': story['id'], 'message': story['message']} html_body += '</table><div style="font-size:11px;color:#ccc;border-top:1px solid #ccc;padding-top:5px;">This email was sent to <a style="text-decoration: none;color:#08C;font-size:11px;font-family: \'Helvetica Neue\',Helvetica,Arial,sans-serif;" href="mailto:%(email)s" target="_blank">%(email)s</a>. If you no longer wish to recieve these emails, <a style="text-decoration: none;color:#08C;font-size:11px;font-family: \'Helvetica Neue\',Helvetica,Arial,sans-serif;" href="http://singleyet.com/settings/" target="_blank">unsubscribe</a>.</div></body></html>' % {'email': item['email']} pmail = PMMail(api_key=POSTMARK_API_KEY, sender="*****@*****.**", to=item['email'], subject=subject, text_body=body, html_body=html_body) pmail.send() queue.task_done() # Let the queue know that the job is done