Lingua
Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
In questo esempio viene illustrato come associare parole chiave ed elenchi di parole chiave negative a una campagna.
Consiglio
Usare il selettore della lingua nell'intestazione della documentazione per scegliere C#, Java, PHP o Python.
Per ottenere i token di accesso e aggiornamento per l'utente di Microsoft Advertising ed effettuare la prima chiamata di servizio utilizzando l'API di Bing Ads, vedere la Guida introduttiva . Ti consigliamo di esaminare la guida introduttiva e le procedure dettagliate per il tuo linguaggio preferito, ad esempio C#, Java, PHP e Python.
I file di supporto per gli esempi di C#, Java, PHP e Python sono disponibili in GitHub. Puoi clonare ogni repository o riutilizzare gli snippet secondo necessità.
using System;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;
namespace BingAdsExamplesLibrary.V13
{
/// <summary>
/// How to associate negative keywords and negative keyword lists with a campaign.
/// </summary>
public class NegativeKeywords : ExampleBase
{
public override string Description
{
get { return "Negative Keywords | Campaign Management V13"; }
}
public async override Task RunAsync(AuthorizationData authorizationData)
{
try
{
ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;
CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData: authorizationData,
environment: environment);
// Add a campaign that will later be associated with negative keywords.
var campaigns = new[]{
new Campaign
{
BudgetType = BudgetLimitType.DailyBudgetStandard,
DailyBudget = 50,
CampaignType = CampaignType.Search,
Languages = new string[] { "All" },
Name = "Everyone's Shoes " + DateTime.UtcNow,
TimeZone = "PacificTimeUSCanadaTijuana",
},
};
OutputStatusMessage("-----\nAddCampaigns:");
AddCampaignsResponse addCampaignsResponse = await CampaignManagementExampleHelper.AddCampaignsAsync(
accountId: authorizationData.AccountId,
campaigns: campaigns);
long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
OutputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(campaignIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(campaignErrors);
long campaignId = (long)campaignIds[0];
// You may choose to associate an exclusive set of negative keywords to an individual campaign
// or ad group. An exclusive set of negative keywords cannot be shared with other campaigns
// or ad groups. This example only associates negative keywords with a campaign.
var entityNegativeKeywords = new[]
{
new EntityNegativeKeyword
{
EntityId = campaignId,
EntityType = "Campaign",
NegativeKeywords = new[]
{
new NegativeKeyword
{
MatchType = MatchType.Phrase,
Text = "auto"
},
new NegativeKeyword
{
MatchType = MatchType.Exact,
Text = "auto"
},
}
}
};
OutputStatusMessage("-----\nAddNegativeKeywordsToEntities:");
AddNegativeKeywordsToEntitiesResponse addNegativeKeywordsToEntitiesResponse =
await CampaignManagementExampleHelper.AddNegativeKeywordsToEntitiesAsync(
entityNegativeKeywords: entityNegativeKeywords);
OutputStatusMessage("Added an exclusive set of negative keywords to the Campaign");
OutputStatusMessage("NegativeKeywordIds:");
CampaignManagementExampleHelper.OutputArrayOfIdCollection(addNegativeKeywordsToEntitiesResponse.NegativeKeywordIds);
OutputStatusMessage("NestedPartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(addNegativeKeywordsToEntitiesResponse.NestedPartialErrors);
// If you attempt to delete a negative keyword without an identifier the operation will return
// partial errors corresponding to the index of the negative keyword that was not deleted.
OutputStatusMessage("-----\nDeleteNegativeKeywordsFromEntities:");
BatchErrorCollection[] nestedPartialErrors = (await CampaignManagementExampleHelper.DeleteNegativeKeywordsFromEntitiesAsync(
entityNegativeKeywords: entityNegativeKeywords)).NestedPartialErrors.ToArray();
OutputStatusMessage("Attempt to DeleteNegativeKeywordsFromEntities without NegativeKeyword identifier partially fails by design.");
CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(nestedPartialErrors);
// Negative keywords can also be added and deleted from a shared negative keyword list.
// The negative keyword list can be shared or associated with multiple campaigns.
// NegativeKeywordList inherits from SharedList which inherits from SharedEntity.
var negativeKeywordList = new NegativeKeywordList
{
Name = "My Negative Keyword List" + DateTime.UtcNow,
Type = "NegativeKeywordList"
};
SharedListItem[] negativeKeywords =
{
new NegativeKeyword
{
Text = "car",
Type = "NegativeKeyword",
MatchType = MatchType.Exact
},
new NegativeKeyword
{
Text = "car",
Type = "NegativeKeyword",
MatchType = MatchType.Phrase
}
};
// Add a negative keyword list that can be shared.
OutputStatusMessage("-----\nAddSharedEntity:");
var addSharedEntityResponse = await CampaignManagementExampleHelper.AddSharedEntityAsync(
sharedEntity: negativeKeywordList,
listItems: negativeKeywords,
sharedEntityScope: EntityScope.Account);
var sharedEntityId = addSharedEntityResponse.SharedEntityId;
long[] listItemIds = addSharedEntityResponse.ListItemIds.ToArray();
OutputStatusMessage(string.Format(
"NegativeKeywordList added to account library and assigned identifer {0}",
sharedEntityId)
);
// Negative keywords were added to the negative keyword list above. You can associate the
// shared list of negative keywords with a campaign with or without negative keywords.
// Shared negative keyword lists cannot be associated with an ad group. An ad group can only
// be assigned an exclusive set of negative keywords.
var associations = new[]
{
new SharedEntityAssociation
{
EntityId = campaignId,
EntityType = "Campaign",
SharedEntityId = sharedEntityId,
SharedEntityType = "NegativeKeywordList"
}
};
OutputStatusMessage("-----\nSetSharedEntityAssociations:");
var partialErrors = (await CampaignManagementExampleHelper.SetSharedEntityAssociationsAsync(
associations: associations,
sharedEntityScope: EntityScope.Account)).PartialErrors;
OutputStatusMessage(string.Format(
"Associated CampaignId {0} with Negative Keyword List Id {1}.",
campaignId, sharedEntityId)
);
// Delete the campaign and everything it contains e.g., ad groups and ads.
OutputStatusMessage("-----\nDeleteCampaigns:");
await CampaignManagementExampleHelper.DeleteCampaignsAsync(
accountId: authorizationData.AccountId,
campaignIds: new[] { (long)campaignIds[0] });
OutputStatusMessage(string.Format("Deleted Campaign Id {0}", campaignIds[0]));
// DeleteCampaigns does not delete the negative keyword list from the account's library.
// Call the DeleteSharedEntities operation to delete the negative keyword list.
OutputStatusMessage("-----\nDeleteSharedEntities:");
partialErrors = (await CampaignManagementExampleHelper.DeleteSharedEntitiesAsync(
sharedEntities: new SharedEntity[] { new NegativeKeywordList { Id = sharedEntityId } },
sharedEntityScope: EntityScope.Account))?.PartialErrors;
OutputStatusMessage(string.Format("Deleted Negative Keyword List Id {0}", sharedEntityId));
}
// Catch authentication exceptions
catch (OAuthTokenRequestException ex)
{
OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
}
// Catch Campaign Management service exceptions
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.EditorialApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (Exception ex)
{
OutputStatusMessage(ex.Message);
}
}
}
}
package com.microsoft.bingads.examples.v13;
import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
public class NegativeKeywords extends ExampleBase {
public static void main(java.lang.String[] args) {
try
{
authorizationData = getAuthorizationData();
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData,
API_ENVIRONMENT,
ICampaignManagementService.class);
// Add a campaign that will later be associated with negative keywords.
ArrayOfCampaign campaigns = new ArrayOfCampaign();
Campaign campaign = new Campaign();
campaign.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
campaign.setDailyBudget(50.00);
ArrayOfstring languages = new ArrayOfstring();
languages.getStrings().add("All");
campaign.setLanguages(languages);
campaign.setName("Everyone's Shoes " + System.currentTimeMillis());
campaign.setTimeZone("PacificTimeUSCanadaTijuana");
campaigns.getCampaigns().add(campaign);
outputStatusMessage("-----\nAddCampaigns:");
AddCampaignsResponse addCampaignsResponse = CampaignManagementExampleHelper.addCampaigns(
authorizationData.getAccountId(),
campaigns);
ArrayOfNullableOflong nullableCampaignIds = addCampaignsResponse.getCampaignIds();
ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
outputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(nullableCampaignIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(campaignErrors);
ArrayOflong campaignIds = new ArrayOflong();
campaignIds.getLongs().add(nullableCampaignIds.getLongs().get(0));
// You may choose to associate an exclusive set of negative keywords to an individual campaign
// or ad group. An exclusive set of negative keywords cannot be shared with other campaigns
// or ad groups. This example only associates negative keywords with a campaign.
ArrayOfNegativeKeyword negativeKeywords = new ArrayOfNegativeKeyword();
NegativeKeyword autoPhrase = new NegativeKeyword();
autoPhrase.setMatchType(MatchType.PHRASE);
autoPhrase.setText("auto");
negativeKeywords.getNegativeKeywords().add(autoPhrase);
NegativeKeyword autoExact = new NegativeKeyword();
autoExact.setMatchType(MatchType.EXACT);
autoExact.setText("auto");
negativeKeywords.getNegativeKeywords().add(autoExact);
ArrayOfEntityNegativeKeyword entityNegativeKeywords = new ArrayOfEntityNegativeKeyword();
EntityNegativeKeyword entityNegativeKeyword = new EntityNegativeKeyword();
entityNegativeKeyword.setEntityId(nullableCampaignIds.getLongs().get(0));
entityNegativeKeyword.setEntityType("Campaign");
entityNegativeKeyword.setNegativeKeywords(negativeKeywords);
entityNegativeKeywords.getEntityNegativeKeywords().add(entityNegativeKeyword);
outputStatusMessage("-----\nAddNegativeKeywordsToEntities:");
AddNegativeKeywordsToEntitiesResponse addNegativeKeywordsToEntitiesResponse = CampaignManagementExampleHelper.addNegativeKeywordsToEntities(
entityNegativeKeywords);
outputStatusMessage("Added an exclusive set of negative keywords to the Campaign.");
outputStatusMessage("NegativeKeywordIds:");
CampaignManagementExampleHelper.outputArrayOfIdCollection(addNegativeKeywordsToEntitiesResponse.getNegativeKeywordIds());
outputStatusMessage("NestedPartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(addNegativeKeywordsToEntitiesResponse.getNestedPartialErrors());
// If you attempt to delete a negative keyword without an identifier the operation will return
// partial errors corresponding to the index of the negative keyword that was not deleted.
outputStatusMessage("-----\nDeleteNegativeKeywordsFromEntities:");
ArrayOfBatchErrorCollection nestedPartialErrors = CampaignManagementExampleHelper.deleteNegativeKeywordsFromEntities(
entityNegativeKeywords).getNestedPartialErrors();
outputStatusMessage("Attempt to DeleteNegativeKeywordsFromEntities without NegativeKeyword identifier partially fails by design.");
CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(nestedPartialErrors);
// Negative keywords can also be added and deleted from a shared negative keyword list.
// The negative keyword list can be shared or associated with multiple campaigns.
// NegativeKeywordList inherits from SharedList which inherits from SharedEntity.
NegativeKeywordList negativeKeywordList = new NegativeKeywordList();
negativeKeywordList.setName("My Negative Keyword List " + System.currentTimeMillis());
negativeKeywordList.setType("NegativeKeywordList");
ArrayOfSharedListItem sharedListItems = new ArrayOfSharedListItem();
NegativeKeyword carExact = new NegativeKeyword();
carExact.setText("car");
carExact.setType("NegativeKeyword");
carExact.setMatchType(MatchType.EXACT);
sharedListItems.getSharedListItems().add(carExact);
NegativeKeyword carPhrase = new NegativeKeyword();
carPhrase.setText("car");
carPhrase.setType("NegativeKeyword");
carPhrase.setMatchType(MatchType.PHRASE);
sharedListItems.getSharedListItems().add(carPhrase);
// Add a negative keyword list that can be shared.
outputStatusMessage("-----\nAddSharedEntity:");
AddSharedEntityResponse addSharedEntityResponse = CampaignManagementExampleHelper.addSharedEntity(
negativeKeywordList,
sharedListItems,
null);
long sharedEntityId = addSharedEntityResponse.getSharedEntityId();
ArrayOflong listItemIds = addSharedEntityResponse.getListItemIds();
outputStatusMessage(String.format(
"NegativeKeywordList added to account library and assigned identifer {0}",
sharedEntityId)
);
// Negative keywords were added to the negative keyword list above. You can associate the
// shared list of negative keywords with a campaign with or without negative keywords.
// Shared negative keyword lists cannot be associated with an ad group. An ad group can only
// be assigned an exclusive set of negative keywords.
ArrayOfSharedEntityAssociation associations = new ArrayOfSharedEntityAssociation();
SharedEntityAssociation association = new SharedEntityAssociation();
association.setEntityId(nullableCampaignIds.getLongs().get(0));
association.setEntityType("Campaign");
association.setSharedEntityId(sharedEntityId);
association.setSharedEntityType("NegativeKeywordList");
associations.getSharedEntityAssociations().add(association);
outputStatusMessage("-----\nSetSharedEntityAssociations:");
ArrayOfBatchError partialErrors = CampaignManagementExampleHelper.setSharedEntityAssociations(
associations,
null).getPartialErrors();
outputStatusMessage(String.format(
"Associated CampaignId %d with Negative Keyword List Id %d.",
nullableCampaignIds.getLongs().get(0), sharedEntityId)
);
// Delete the campaign and everything it contains e.g., ad groups and ads.
outputStatusMessage("-----\nDeleteCampaigns:");
ArrayOflong deleteCampaignIds = new ArrayOflong();
deleteCampaignIds.getLongs().add(nullableCampaignIds.getLongs().get(0));
CampaignManagementExampleHelper.deleteCampaigns(
authorizationData.getAccountId(),
deleteCampaignIds);
outputStatusMessage(String.format("Deleted CampaignId %d", deleteCampaignIds.getLongs().get(0)));
// DeleteCampaigns does not delete the negative keyword list from the account's library.
// Call the DeleteSharedEntities operation to delete the negative keyword list.
outputStatusMessage("-----\nDeleteSharedEntities:");
ArrayOfSharedEntity sharedEntities = new ArrayOfSharedEntity();
negativeKeywordList.setId(sharedEntityId);
sharedEntities.getSharedEntities().add(negativeKeywordList);
partialErrors = CampaignManagementExampleHelper.deleteSharedEntities(
sharedEntities,
null).getPartialErrors();
outputStatusMessage(String.format("Deleted Negative Keyword List Id %d", sharedEntityId));
}
catch (Exception ex) {
String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
outputStatusMessage(faultXml);
String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
outputStatusMessage(message);
}
}
}
<?php
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AddNegativeKeywordsToEntitiesRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AddSharedEntityRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\BudgetLimitType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Campaign;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\DeleteNegativeKeywordsFromEntitiesRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\DeleteSharedEntitiesRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\EntityNegativeKeyword;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\EntityType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\MatchType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\NegativeKeyword;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\NegativeKeywordList;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\SetSharedEntityAssociationsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\SharedEntityAssociation;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;
class NegativeKeywordsTest extends RestApiTestBase
{
/**
* @throws Exception
*/
public function testAddCampaigns()
{
print("-----\r\nAdding Campaigns:\r\n");
$campaign = (new Campaign())
->setName("Women's Shoes ".self::generateRandomAlphaNumeric())
->setBudgetType(BudgetLimitType::DAILY_BUDGET_STANDARD)
->setDailyBudget(50.00)
->setLanguages(['All'])
->setTimeZone('PacificTimeUSCanadaTijuana');
return self::addCampaignsRequest([$campaign]);
}
/**
* @depends testAddCampaigns
* @throws Exception
*/
public function testAddNegativeKeywordsToEntities($campaignIds)
{
// You may choose to associate an exclusive set of negative keywords to an individual campaign
// or ad group. An exclusive set of negative keywords cannot be shared with other campaigns
// or ad groups. This sample only associates negative keywords with a campaign.
print("-----\r\nAdding Negative Keywords to Campaign:\r\n");
$negativeKeyword = (new NegativeKeyword())
->setMatchType(MatchType::PHRASE)
->setText("auto");
$entityNegativeKeyword = (new EntityNegativeKeyword())
->setEntityId($campaignIds[0])
->setEntityType(EntityType::CAMPAIGN)
->setNegativeKeywords([$negativeKeyword]);
$request = new AddNegativeKeywordsToEntitiesRequest([
'EntityNegativeKeywords' => [$entityNegativeKeyword]
]);
$response = self::$campaignManagementServiceApi->addNegativeKeywordsToEntities($request);
print("EntityNegativeKeywords:\r\n");
print_r($response->getNegativeKeywordIds());
self::assertEmpty($response->getNestedPartialErrors());
// If you attempt to delete a negative keyword without an identifier the operation will return
// partial errors corresponding to the index of the negative keyword that was not deleted.
$request = new DeleteNegativeKeywordsFromEntitiesRequest([
'EntityNegativeKeywords' => [$entityNegativeKeyword]
]);
$response = self::$campaignManagementServiceApi->deleteNegativeKeywordsFromEntities($request);
self::assertNotEmpty($response->getNestedPartialErrors());
}
/**
* @depends testAddNegativeKeywordsToEntities
* @throws Exception
*/
public function testAddSharedNegativeKeywordList()
{
// Negative keywords can also be added and deleted from a shared negative keyword list.
// The negative keyword list can be shared or associated with multiple campaigns.
// NegativeKeywordList inherits from SharedList which inherits from SharedEntity.
print("-----\r\nAdding Shared Negative Keyword List:\r\n");
$negativeKeywordList = (new NegativeKeywordList())
->setName("My Negative Keyword List ".self::generateRandomAlphaNumeric())
->setType("NegativeKeywordList");
$negativeKeywords = [
(new NegativeKeyword())
->setText("car")
->setType("NegativeKeyword")
->setMatchType(MatchType::EXACT),
(new NegativeKeyword())
->setText("car")
->setType("NegativeKeyword")
->setMatchType(MatchType::PHRASE)
];
$request = new AddSharedEntityRequest(
[
'SharedEntity' => $negativeKeywordList,
'NegativeKeywords' => $negativeKeywords
]
);
$response = self::$campaignManagementServiceApi->addSharedEntity($request);
$sharedEntityId = $response->getSharedEntityId();
print("Shared Entity ID: ".$sharedEntityId."\r\n");
self::assertNotEmpty($sharedEntityId);
print("PartialErrors:\r\n");
print_r($response->getPartialErrors());
self::assertEmpty($response->getPartialErrors());
return $sharedEntityId;
}
/**
* @depends testAddCampaigns
* @depends testAddSharedNegativeKeywordList
* @throws Exception
*/
public function testAssociateSharedNegativeKeywordList($campaignIds, $sharedEntityId)
{
// Negative keywords were added to the negative keyword list above. You can associate the
// shared list of negative keywords with a campaign with or without negative keywords.
// Shared negative keyword lists cannot be associated with an ad group. An ad group can only
// be assigned an exclusive set of negative keywords.
print("-----\r\nAssociating Shared Negative Keyword List with Campaign:\r\n");
$association = (new SharedEntityAssociation())
->setEntityId($campaignIds[0])
->setEntityType(EntityType::CAMPAIGN)
->setSharedEntityId($sharedEntityId)
->setSharedEntityType("NegativeKeywordList");
$request = new SetSharedEntityAssociationsRequest([
'Associations' => [$association]
]);
$response = self::$campaignManagementServiceApi->setSharedEntityAssociations($request);
print("PartialErrors:\r\n");
print_r($response->getPartialErrors());
self::assertEmpty($response->getPartialErrors());
return $campaignIds;
}
/**
* @depends testAssociateSharedNegativeKeywordList
* @throws Exception
*/
public function testDeleteCampaigns($campaignIds)
{
self::deleteCampaignsRequest($campaignIds);
}
/**
* @depends testAddSharedNegativeKeywordList
* @depends testDeleteCampaigns
* @throws Exception
*/
public function testDeleteSharedNegativeKeywordList($sharedEntityId)
{
// DeleteCampaigns does not delete the negative keyword list from the account's library.
// Call the DeleteSharedEntities operation to delete the shared entities.
print("-----\r\nDeleting Shared Negative Keyword List:\r\n");
$negativeKeywordList = (new NegativeKeywordList())
->setId($sharedEntityId)
->setType("NegativeKeywordList");
$request = new DeleteSharedEntitiesRequest([
'SharedEntities' => [$negativeKeywordList]
]);
$response = self::$campaignManagementServiceApi->deleteSharedEntities($request);
print("Deleted Shared Entity ID: ".$sharedEntityId."\r\n");
self::assertNotEmpty($sharedEntityId);
print("PartialErrors:\r\n");
print_r($response->getPartialErrors());
self::assertEmpty($response->getPartialErrors());
}
}
from auth_helper import *
from openapi_client.models.campaign import *
from time import strftime, gmtime
def main(authorization_data):
try:
# Add a campaign that will later be associated with negative keywords.
campaign = Campaign(
budget_type=BudgetLimitType.DAILYBUDGETSTANDARD,
daily_budget=50,
languages=['All'],
name="Women's Shoes " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()),
time_zone='PacificTimeUSCanadaTijuana'
)
campaigns = [campaign]
add_campaigns_request = AddCampaignsRequest(
account_id=authorization_data.account_id,
campaigns=campaigns
)
add_campaigns_response = campaign_service.add_campaigns(
add_campaigns_request=add_campaigns_request
)
campaign_ids = add_campaigns_response.CampaignIds
# Create exclusive negative keywords for the campaign
negative_keywords = [
NegativeKeyword(
match_type=MatchType.EXACT,
text="auto"
),
NegativeKeyword(
match_type=MatchType.PHRASE,
text="auto"
)
]
entity_negative_keyword = EntityNegativeKeyword(
entity_id=campaign_ids[0],
entity_type="Campaign",
negative_keywords=negative_keywords
)
entity_negative_keywords = [entity_negative_keyword]
add_negative_keywords_request = AddNegativeKeywordsToEntitiesRequest(
entity_negative_keywords=entity_negative_keywords
)
add_negative_keywords_response = campaign_service.add_negative_keywords_to_entities(
add_negative_keywords_to_entities_request=add_negative_keywords_request
)
# Delete negative keywords (demonstrates partial failure by design)
delete_negative_keywords_request = DeleteNegativeKeywordsFromEntitiesRequest(
entity_negative_keywords=entity_negative_keywords
)
nested_partial_errors = campaign_service.delete_negative_keywords_from_entities(
delete_negative_keywords_from_entities_request=delete_negative_keywords_request
)
# Create a shared negative keyword list
negative_keyword_list = NegativeKeywordList(
name="My Negative Keyword List " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()),
type="NegativeKeywordList"
)
shared_list_items = [
NegativeKeyword(
text="car",
type="NegativeKeyword",
match_type=MatchType.EXACT
),
NegativeKeyword(
text="car",
type="NegativeKeyword",
match_type=MatchType.PHRASE
)
]
add_shared_entity_request = AddSharedEntityRequest(
shared_entity=negative_keyword_list,
list_items=shared_list_items
)
add_shared_entity_response = campaign_service.add_shared_entity(
add_shared_entity_request=add_shared_entity_request
)
shared_entity_id = add_shared_entity_response.SharedEntityId
# Associate the shared negative keyword list with the campaign
shared_entity_association = SharedEntityAssociation(
entity_id=campaign_ids[0],
entity_type="Campaign",
shared_entity_id=shared_entity_id,
shared_entity_type="NegativeKeywordList"
)
shared_entity_associations = [shared_entity_association]
set_shared_entity_associations_request = SetSharedEntityAssociationsRequest(
associations=shared_entity_associations
)
partial_errors = campaign_service.set_shared_entity_associations(
set_shared_entity_associations_request=set_shared_entity_associations_request
)
# Delete the campaign
delete_campaigns_request = DeleteCampaignsRequest(
account_id=authorization_data.account_id,
campaign_ids=campaign_ids
)
campaign_service.delete_campaigns(
delete_campaigns_request=delete_campaigns_request
)
# Delete the shared negative keyword list
negative_keyword_list = NegativeKeywordList(
id=shared_entity_id
)
negative_keyword_lists = [negative_keyword_list]
delete_shared_entities_request = DeleteSharedEntitiesRequest(
shared_entities=negative_keyword_lists
)
partial_errors = campaign_service.delete_shared_entities(
delete_shared_entities_request=delete_shared_entities_request
)
except Exception as ex:
print(f"Error occurred: {str(ex)}")
if __name__ == '__main__':
print("Loading the web service client...")
authorization_data = AuthorizationData(
account_id=None,
customer_id=None,
developer_token=DEVELOPER_TOKEN,
authentication=None,
)
authenticate(authorization_data)
campaign_service = ServiceClient(
service='CampaignManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
main(authorization_data)