def update_facebook(app_id, app_secret, access_token, options): # pragma: no cover """ Update status of ads on Facebook if different from respective suggestion; return dataframe with updated ads """ api = FacebookAdsApi.init(app_id, app_secret, access_token) updated = [] # Determine number of required batches since # Facebook only allows 50 API calls per batch num_options = len(options.index) batch_size = 50 batches = int(num_options / batch_size) + 1 # Split options into batches and loop through those i = 0 for _ in range(batches): option_batch = options.loc[i:i + batch_size, :] i += batch_size update_batch = api.new_batch() # Loop through options within batch, compare current and suggested # ad status and update if changed for _, row in option_batch.iterrows(): ad_id = str(row['ad_id']) ad = Ad(ad_id) ad.api_get(fields=[Ad.Field.status]) old_status = ad[Ad.Field.status] new_status = row['ad_status'] if old_status != new_status: ad[Ad.Field.status] = new_status updated.append([ad_id, old_status + ' -> ' + new_status]) ad.api_update(batch=update_batch, fields=[], params={Ad.Field.status: new_status}) update_batch.execute() return pd.DataFrame(updated, columns=['ad_id', 'updated'])
def get_ad_data_or_sleep(self, ad): """ Get needed data for ads or sleep :param ad: :return: """ while True: ad_data = {'ad_id': ad} try: ad = Ad(ad) creative = AdCreative( ad.api_get(fields=[Ad.Field.creative])['creative']['id']) fields = [ AdCreative.Field.call_to_action_type, AdCreative.Field.object_story_spec ] creative.api_get(fields=fields) creative = dict(creative) try: call_to_action = creative['object_story_spec'][ 'video_data']['call_to_action'] try: print(creative['object_story_spec']['photo_data']) except KeyError: pass ad_data['website_url'] = call_to_action['value']['link'] ad_data['call_to_action_type'] = call_to_action['type'] ad_data['headline'] = creative['object_story_spec'][ 'video_data']['title'] ad_data['description'] = creative['object_story_spec'][ 'video_data']['message'] video = AdVideo(creative['object_story_spec']['video_data'] ['video_id']) ad_data['video_name'] = video.api_get( fields=[AdVideo.Field.title])['title'] except KeyError: pass self.current_ads.append(ad_data) except FacebookRequestError as e: print(type(e.api_error_code())) if e.api_error_code() == 803: break print('Sleeping right now for ads') time.sleep(600) else: break return ad_data
def _extend_record(self, ad: Ad, fields: Sequence[str]): return ad.api_get(fields=fields).export_all_data()