I am trying to automate a task for my company. They want me to pull the insights from their ad campaigns and put it in a CSV file. From here I will create a excel sheet that grabs this data and automates the plots that we send to our clients.
I have referenced the example code from the library and I believe where my confusion exists is in who I define 'me' to be in line 14.
token = 'temporary token from facebook API'
VOCO_id = 'AppID'
AppSecret = 'AppSecret'
me = 'facebookuserID'
AppTokensDoNotExpire = 'AppToken'
from facebook_business import FacebookSession
from facebook_business import FacebookAdsApi
from facebook_business.adobjects.campaign import Campaign as AdCampaign
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser
session = FacebookSession(VOCO_id,AppSecret,AppTokensDoNotExpire)
api = FacebookAdsApi(session)
FacebookAdsApi.set_default_api(api)
me = AdUser(fbid=VOCO_id)
####my_account = me.get_ad_account()
When I run the following with the hashtag on my_account, I get a return stating that the status is "live" for these but the value of my permissions is not compatible.
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 using gspread and a Service Account Key, Other, json file. to continually update a google spreadsheet with python 2.7. I have this running off a Raspberry Pi running the latest Raspian Jessie. my oauth and gspread should all be the latest versions available for my platform. My script runs for one hour(the max token life span),then stops working with the error message : "Invalid token: Statless token expired error" My code is as follows
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from httplib2 import Http
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
gc = gspread.authorize(credentials)
wks = gc.open('spreadsheet name')
p1 = wks.worksheet('Printer One')
def functon()
...
p1.append_row(printing)
Any Help would be greatly appreciated, Thank You.
Authorisation expires every 0.5/1 hour (I think it depends on which of the two available methods you use to connect).
I have a google sheet connected 24/7 that updates every 2 seconds. Almost always the reason for a bad read/write is an authorisation error but also Google API can throw a variety of errors at you too that normally resolve after a few seconds. Here's one of my functions to update a cell, but using your details for auth_for_worksheet. Every operation (update single cell, update a range, read a column of values) has some similar construct as a function, which always returns an authorised worksheet. It's probably not the most elegant solution but the sheet has been connected for 3 months fine with no downtime.
def auth_for_worksheet():
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
gc = gspread.authorize(credentials)
wks = gc.open('spreadsheet name')
p1 = wks.worksheet('Printer One')
return p1
def update_single_cell(worksheet, counter, message):
""" No data to return, update a single cell in column B to reflect this """
single_cell_updated = False
while not single_cell_updated:
try:
cell_location = "B" + str(counter)
worksheet.update_acell(cell_location, message)
single_cell_updated = True
except gspread.exceptions.HTTPError:
logger.critical("Could not update single cell")
time.sleep(10)
worksheet = auth_for_worksheet()
logger.info("Updated single cell")
return worksheet
if __name__ == '__main__':
# your code here, but now to update a single cell
wksheet = update_single_cell(wksheet, x, "NOT FOUND")
I am using gspread and a Service Account Key, Other, json file. to continually update a google spreadsheet with python 2.7. I have this running off a Raspberry Pi running the latest Raspian Jessie. my oauth and gspread should all be the latest versions available for my platform. My script runs for one hour(the max token life span),then stops working with the error message : "Invalid token: Statless token expired error" My code is as follows
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from httplib2 import Http
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
gc = gspread.authorize(credentials)
wks = gc.open('spreadsheet name')
p1 = wks.worksheet('Printer One')
def functon()
...
p1.append_row(printing)
Any Help would be greatly appreciated, Thank You.
Authorisation expires every 0.5/1 hour (I think it depends on which of the two available methods you use to connect).
I have a google sheet connected 24/7 that updates every 2 seconds. Almost always the reason for a bad read/write is an authorisation error but also Google API can throw a variety of errors at you too that normally resolve after a few seconds. Here's one of my functions to update a cell, but using your details for auth_for_worksheet. Every operation (update single cell, update a range, read a column of values) has some similar construct as a function, which always returns an authorised worksheet. It's probably not the most elegant solution but the sheet has been connected for 3 months fine with no downtime.
def auth_for_worksheet():
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
gc = gspread.authorize(credentials)
wks = gc.open('spreadsheet name')
p1 = wks.worksheet('Printer One')
return p1
def update_single_cell(worksheet, counter, message):
""" No data to return, update a single cell in column B to reflect this """
single_cell_updated = False
while not single_cell_updated:
try:
cell_location = "B" + str(counter)
worksheet.update_acell(cell_location, message)
single_cell_updated = True
except gspread.exceptions.HTTPError:
logger.critical("Could not update single cell")
time.sleep(10)
worksheet = auth_for_worksheet()
logger.info("Updated single cell")
return worksheet
if __name__ == '__main__':
# your code here, but now to update a single cell
wksheet = update_single_cell(wksheet, x, "NOT FOUND")
I'm new to the Facebook Ads Python SDK and am trying to create an ad that will display on mobile and desktop news feeds. Reviewing the web flow to create an ad, to show up in a feed, the ad needs to be related to a Facebook page. I manage a Facebook page, but am not sure where I need to input the FB page info.
I've reviewed the documentation and getting started examples, however the getting started is about a page post ad, so not relevant to me. I assumed "Placements" would be relevant but nothing I find there is helpful either. I also looked at Connection objects but that also seemed a dead end.
The code I've got runs and creates ads that are right column ads. I've tried adding "page_types: ['feed']" to AdSet targeting but that returns an error saying that placement is ineligible for this ad.
Could someone point me in the right direction on how to create an ad that will show up in the desktop news feed? Meat of the code is below.
`
# create campaign
campaign = AdCampaign(parent_id=config['act_account_id'])
campaign[AdCampaign.Field.name] = 'Test Campaign'
campaign[AdCampaign.Field.status] = AdCampaign.Status.paused
campaign[AdCampaign.Field.objective] = AdCampaign.Objective.website_clicks
campaign.remote_create()
# create adset
targeting = {
#'page_types': ['feed'],
'geo_locations': {
'cities': [{'key': '2532348', 'radius': 25, 'distance_unit': 'mile'}]
}
}
data = {
AdSet.Field.name: 'My Python SDK AdSet',
AdSet.Field.bid_type: AdSet.BidType.cpc,
AdSet.Field.is_autobid: True,
AdSet.Field.status: AdSet.Status.active,
AdSet.Field.lifetime_budget: 500,
AdSet.Field.end_time: '2015-06-4 23:59:59 PDT',
AdSet.Field.campaign_group_id: config['campaign_id'],
AdSet.Field.targeting: targeting,
}
adset = AdSet(parent_id=config['act_account_id'])
adset.remote_create(params=data)
# Set up creative for ad
image = AdImage(parent_id=config['act_account_id'])
image[AdImage.Field.filename] = image_filename
image.remote_create()
creative = AdCreative(parent_id=config['act_account_id'])
creative[AdCreative.Field.name] = 'sample creative'
creative[AdCreative.Field.title] = 'ad headline'
creative[AdCreative.Field.body] = 'ad text'
creative[AdCreative.Field.object_url] = 'www.http://www.misc-url.com'
creative[AdCreative.Field.image_hash] = image[AdImage.Field.hash]
creative.remote_create()
# Create your ad by referencing the ad creative.
adgroup = AdGroup(parent_id=config['act_account_id'])
adgroup[AdGroup.Field.name] = 'Testing SDK Ad'
adgroup[AdGroup.Field.campaign_id] = config['adset_id']
adgroup[AdGroup.Field.creative] = {'creative_id': str(creative_id)}
adgroup[AdGroup.Field.status] = AdGroup.Status.paused
adgroup.remote_create()
`
There is an api call to create a page post at the time of ad creation:
https://developers.facebook.com/docs/marketing-api/adcreative/v2.3#object_story_spec
See the blog post for more detailed info:
https://developers.facebook.com/ads/blog/post/2014/08/28/creative-page-post-api
I was using gdata module to access, upload, download files from google doc. I have the oauth key and secret with me. Now I want to switch to google drive api. Learning and studying a bit on google drive api , it looks like a bit different in the authentication. I also have downloaded pydrive module so as I can start things up. But I am not able to authorize my server side python code to authorize/authenticate the user using my oauth keys and access my drive. Do any one has any spare know how on how I can use pydrive to access my drive with my previous auth keys. I just need a simple way to authenticate.
For using the gdata module we use either of these credentials-
1> username & password or
2> consumer oauth key and secret key.
Since you are trying to use oauth credentials, I think you want a Domain Wide Delegated Access for Google Drive, which will help you to achieve uploading/downloading files into any user's google drive through out the domain.
For this you need to generate a new Client ID of a Service Account Type from
Developer's Console
*.p12 file will get downloaded. Note the path where you save it.
Also note the email address of your Service account. These will be use while coding.
Below is the python code where u have to carefully edit-
PATH TO SERIVE ACCOUNT PRIVATE KEY, something#developer.gserviceaccount.com, EMAIL_ID#YOURDOMAIN.COM in order to run it properly and test it.
Hope this will help!
Resource- Google Drive API
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = 'something#developer.gserviceaccount.com'
"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'PATH TO SERIVE ACCOUNT PRIVATE KEY'
def createDriveService(user_email):
"""Build and returns a Drive service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user.
Returns:
Drive service object.
"""
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope='https://www.googleapis.com/auth/drive', sub=user_email)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
drive_service=createDriveService('EMAIL_ID#YOURDOMAIN.COM')
result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = drive_service.files().list().execute()
#print files
result.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
for f in result:
print '\n\nFile: ',f.get('title')
print "\n"