Can I use the Facebook Python SDK to post a open graph action. As the python facebook SDK is now very old, how can I use that to post a open graph action - I could not find an example anywhere.
You can use the GraphAPI.request(self, path, args=None, post_args=None) function from the Python for Facebook 3rd party library (http://www.pythonforfacebook.com/). Just follow the documentation on the Facebook Developer Site to build the path, args and post_args needed to make the API call.
Using the facebook-sdk package from pip you can post an action with the put_object call
facebook.GraphAPI(token).put_object("me", "my_app:my_action", "my_object_type"="http://my_objects_url")
you can use https://github.com/zetahernandez/facebook-python-sdk
it supports doing simple request like
facebook = Facebook(
app_id='{app_id}',
app_secret='{app_secret}',
default_graph_version='v2.5',
)
facebook.set_default_access_token(access_token='{access_token}')
try:
response = facebook.get(endpoint='/me?fields=id,name')
except FacebookResponseException as e:
print e.message
else:
print 'User name: %(name)s' % {'name': response.json_body.get('id')}
or request in batch
facebook = Facebook(
app_id='{app_id}',
app_secret='{app_secret}',
)
facebook.set_default_access_token(access_token='{access_token}')
batch = {
'photo-one': facebook.request(
endpoint='/me/photos',
params={
'message': 'Foo photo.',
'source': facebook.file_to_upload('path/to/foo.jpg'),
},
),
'photo-two': facebook.request(
endpoint='/me/photos',
params={
'message': 'Bar photo.',
'source': facebook.file_to_upload('path/to/bar.jpg'),
},
),
'photo-three': facebook.request(
endpoint='/me/photos',
params={
'message': 'Other photo.',
'source': facebook.file_to_upload('path/to/other.jpg'),
},
)
}
try:
responses = facebook.send_batch_request(requests=batch)
except FacebookResponseException as e:
print e.message
Related
I'm using the campaign manager API to upload a local file into an advertiser; the script works all the way through without any errors. However, when checking the advertiser directly, there isn't a new creative asset. The changelogs also don't show any new changes. The script run (without the google authentication - OAuth 2.0, which is working to expectation on other calls):
def upload_creative_asset(
service, profile_id, advertiser_id, asset_name,path_to_asset_file,
asset_type):
"""Uploads a creative asset and returns an assetIdentifier."""
# Construct the creative asset metadata
creative_asset = {
'assetIdentifier': {
'name': asset_name,
'type': asset_type
}
}
media = MediaFileUpload(path_to_asset_file, mimetype='image/gif')
if not media.mimetype():
media = MediaFileUpload(path_to_asset_file, 'application/octet-stream')
response = service.creativeAssets().insert(
advertiserId=advertiser_id,
profileId=profile_id,
media_body=media,
body=creative_asset)
return response
path_to_creative = "automated_dcm_loading/test.gif"
upload_creative_request = upload_creative_asset(service,advertiser_id='10229XXX',profile_id='6414XXX',asset_name='test.gif',path_to_asset_file=path_to_creative,asset_type='image')
upload_creative_request.execute()
The response is:
{'kind': 'dfareporting#creativeAssetMetadata',
'assetIdentifier': {'type': 'IMAGE', 'name': 'test.gif'},
'id': '475828XXX',
'richMedia': False}
This tells me it's worked but doesn't appear in campaign manager anywhere.
UPDATE: This is only half the process to get an asset to appear in campaign manager. The next step for those who need this is to use this exact output in a creatives().insert() function to wrap the asset with a creative. Without this creative step your asset/image/video will sit on a server somewhere with nowhere for it be shown.
I am trying to integrate in gcloud oAuh2.0. This is the code snippet:
OAUTH_PROVIDERS = [
{
'name': 'google',
'whitelist': ['#gmail.com'],
'icon': 'fa-google',
'token_key': 'access_token',
'remote_app': {
'base_url': 'https://www.googleapis.com/oauth2/v2/',
'request_token_params': {
'scope': 'email profile'
},
'request_token_url': None,
'access_token_url': 'https://accounts.google.com/o/oauth2/token',
'authorize_url': 'https://accounts.google.com/o/oauth2/auth',
'consumer_key': 'myKeyID',
'consumer_secret': 'MySecret'
}
}
]
I am able to access the authorization page and successfully sign in as well, but after the signing it redirects me to the page which shows invalid login details (Even though Google has validated it).
Here's what I receive:
What possibly could be the error?
Solved the error, I was trying to register with a pre-registered email, sorry for the confusion!
I'm sorry but English is not my first language and my English is broken.
I'm trying to download my 3000+ pictures using Google Photos API with Python.
First I downloaded MediaItems list with this code.
from pathlib import Path
from requests_oauthlib import OAuth2Session
import json
api_url = "https://photoslibrary.googleapis.com/v1/mediaItems"
scope = ["https://www.googleapis.com/auth/photoslibrary.readonly"]
def save_token(token):
token = {
"access_token": token.get("access_token"),
"refresh_token": token.get("refresh_token"),
"token_type": token.get("token_type"),
"expires_in": token.get("expires_in")
}
Path("token.json").write_text(json.dumps(token))
def load_token():
token = {
"access_token": "",
"refresh_token": "",
"token_type": "",
"expires_in": "-30",
}
path = Path("token.json")
if path.exists():
token = json.loads(path.read_text())
return token
def login():
auth_info = json.loads(Path("credentials.json").read_text()).get("installed", None)
assert auth_info is not None
token = load_token()
extras = {
"client_id": auth_info.get("client_id"),
"client_secret": auth_info.get("client_secret"),
}
google = OAuth2Session(
auth_info.get("client_id"),
scope=scope,
token=token,
auto_refresh_kwargs=extras,
token_updater=save_token,
auto_refresh_url=auth_info.get("token_uri"),
redirect_uri=auth_info.get("redirect_uris")[0]
)
if not google.authorized:
authorization_url, state = google.authorization_url(
auth_info.get("auth_uri"),
access_type="offline",
prompt="select_account"
)
print("Access {} and paste code.".format(authorization_url))
access_code = input(">>> ")
google.fetch_token(
auth_info.get("token_uri"),
client_secret=auth_info.get("client_secret"),
code=access_code
)
assert google.authorized
save_token(google.token)
return google
def test():
google = login()
response = google.get(api_url)
print(response.text)
if __name__ == "__main__":
test()
This code worked without problems and I downloaded about 30 json files (contains 3000 pictures information) with nextPageToken.
After that, I tried to download these pictures by this code.
The photo_info_list variable contains all MediaItems.
photo_download_format = "{base}=w{width}-h{height}"
def download_photos(photo_info_list):
google = login()
for photo_info in photo_info_list:
photo_id = photo_info.get("id", "dummy_id")
base_url = photo_info.get("baseUrl")
metadata = photo_info.get("mediaMetadata")
filename = photo_info.get("filename")
download_url = photo_download_format.format(
base=base_url,
width=metadata["width"],
height=metadata["height"]
)
response = google.get(download_url)
# save_picture
This code worked well for first 162 pictures (about 270MB) but then I got 403 forbidden error.
I deleted token and tried login procedures again, created another credentials but got the same errors.
Does anyone know what is the problem?
Any suggestion or information are really appreciate. Thank you!
baseUrls expire in 60 minutes after acquisition. Per the documentation for Google Photos APIs
You also shouldn't store baseUrls, which expire after approximately 60 minutes.
The most likely explanation is that your baseUrl has expired in the middle of downloading.
I'm trying to make a chatbot in Hangouts Chat.
I'm referring this documentation to implement account linking.
Its default version is working but when I try to generate access_token and refresh token using Token Endpoint. It gives
{
"error": "invalid_grant",
"error_description": "Bad Request"
}
Here is my callback function code.
def on_oauth2_callback():
"""Handles the OAuth callback."""
print("IN CALLBACK ", flask.request.args)
oauth2_callback_args = OAuth2CallbackCipher.decrypt(
flask.request.args['state'])
user_name, redirect_url = (
oauth2_callback_args['user_name'],
oauth2_callback_args['redirect_url'])
oauth2_flow = flow.Flow.from_client_secrets_file(
OAUTH2_CLIENT_SECRET_FILE,
scopes=PEOPLE_API_SCOPES,
redirect_uri=flask.url_for('auth.on_oauth2_callback', _external=True),
state=flask.request.args['state'])
oauth2_flow.fetch_token(authorization_response=flask.request.url)
print("REDIRECT URL ", redirect_url)
auth_code = request.args.get('code')
data = {'code': auth_code,
'client_id': "xxxxxxxxxxxxxxx.apps.googleusercontent.com",
'client_secret': "xxxxxxxxxxxx",
'redirect_uri': redirect_url,
'grant_type': 'authorization_code'}
print("%^" * 10, json.dumps(data))
r = requests.post('https://www.googleapis.com/oauth2/v3/token', data=json.dumps(data))
print("%" * 10, r.text)
return flask.redirect(redirect_url)
What am I doing wrong? And if there's another way kindly enlighten me.
Once you call oauth2_flow.fetch_token(authorization_response=flask.request.url) you just exchanged the authorization code in that response for an access token.
So you don't need to call the token endpoint, you just need to get credentials:
credentials = oauth2_flow.credentials
And finally get token and refresh_token from credentials.token and credentials.refresh_token.
Take a look on this documentation.
I hope it's clear!
i am trying to post a message into my wall using facebook graph api. I have my access_token. I have tried in my browser using following URL.
https://graph.facebook.com/me/feed?message="Hii friends"&access_token=xxxxxxxxxx
But message is not posted. So i couldn't solve this problem. Finally i want to use this URL inside urllib2.urlopen()
Please Help
I recently got posting to facebook to work like so:
import requests
face_token = 'your_token'
post = 'Your Post wowzers'
post.replace(' ', '+')
requests.post("https://graph.facebook.com/me/feed/?message=" + post + "&access_token=" + face_token)
You can do it with the graph api like this:
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()
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
This will most likely not work in the browser. Check out some other threads on stackoverflow for this:
How do I update FB Status using Python & GraphAPI?
Posting to Facebook wall
Also, check out google, there are many tutorials and frameworks for using the Facebook API with Python.