Rails 3.1 - Facebook Page API calls - facebook

I have the following working perfectly for calls to Facebook pages with simple URLS like: www.facebook.com/TurbonegroHQ
def get_facebook
#artist = Artist.accessible_by(current_ability).find(params[:id])
if #artist.facebook_url.present?
require 'open-uri'
require 'json'
result = JSON.parse(open("https://graph.facebook.com/"<<#artist.facebook_url).read)
#hometown = result["hometown"]
#band_members = result["band_members"]
#likes = result["likes"]
end
end
However, when a Facebook page URL isn't in this format, but something like https://www.facebook.com/pages/Clutch-The-Bakerton-Group-Weathermaker-Music/16637738637 it fails. Any ideas how I can get around this?
Thanks in advance?

TurbonegroHQ is the username of the page - this is interchangeable with the object ID in the Graph API.
If the page doesn't have a username you need to access it via the ID instead. In that case https://graph.facebook.com/16637738637 is the URL to access
Usually you'll have IDs rather than the URLs as the ID is returned in the API on all the endpoints I can think of

Related

Facebook Server-Side API - push custom events to create Custom Audience

We try to use Server-Side API to push custom events to our pixel in order to create event-based Custom Audiences in Facebook Ads (https://developers.facebook.com/docs/marketing-api/facebook-pixel/server-side-api/)
We use _fbp cookie value to match users (it's a first party cookie created on our website by FB pixel).
For example (Python):
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adspixel import AdsPixel
my_app_id = 'X'
my_app_secret = 'X'
my_access_token = 'X'
my_pixel_id = 'X'
FacebookAdsApi.init(access_token=my_access_token, app_id=my_app_id, app_secret=my_app_secret)
fields = []
params = {
'data': [{'event_name': 'icrm_test_20191113_fbp_1m', 'event_time': 1573230217, 'user_data':{'fbp': 'fb.1.1558571054389.1098115397'}}]
}
print(AdsPixel(my_pixel_id).create_event(fields=fields, params=params))
The problem is, when we create a Custom Audience in Facebook Ads, the size of the list is always < 1000, even if we push hundreds of thousands of cookie IDs, which means Facebook matched a very low % of cookies, which were sent.
Custom Audience definition based on server-side event:
List size is always <1000, no matter how many fbp cookies are sent:
It seems like there is some kind of an issue matching _fbp cookies to Facebook user profiles. Is there any known way of improving/fixing matching results? We can't use hashes of sensitive data.
External_id matching (https://developers.facebook.com/docs/marketing-api/facebook-pixel/server-side-api/parameters) also gave us similar results.
The event time you are using there translates to 11/08/2019 # 4:23pm (UTC).
So they're not gonna get included in your 30 day window.
Try importing time
import time
Then set
'event_time': int(time.time())

Issue retrieving friendlists from Facebook through Koala gem

I am working with a project started by someone else which interacts with Facebook through the Koala gem. For some odd reason it will allow me to create friend lists but when I retrieve them I get nothing. I can verify I have friend lists available through the Graph API by using Facebook's Graph API Explorer tool, and I do have the "manage_friendlists" permission in the application. I can also verify that it successfully adds friend lists through this application and trying to add an identically named friend list will return an error (which it should). However, when it gets to the point of actually retrieving them through the app, it simply returns the hash
{:me => {:id => 'my_id'}}
with nothing else. The method is written as
def friendlists
graph_api.get_objects('me', {fields: 'friendlists'})['me']['friendlists']['data']
end
which gives an 'undefined method [] for nilClass' since there is no 'friendlists' nested hash returning. I am using Koala 1.4.0 if that makes any difference. Any thoughts or suggestions? Thanks!
I am also using koala gem... you can use it as follows:
session['fb_access_token'] is the one when user is logging in, I am assigning as follow:
session['fb_access_token'] = auth['credentials']['token']
def self.fetching_facebook_friends
#graph = Koala::Facebook::API.new(session['fb_access_token'])
profile = #graph.get_object("me")
#profile_image = graph.get_picture("me")
friends = #graph.get_connections("me", "friends?fields=id, name, picture.type(large)")
end

Facebook Private Messaging

It is said, that it is not possible to initiate new conversation through the API alone, except using Facebook's own Form integrated in the app. Is this correct, or is there some new API, which enables me to initiate a new conversation?
To reply to an existing conversation, I retrieved the conversations id using the following FQL Query "SELECT thread_id, . WHERE viewer_id={0} AND folder_id=0". Afterwards I retrieved the PageAccessToken for my app page using my user Access token, and tried to use this call:
*You can reply to a user's message by issuing an HTTP POST to /CONVERSATION_ID/messages with the following parameters [conversation id, message]. A conversation ID look like t_id.216477638451347.*
My POST Call looked like this (this is not a valid thread id): /t_id.2319203912/messages with message parameter filled. But it always said "Unknown method". Can you help me out with this one? Is there a parameter missing? I passed in the page's Access Token to call this one.
Is there some API out (except Facebook's Chat API), that I am missing, which can send private messages to users?
Edit:
What I wonder about is, that the code below only returns a single page, the application's page. Is this correct, or is there another page token required? This is what bugged me the most about the returned page.
The FacebookClient uses my UserToken to perform the next following task.
This is the code to retrieve my Page Access Token:
dynamic pageService = FacebookContext.FacebookClient.GetTaskAsync("/"+UserId+"/accounts").Result;
dynamic pageResult = pageService.data[0];
_pageId = pageResult["id"].ToString();
return pageResult["access_token"].ToString();
Now the code to retrieve my ConversationÍd:
dynamic parameters = new ExpandoObject();
parameters.q = string.Format("SELECT thread_id, folder_id, subject, recipients, updated_time, parent_message_id, parent_thread_id, message_count, snippet, snippet_author, object_id, unread, viewer_id FROM thread WHERE viewer_id={0} AND folder_id=0", FacebookContext.UserId);
dynamic conversations = FacebookContext.FacebookClient.GetTaskAsync("/fql",parameters).Result;
The following code is executed using the access token retrieved from the code above (page access token request).
Now the Code used to send the reply:
dynamic parameters = new ExpandoObject();
parameters.message = CurrentAnswer;
string taskString = "/t_id." + _conversationId + "/messages";
dynamic result = FacebookContext.FacebookClient.PostTaskAsync(taskString,parameters).Result;
return true;
I also tried it with facebook's graph API Debugger using the token, which is returned by my first part of code. But with the same error message.

Retrieve User ID of Facebook App Invitor

In the context of a given Facebook app, suppose User A invited user B to start using it. Once User B accepts to use the app, is there any way to retrieve the ID of User A programmatically (via either PHP/JS SDK) ? This doesn't seem quite documented.
For what it's worth, A/B users are friends, if it's any use.
when user comes following the app request, you can get request id's using
$_GET['request_ids']
then retrieve all the request ids with which you can call graph api to get the corresponding request details like below:
if(isset($_GET['request_ids']))
{
$request_ids = $_GET['request_ids'];
}
$request_ids = explode(",", $request_ids);
foreach($request_ids as $request_id)
{
$request_object = $facebook->api($request_id);
//this $request_object have sender facebook id in the field uid_from
}
If you look here:
http://developers.facebook.com/docs/reference/dialogs/requests/
You can see the object layout. Of note is the data property:
Optional, additional data you may pass for tracking. This will be
stored as part of the request objects created. The maximum length is
255 characters.
In this object you can add your referring UserId and then when the request is claimed, you can then process it on your end.
Hope this helps.

Nothing except "None" returned for my Python web.py Facebook app when I turn on "OAuth 2.0 for Canvas"

I am a beginning Facebook app developer, but I'm an experienced developer. I'm using web.py as my web framework, and to make matters a bit worse, I'm new to Python.
I'm running into an issue, where when I try to switch over to using the newer "OAuth 2.0 for Canvas", I simply can't get anything to work. The only thing being returned in my Facebook app is "None".
My motivation for turning on OAuth 2.0 is because it sounds like Facebook is going to force it by July, and I might as well learn it now and now have to rewrite it in a few weeks.
I turned on "OAuth 2.0 for Canvas" in the Advanced Settings, and rewrote my code to look for "signed_request" that is POSTed to my server whenever my test user tries to access my app.
My code is the following (I've removed debugging statements and error checking for brevity):
#!/usr/bin/env python
import base64
import web
import minifb
import urllib
import json
FbApiKey = "AAAAAA"
FbActualSecret = "BBBBBB"
CanvasURL = "http://1.2.3.4/fb/"
RedirectURL="http://apps.facebook.com/CCCCCCCC/"
RegURL = 'https://graph.facebook.com/oauth/authorize?client_id=%s&redirect_uri=%s&type=user_agent&display=page' % (FbApiKey, RedirectURL)
urls = (
'/fb/', 'index',
)
app = web.application(urls, locals())
def authorize():
args = web.input()
signed_request = args['signed_request']
#split the signed_request via the .
strings = signed_request.split('.')
hmac = strings[0]
encoded = strings[1]
#since uslsafe_b64decode requires padding, add the proper padding
numPads = len(encoded) % 4
encoded = encoded + "=" * numPads
unencoded = base64.urlsafe_b64decode(str(encoded))
#convert signedRequest into a dictionary
signedRequest = json.loads(unencoded)
try:
#try to find the oauth_token, if it's not there, then
#redirect to the login page
access_token = signedRequest['oauth_token']
print(access_token)
except:
print("Access token not found, redirect user to login")
redirect = "<script type=\"text/javascript\">\ntop.location.href=\"" +_RegURL + "\";\n</script>"
print(redirect)
return redirect
# Do something on the canvas page
returnString = "<html><body>Hello</body></html>"
print(returnString)
class index:
def GET(self):
authorize()
def POST(self):
authorize()
if __name__ == "__main__":
app.run()
For the time being, I want to concentrate on the case where the user is already logged in, so assume that oauth_token is found.
My question is: Why is my "Hello" not being outputted, and instead all I see is "None"?
It appears that I'm missing something very fundamental, because I swear to you, I've scoured the Internet for solutions, and I've read the Facebook pages on this many times. Similarly, I've found many good blogs and stackoverflow questions that document precisely how to use OAuth 2.0 and signed_request. But the fact that I am getting a proper oauth_token, but my only output is "None" makes me think there is something fundamental that I'm doing incorrectly. I realize that "None" is a special word in python, so maybe that's the cause, but I can't pin down exactly what I'm doing wrong.
When I turn off OAuth 2.0, and revert my code to look for the older POST data, I'm able to easily print stuff to the screen.
Any help on this would be greatly appreciated!
How embarrassing!
In my authorize function, I return a string. But since class index is calling authorize, it needs to be returned from the class, not from authorize. If I return the return from authorize, it works.