Posts tagged with python

I'm working with the Google Ads API to retrieve campaign simulations for a specific date range. So far whenever I try to filter for a date range outside of the "current simulation" I receive no results. The "current simulation" is the default simulation that shows on the platforms websites simulation tool.

Here's my current code snippet (relevant portion):

try:     # Get the GoogleAdsService     googleads_service = client.get_service("GoogleAdsService")     # Construct the query     query = f"""         SELECT             campaign_simulation.campaign_id,             campaign_simulation.type,             campaign_simulation.start_date,             campaign_simulation.end_date,             campaign_simulation.budget_point_list.points,             campaign_simulation.cpc_bid_point_list.points,             campaign_simulation.target_cpa_point_list.points,             campaign_simulation.target_impression_share_point_list.points,             campaign_simulation.target_roas_point_list.points         FROM             campaign_simulation         WHERE             campaign_simulation.campaign_id = {campaign_id}      """     # Execute the search request     response = googleads_service.search_stream(customer_id=customer_id, query=query) 

I've attempted filtering based on campaign_simulation.start_date and campaign_simulation.end_date within the WHERE clause, but it only retrieves the current simulation. On the platforms website you can change the range to be any 7 day period after the current date, and this is what I expect to be able to do from the API as well.

New reel does appear in fan page's Reels feed but it's invisible to users (i used another account to display the same feed and new reel is not there).

My "Page" perms:

publish_video pages_show_list pages_read_engagement pages_manage_posts 

Using this Python code to publish Facebook reel:

import os import requests from os.path import isfile page_id= 'your business page id' api_version= 'v20.0' page_access_token= 'your_page_token' def initialize_upload():     url = f"https://graph.facebook.com/{api_version}/{page_id}/video_reels"     payload = {         'upload_phase': 'start',         'access_token': page_access_token     }     r = requests.post(url, data=payload)     json = r.json()     if r.status_code == 200:         video_id = r.json()['video_id']     else:         raise Exception(json)      return video_id def process_upload(video_id, file_size, file_data):       url = f'https://rupload.facebook.com/video-upload/{api_version}/{video_id}'     payload = {         'Authorization': 'OAuth ' + page_access_token,         'offset': '0',         'file_size': str(file_size),         'Content-Type': 'application/octet-stream'     }     r = requests.post(url, data=file_data, headers=payload)     json = r.json()     if r.status_code != 200:         raise Exception(json) def publish(video_id, description, publish_time=None):     url = f"https://graph.facebook.com/{api_version}/{page_id}/video_reels"     payload = {         'access_token': page_access_token,         'video_id': video_id,         'upload_phase': 'finish',         'description': description,     }     if publish_time:         payload['video_state'] = 'SCHEDULED'         payload['scheduled_publish_time'] = publish_time     else:         payload['video_state'] = 'PUBLISHED'     r = requests.post(url, data=payload)     json = r.json()     if r.status_code != 200:         raise Exception(json) if __name__ == '__main__':     video_id = initialize_upload()     print(video_id)          mp4_path= r"C:\test\Facebook.mp4"              if isfile(mp4_path):         file_size = os.path.getsize(mp4_path)         file_data= open(mp4_path, 'rb')         process_upload(video_id, file_size, file_data)         publish(video_id,  '#description')     else:         print('File not found') 

Metadata (those views are mine):

{'comments': {'data': [],               'summary': {'can_comment': True,                           'order': 'chronological',                           'total_count': 0}},  'created_time': '2024-08-13T16:22:02+0000',  'description': '#test',  'from': {'id': '***', 'name': 'Test'},  'id': '***',  'is_crossposting_eligible': True,  'likes': {'data': [],            'summary': {'can_like': True, 'has_liked': False, 'total_count': 0}},  'permalink_url': '/reel/***/',  'privacy': {'allow': '',              'deny': '',              'description': 'Public',              'friends': '',              'networks': '',              'value': 'EVERYONE'},  'status': {'copyright_check_status': {'matches_found': False,                                        'status': 'complete'},             'processing_phase': {'status': 'complete'},             'publishing_phase': {'publish_status': 'published',                                  'publish_time': '2024-08-13T17:33:12+0000',                                  'status': 'complete'},             'uploading_phase': {'bytes_transferred': 13671054,                                 'status': 'complete'},             'video_status': 'ready'},  'views': 45} 

Any idea why is it private?

I have a Python application that uses a Facebook Business library. Therefore, I need to use a token provided by Facebook to access my insights and manipulate them.

However, this token has an expiration date, which is long, but I wanted to know if there is a way to update this token automatically within my application, so that it doesn't stop running.

I am getting the following error from the below code and I can't seem to work out what exactly i am not doing right, I feel as though I am specifying the correct account IDs but it isn't being accepted.

import hashlib import hmac import sys sys.path.append('./.venv/lib/python3.12/site-packages') # Replace this with the place you installed facebookads using pip sys.path.append('./.venv/lib/python3.12/site-packages/facebook_business-3.0.0-py2.7.egg-info') # same as above from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount my_app_id = '995427558947840' my_app_secret = '04765ed9281612e2aa8723935a7e4ad2' my_access_token = 'EAAVuWk8drdWkBOw5gCusNtZCxbwej5AIQdBsVhug4SZCneZCU95y2LgIyd5ulE8JC2KMfoyVYdxF5CZBrvyZCp6vYJzhApftZBp9Y4Lt0TtkRcOsTJmOE2AZBGbrbJcpn6ZAqXzyqTloLqrFSohRb6gBTz5KVI1m0VU7qLTCuZBMvNlTZBw5CiwbBQZBLGYh98rht0q3N7gPdJgunZCrVZAjWFeZCsYc2ZCvRCAZD' app_secretproof = hmac.new(bytes(my_access_token,'utf-8'),bytes(my_app_secret,'utf-8'),hashlib.sha256 ).hexdigest() FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token, app_secretproof) account = AdAccount('act_229199089180260') campaigns = account.get_campaigns() print(campaigns) 

Account ID provided in FacebookAdsApi.set_default_account_id expects a string that begins with 'act_'

I expect this code to bring me back all the campaigns in my given Facebook Ad account

I'm using Airbyte to extract data from Facebook Marketing. I need to add a custom field to the API requests to better manage the data extraction process. The main problem is that the returned campaigns data does not include a way to map the adsets to the campaigns, so i want to add the "adsets" field to the campaigns request to then map them.

I have reviewed Airbyte documentation and forums but couldn't find clear instructions. I have also tried to use the Custom Insights but no luck.