Unable to post to facebook page's feed via an application - python

I'm unable to post to my website's facebook page wall via my facebook application even though it has the publish_stream, offline_access & manage_pages permission for posting to the page (along with its correct access token).
The application is able to post to '/page_id/links/' but not to '/page_id/feed/'.
See the code below:
graph = facebook.GraphAPI(settings.FB_PAGE_ACCESS_TOKEN_FOR_FB_APP)
attachment = {}
message = 'Hello! check the link!'
site = Site.objects.get_current()
attachment['name'] = '%s' % idea.title
attachment['link'] = 'http://%s%s' %(site,idea.get_absolute_url())
attachment['caption'] = 'addressing problem "%s"' % idea.problem
attachment['description'] = '%s' % striptags(idea.desc)
attachment['properties'] = {'See more': {'text':'Featured ideas', 'href':'http://%s' % site}}
# this works; posts to /fbpage/links/
graph.put_object(settings.FACEBOOK_PAGE, "links", message=message, **attachment)
# this does not work; posts to /fbpage/feed/
graph.put_wall_post(message, attachment, settings.FACEBOOK_PAGE)

I posted my solution to get the right access token in this question:
How to get the access token to post on behalf of a facebook page via a custom application?

Related

atlassian-python-api exception by using confluence.delete_attachment()

i try to delete all attachments from a site with confluence.delete_attachment(page_id, filename, version), butt it throws always the same exception:
requests.exceptions.HTTPError: 401 Client Error: Authorization Required for url:
I am currently deleting the attachments as follows:
from atlassian import Confluence
confluence_url = 'https://xxx/confluence/'
confluence_usr = os.environ.get('CONFLUENCE_CREDS_USR')
confluence_psw = os.environ.get('CONFLUENCE_CREDS_PSW')
confluence = Confluence(url=confluence_url, username=confluence_usr, password=confluence_psw)
# Check site response, if site not reachable, check 5 times every 5 sec
response = resilient_confluence_http_get_request(f'{confluence_url}rest/api/content/{page_ids[csv_file]}')
# Check site response, if site not reachable, check 5 times every 5 sec
attachment = confluence.get_attachments_from_content(page_ids[csv_file])
print(f"attachment type: {type(attachment)}")
print(f"attachment content:\n {attachment}\n\n")
att_to_del = []
indices = 0
for i in attachment['results']:
print(f"id type: {type(attachment['results'][indices]['id'])}")
att_to_del.append(attachment['results'][indices]['id'])
indices += 1
print(f"delete attachments with id's {att_to_del}")
for id_to_delete in att_to_del:
response = requests.delete(f'https://xxx/confluence/rest/api/content/{id_to_delete}',
auth=(confluence_usr, confluence_psw))
The delete function is the only one that doesn't work. What am I doing wrong?
Here i try to delete with confluence.delete_attachment(...):
def response_wait_repeat():
attachments = confluence.get_attachments_from_content('my_site_id')
print(attachments)
confluence.delete_attachment('my_site_id', 'my_filename', version=None)
I assume you are using atlassian-python-api
as the examples on the pypi documentation, you first need to create a connection to the confluence:
from atlassian import Confluence
confluence = Confluence(
url='http://localhost:8090',
username='admin',
password='admin')
status = confluence.create_page(
space='DEMO',
title='This is the title',
body='This is the body. You can use <strong>HTML tags</strong>!')
print(status)
If you are still getting this error (401 Authorization Required) I would check manually in confluence, whether you have the permission to do these such actions.
It's probably the case, because you are saying the only action you cannot preform is delete.
otherwise I would contact the confluence admin.

how can i update an alfresco share site?

