Python facebook-sdk post to page - python

I'm trying to post to a Facebook Page I manage with the Python facebook-sdk but I can't figure out how to do it. I can post to my Facebook Wall like so:
graph.put_object("me", "feed", message='My message goes here')
I can get the pages I manage and the access tokens like so:
fbpages = graph.request('me/accounts')
But I can't find any resources to indicate how to actually then use the access token to post to the page. I imagine it would be something like this:
graph.put_object("me", "page id", "access token", message='My message goes here')
How would I actually go about doing this with the Python facebook-sdk?
I'm using 'pythonforfacebook/facebook-sdk'.

Thank's to WizKid for pointing me in the right direction. For anyone else with this problem it is solved like so:
graph = facebook.GraphAPI(page_access_token)
graph.put_object("page id", "feed", message='My message goes here')

With the new API(v2.8), you can use the following code:
import facebook
def main():
graph = facebook.GraphAPI(access_token='your_user_access_token', version='2.8')
#if version 2.8 show error use 2.6
attachment = {
'name': 'Link name'
'link': 'https://www.example.com/',
'caption': 'Check out this example',
'description': 'This is a longer description of the attachment',
'picture': 'https://www.example.com/thumbnail.jpg'
}
graph.put_wall_post(message='Check this out...', attachment=attachment, profile_id='your_page_id')
if __name__ == "__main__":
main()
You can change the attachment as your need. I think this will be helpful if someone needs to use the new API. You need to install facebook sdk first.
pip install facebook-sdk

Related

Microsoft Graph API REQUESTS with Python: "Insufficient privileges to complete the operation" error when making simple call