I am trying to update a website (just change its name) I have created with the Share script in Alfresco, but I am getting a 401 response. I'm sure my login and password are correct.
Code:
s = requests.Session()
data = {'username':"admin", 'password':"admin"}
url = "http://127.0.0.1:8080/share/page/dologin"
r = s.post(url, data=data)
if (r.status_code != 200) :
print "Incorrect login or password "
url1 = "http://127.0.0.1:8080/alfresco/service/api/sites/OdooSite50"
print url_alfresco
jsonString = JSONEncoder().encode({
"title" : name
})
headers = {'content-type': 'application/json',"Accept":"application/json"}
site = s.put(url1,headers=headers,data=data)
if (site.status_code != 200) :
print " Error while creating site"
print site.status_code
I am getting the error on the second part. The login part works without any problems.
Can you tell me what I do wrong?
This is because you are using different contexts to make your queries.
The Alfresco stack is made of multiples parts :
alfresco.war
share.war
solr.war
If we forget the solr part and focus on your problem, you have :
a content repository (alfresco) which contains the core services of alfresco
a web application (share) which contains the web ui of your application and communicate the content repository to do some actions
They don't share the same context and have different lives. One can be on a server, the other one can be in another one server.
So this mean, when you are authenticating, you are doing it on the share context :
http://127.0.0.1:8080/share/page/dologin
and when you are trying to update your website, you are doing it on the alfresco context (on which you are not authenticated yet) :
http://127.0.0.1:8080/alfresco/service/api/sites/OdooSite50
I see two solutions then :
You do your authentication on the alfresco context (webservice alfresco/s/api/login) and then you will be authenticated for calling your alfresco site services
You pass through the share proxy : /alfresco/service/api/sites becomes /share/proxy/alfresco/api/sites

Read facebook messages using python sdk

I'm trying to read facebook conversations of a page using a python script. With this code
import facebook
at = "page access token"
pid = "page id"
api = facebook.GraphAPI( at )
p = api.get_object( 'me/conversations')
print p
I get a dictionary containing the following
{'paging': {'next': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&until=1454344040&__paging_token=<my_access_token>', 'previous': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&since=1454344040&__paging_token=<my_access_token>'}, 'data': [{'link': '/Python-1745249635693902/manager/messages/?mercurythreadid=user%3A100000386799941&threadid=mid.1454344039847%3A2e3ac25e0302042916&folder=inbox', 'id': 't_mid.1454344039847:2e3ac25e0302042916', 'updated_time': '2016-02-01T16:27:20+0000'}]}
What are those fields? How can I get the text of the message?
Edit: I tried asking for the "messages" field by adding
msg = api.get_object( p['data'][0]['id']+'/messages')
print msg
but it just returns the same fields. I've searched in the API docs for a while, but I didn't find anything helpful. Is it even possible to read the message content of a facebook page's conversation using python?
I managed to find the answer myself; the question was not well posed and did not match what I was exactly looking for.
I wanted to get the content of the messages of facebook conversations of a page. Following the facebook graph API documentation, this can be achieved by asking for the conversations ({page-id}/conversations), then the messages in said conversations ({conversation-id}/messages, https://developers.facebook.com/docs/graph-api/reference/v2.5/conversation/messages), and finally asking for the message itself should return a dict with all the fields, content included (/{message-id}, https://developers.facebook.com/docs/graph-api/reference/v2.5/message).
At least this is how I believed it should have been; however the last request returned only the fields 'created_time' and 'id'.
What I was really trying to ask was a way to fetch the 'message' (content) field. I was assuming the function graph.get_object() from the official python facebook sdk should have returned all the fields in any case, since it has only one documented argument (http://facebook-sdk.readthedocs.org/en/latest/api.html) - the graph path for the requested object, and adding additional field request is not allowed.
The answer I was looking for was in this other question, Request fields in Python Facebook SDK.
Apparently, it's possible to ask for specific fields ( that are not returned otherwise ) by passing an **args dict with such fields along with the path requested.
In a GET request to the Facebook graph that would be the equivalent of adding
?fields=<requested fieds>
to the object path.
This is the working code:
#!/usr/bin/env python
import facebook
at = <my access token>
pid = <my page id>
api = facebook.GraphAPI( at )
args = {'fields' : 'message'} #requested fields
conv = api.get_object( 'me/conversations')
msg = api.get_object( conv['data'][0]['id']+'/messages')
for el in msg['data']:
content = api.get_object( el['id'], **args) #adding the field request
print content

How do I update FB Status using Python & GraphAPI?

How do I update FB Status using Python & GraphAPI? This question has been asked before, but many of the solutions have been deprecated and the requirement of GraphAPI seems to have rendered many solutions irrelevant.
I have fiddled around with the fbpy, Facebook, OAuth, and oauth2 packages, and have looked through their examples, but I still cannot figure out how to get them working. I have no trust in any of the code or the packages I have been using and am wondering if anyone has any definitive solutions that they know will work.
First you need to do is understand login flows. You should understand if you easily want to switch through the different Facebook libraries. Therefore it can have code that is very verbose to code that is very simple based on implementation.
The next thing is that there are different ways to implement handling OAuth and different ways to display and launch your web app in Python. There is no way to authorize without hitting a browser. Otherwise you would have to keep copy pasting the access_token to the code.
Let's say you chose web.py to handle your web app presentation and requests.py to handle the Graph API HTTP calls.
import web, requests
Then setup the URL we want all request to go through
url = (
'/', 'index'
)
Now get your application id, secret and post-login URL you would like to use
app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"
This code will have one class index to handle the logic. In this class we want to deal with the authorization code Facebook will return after logging in
user_data = web.input(code=None)
code = user_data.code
From here setup a conditional to check the code
if not code:
# we are not authorized
# send to oauth dialog
else:
# authorized, get access_token
Within the "not authorized" branch, send the user to the dialog
dialog_url = ( "http://www.facebook.com/dialog/oauth?" +
"client_id=" + app_id +
"&redirect_uri=" + post_login_url +
"&scope=publish_stream" )
return "<script>top.location.href='" + dialog_url + "'</script>"
Else we can extract the access_token using the code received
token_url = ( "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + app_id +
"&redirect_uri=" + post_login_url +
"&client_secret=" + app_secret +
"&code=" + code )
response = requests.get(token_url).content
params = {}
result = response.split("&", 1)
for p in result:
(k,v) = p.split("=")
params[k] = v
access_token = params['access_token']
From here you can choose how you want to deal with the call to update the status, for example a form,
graph_url = ( "https://graph.facebook.com/me/feed?" +
"access_token=" + access_token )
return ( '<html><body>' + '\n' +
'<form enctype="multipart/form-data" action="' +
graph_url + ' "method="POST">' + '\n' +
'Say something: ' + '\n' +
'<input name="message" type="text" value=""><br/><br/>' + '\n' +
'<input type="submit" value="Send"/><br/>' + '\n' +
'</form>' + '\n' +
'</body></html>' )
Or using face.py
from facepy import GraphAPI
graph = GraphAPI(access_token)
try:
graph.post(
path = 'me/feed',
message = 'Your message here'
)
except GraphAPI.OAuthError, e:
print e.message
So in the end you can get a slimmed down version like
import web
from facepy import GraphAPI
from urlparse import parse_qs
url = ('/', 'index')
app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"
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=publish_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')
For more info see
* Facebook API - User Feed: http://developers.facebook.com/docs/reference/api/user/#feed
* Publish a Facebook Photo in Python – The Basic Sauce: http://philippeharewood.com/facebook/publish-a-facebook-photo-in-python-the-basic-sauce/
* Facebook and Python – The Basic Sauce: http://philippeharewood.com/facebook/facebook-and-python-the-basic-sauce/
One possible (tested!) solution using facepy:
Create a new application or use an existing one previously created.
Generate a user access token using the Graph API explorer with the status_update extended permission for the application.
Use the user access token created in the previous step with facepy:
from facepy import GraphAPI
ACCESS_TOKEN = 'access-token-copied-from-graph-api-explorer-on-web-browser'
graph = GraphAPI(ACCESS_TOKEN)
graph.post('me/feed', message='Hello World!')
You can try this blog too. It's using fbconsole app.
The code from the blog:
from urllib import urlretrieve
import imp
urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fbconsole.py')
fb = imp.load_source('fb', '.fbconsole.py')
fb.AUTH_SCOPE = ['publish_stream']
fb.authenticate()
status = fb.graph_post("/me/feed", {"message":"Your message here"})
This is how I got it to work. You absolutely don't need to create any app for this. I'll describe how to post status updates to your profile and to a facebook page of yours.
First, to post a status update to your profile:
Go to https://developers.facebook.com/tools/explorer.
You'll see a textbox with Access Token written before it. Click on the button 'Get Access Token' beside this textbox. It will open a pop up asking you for various permissions for the access token. Basically these permissions define what all you can do through the Graph API using this token. Check the tick boxes beside all the permissions you need one of which will be updating your status.
Now go ahead and install the facepy module. Best way would be to use pip install.
After this pase the following code snippet in any .py file:
from facepy import GraphAPI
access_token = 'YOUR_GENERATED_ACCESS_TOKEN'
apiConnection = GraphAPI(access_token)
apiConnection.post(path='me/feed',
message='YOUR_DESIRED_STATUS_UPDATE_HERE')
Now execute this .py file the standard python way and check your facebook. You should see YOUR_DESIRED_STATUS_UPDATE_HERE posted to your facebook profile.
Next, to do the same thing with a facebook page of yours:
The procedure is almost exactly the same except for generating your access token.
Now you can't use the same access token to post to your facebook page. You need to generate a new one, which might be a little tricky for someone new to the Graph API. Here's what you need to do:
Go to the same developers.facebook.com/tools/explorer page.
Find a dropdown showing 'Graph API Explorer' and click on it. From the dropdown, select your page you want to post updates from. Generate a new access token for this page. The process is described here: . Do not forget to check the manage_pages permission in the extended permissions tab.
Now use this token in the same code as you used earlier and run it.
Go to your facebook page. You should YOUR_DESIRED_STATUS_UPDATE posted to your page.
Hope this helps!

Python - Facebook API - Need a working example

Ok, so i've googled around, i've found threads here on stackoverflow and i've checked the official Facebook wiki and.. and what not..
I now hope that one of you guys sits on a Facebook API sample code for Python.
This is what i've got so far and all i get is "Invalid Signature" via PyFacebook which appears to be a dead project:
from facebook import Facebook
api_key = '123456789______'
secret = '<proper secret key>'
OTK = 'XXXXX' # <-- You get this from: https://www.facebook.com/code_gen.php?v=1.0&api_key=123456789______
long_term_key = None
fb = Facebook(api_key, secret)
def generate_session_from_onetime_code(fb, code):
fb.auth_token = code
return fb.auth.getSession()
if not long_term_key:
long_term_key = generate_session_from_onetime_code(fb, OTK)['session_key']
print 'Replace None with this in the .py file for long_term_key:'
print long_term_key
fb.session_key = long_term_key
fb.uid = 000000001 # <-- Your user-id
fb.signature = api_key # <-- This doesn't work at all, MD5 of what?
#fb.validate_signature(fb) # <-- doesn't work either, prob need to pass MD5 handle?
print fb.friends.get() # <-- Generates "Invalid Signature"
"all" i want, is to retrieve my friends list for now,
if there's a better API point me in the right direction but Facebook has officially declared their own Python SDK dead and pyfacebook is almost working for me but not quite..
So, please help.
The unofficial fork of the python sdk is still working fine for me.
To retrieve your friends, generate an access token here:
https://developers.facebook.com/tools/access_token/
Limitations:
A user access token with user_friends permission is required to view
the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
Code
import facebook
token = 'your token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
friend_list = [friend['name'] for friend in friends['data']]
print friend_list

Categories