Receiving the following error response when doing a basic Graph API POST using REQUESTS in Python:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "36c01b2f-5c5c-438a-bd10-b3ebbc1a17c9",
"date": "2019-04-05T22:39:37"
}
}
}
Here is my token request and Graph request using REQUESTS in Python:
redirect_uri = "https://smartusys.sharepoint.com"
client_id = 'd259015e-****-4e99-****-aaad67057124'
client_secret = '********'
tennant_id = '15792366-ddf0-****-97cb-****'
scope = 'https://graph.microsoft.com/.default'
####GET A TOKEN
payload = "client_id="+client_id+"&scope="+scope+"&client_secret="+client_secret+"&grant_type=client_credentials"
headers = {'content-type':'application/x-www-form-urlencoded'}
tokenResponse = requests.post('https://login.microsoftonline.com/'+tennant_id+'/oauth2/v2.0/token',headers=headers, data=payload)
json_tokenObject = json.loads(tokenResponse.text)
authToken = json_tokenObject['access_token']
#### Make a call to the graph API
graphResponse = requests.get('https://graph.microsoft.com/v1.0/me/',headers={'Authorization':'Bearer '+authToken})
if tokenResponse.status_code != 200:
print('Error code: ' +graphResponse.status_code)
print(graphResponse.text)
exit()
print('Request successfull: Response: ')
print(graphResponse.text)
print('Press any key to continue...')
x=input()
According to the documentation ( https://learn.microsoft.com/en-us/graph/api/resources/users?view=graph-rest-1.0 ) for this /me call, I need just one of the following permissions:
User.ReadBasic.All
User.Read
User.ReadWrite
User.Read.All
User.ReadWrite.All
Directory.Read.All
Directory.ReadWrite.All
Directory.AccessAsUser.All
and I have all of these on both application and delegated permissions in the azure application manager.
What am I doing wrong here? I feel like it's something small but I just can't figure this out.
I decoded my token using: http://calebb.net/ and I do not see a spot for "AUD" or "role" or "scope" so maybe that is where I am doing it wrong?
I looked everywhere and can't find a resolution, any help would be VERY much appreciated.
Thank you.
This sounds like you forgot to "Grant Permissions" to your application.
See this answer.
I finally figured this out, it had to do with Admin rights that needed to be granted by the Admin for our Office 365.
it was as simple as giving my Office admin the following link and having him approve it:
https://login.microsoftonline.com/{TENNANT ID HERE}/adminconsent?client_id={CLIENT ID HERE}
Instantly worked.

Post photo on Facebook page doesn't work

I can't post a photo on a facebook page with my facebook app (V 2.11). My app has the manage_pages e publish_pages permissions. I have a page token too. Post text works well. If I use a image url from my domain the post doesn't work if I use a image url from another domain (eg: tripadvisor) the post works. My domain has a SSL DigiCert SHA2 Secure Server CA.
This is my code:
def PostPhotoFB(photo, title, link, text , fb_access_token, fb_page_id, desc):
facebook_data = {'url': photo,
'access_token': fb_access_token,
'caption': text,
}
facebook_request = "https://graph.facebook.com/" + fb_page_id + "/photos"
response_facebook = requests.post(facebook_request, data=facebook_data)
if response_facebook.status_code == 200:
return json.loads(response_facebook.text)['id']
else:
return ""
with an image in my server I get 400 and
"(#324) Missing or invalid image
file","type":"OAuthException","code":324
I use Jpg or PNG image.
this is a exemple url "https://www.stbrun.com/static/img_locale/24/biciclette.jpg"
I don't understand. Can you help me please? Thanks a lot
Using the graph api, you can post like this:
import facebook
def main():
graph = facebook.GraphAPI(access_token='your_user_access_token',
version='2.8')
#if version 2.8 shows error use 2.6
attachment = {
'name': 'Link name'
'link': 'https://www.example.com/',
'caption': 'Check out this example',
'description': 'This is a longer description of the attachment',
'picture': 'https://www.example.com/thumbnail.jpg'
}
graph.put_wall_post(message='Check this out...',
attachment=attachment, profile_id='your_page_id')
if __name__ == "__main__":
main()
If you leave the profile_id blank, it will default to your profile. In the attachment dictionary, you can leave the extra fields that you don't need. First you need to install fackbook-sdk:
pip install facebook-sdk

Instagram API - Unable to generate proper access token (Python)

I am getting a JSON return like this:
{'data': [],
'meta': {'code': 200},
'pagination': {'deprecation_warning': 'next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead'}}
I am doing the following (where I'm omitting my personal info for the sake of this post):
CONFIG = {
'client_id': '',
'client_secret': '',
'redirect_uri': 'http://localhost:8515/oauth_callback'
}
api = InstagramAPI(**CONFIG)
Then I follow this link (inserting my info):
https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
and I get an access token that allows me to do some things like the following:
api = InstagramAPI(access_token = access_token)
recent_media, next = api.user_recent_media()
but when I try to search for "nhl", for example:
url = requests.get('https://api.instagram.com/v1/tags/nhl/media/recent?access_token='+access_token)
url.json()
I get the error result seen at the top of this post.
On the other hand, using the apigee console to access the instagram API, I get a different access token (by allowing access to my instagram account) that gives the JSON response I'm looking for:
{"pagination":{"next_max_tag_id":"AQD9K8O5THfHA7yp1waOwivzT ...etc
including the data I want:
"data":[{"attribution":null,"tags":["nhl","zachayfucale","nhlpa"
...etc
My question is: how can I generate the access token that apigee was able to get?
I have also been able to acquire an access token a different way and I can include this method too if anyone asks, however it does not help solve my problem.

Reading page's messages with Python Facebook SDK

Basically i need to get all messages of a page using facebook SDK in python.
Following some tutorial i arrived to this point:
import facebook
def main():
cfg = {
"page_id" : "MY PAGE ID",
"access_token" : "LONG LIVE ACCESS TOKEN"
}
api = get_api(cfg)
msg = "Hre"
status = api.put_wall_post(msg) #used to post to wall message Hre
x = api.get_object('/'+str(MY PAGE ID)+"/conversations/") #Give actual conversations
def get_api(cfg):
graph = facebook.GraphAPI(cfg['access_token'])
resp = graph.get_object('me/accounts')
page_access_token = None
for page in resp['data']:
if page['id'] == cfg['page_id']:
page_access_token = page['access_token']
graph = facebook.GraphAPI(page_access_token)
return graph
if __name__ == "__main__":
main()
The first problem is that api.get_object('/'+str(MY PAGE ID)+"/conversations/")returns a dictionary containing many informations, but what i would like to see is the messages they sent to me, while for now it print the user id that sent to me a message.
The output look like the following:
{u'paging': {u'next': u'https://graph.facebook.com/v2.4/571499452991432/conversations?access_token=Token&limit=25&until=1441825848&__paging_token=enc_AdCqaKAP3e1NU9MGSsvSdzDPIIDtB2ZCe2hCYfk7ft5ZAjRhsuVEL7eFYOOCdQ8okvuhZA5iQWaYZBBbrZCRNW8uzWmgnKGl69KKt4catxZAvQYCus7gZDZD', u'previous': u'https://graph.facebook.com/v2.4/571499452991432/conversations?access_token=token&limit=25&since=1441825848&__paging_token=enc_AdCqaKAP3e1NU9MGSsvSdzDPIIDtB2ZCe2hCYfk7ft5ZAjRhsuVEL7eFYOOCdQ8okvuhZA5iQWaYZBBbrZCRNW8uzWmgnKGl69KKt4catxZAvQYCus7gZDZD&__previous=1'}, u'data': [{u'link': u'/communityticino/manager/messages/?mercurythreadid=user%3A1055476438&threadid=mid.1441825847634%3Af2e0247f54f5c4d222&folder=inbox', u'id': u't_mid.1441825847634:f2e0247f54f5c4d222', u'updated_time': u'2015-09-09T19:10:48+0000'}]}
which is basically paging and data.
Given this is there a way to read the conversation?
In order to get the messages content you need first to request the single messages in the conversation, accessible with the 'id' field in the dictionary you copied, result of
x = api.get_object('/'+str(MY PAGE ID)+"/conversations/") #Give actual conversations
you can request the messages in the conversation by calling
msg = api.get_object('/'+<message id>)
Here it gets tricky, because following the graph api documentation you should receive back a dictionary with ALL the possible fields, including the 'message' (content) field. The function however returns only the fields 'created_time' and 'id'.
Thanks to this other question Request fields in Python Facebook SDK I found that you can request for those fields by adding a dict with such fields specified in the arguments of the graph.get_object() function. As far as I know this is undocumented in the facebook sdk reference for python.
The correct code is
args = {'fields' : 'message'}
msg = api.get_object('/'+<message id>, **args)
Similar question: Read facebook messages using python sdk

How to get page access token

I create app in facebook and page in my profile. In "Select how your app integrates with Facebook" section I don't select any option because I want only post text to facebook page (maybe this is problem?).
I have this code:
FACEBOOK_APP_ID = 'myappid'
FACEBOOK_APP_SECRET = 'myappsecret'
FACEBOOK_PROFILE_ID = 'myprofileid'
oauth_args = dict(client_id = FACEBOOK_APP_ID,
client_secret = FACEBOOK_APP_SECRET,
scope = 'publish_stream',
grant_type = 'client_credentials'
)
oauth_response = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(oauth_args)).read()
oauth_response looks good
but when I run:
resp = urllib.urlopen('https://graph.facebook.com/me/accounts?'+oauth_response).read()
I get error:
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
What am I doing wrong? I want to post on page wall some text when, for example, I click button on my website (Django).
UPDATE:
Ok, I get the pages data in json. I parsing it and I get page_access_token, but when I call this:
attach = {
"name": 'Hello world',
"link": 'http://linktosite',
"caption": 'test post',
"description": 'some test'
}
facebook_graph = facebook.GraphAPI(page_access_token)
try:
response = facebook_graph.put_wall_post('', attachment=attach)
except facebook.GraphAPIError as e:
print e
I get error: "The target user has not authorized this action"
This question is basically asking about the same problem, and the answer seems to be what you're looking for: (OAuthException - #2500) An active access token must be used to query information about the current user
If the page_access_token is correct, I guess you (the page admin) have not yet granted permission for your facebook application to post message to facebook page.
Check facebook login function in client side, whether you ask enough permission, the scope option should be 'mange_pages publish_stream photo_upload...' depends on your requirement, rather than only 'mange_pages'

Categories

Resources