client.Audiences
Каждый метод этого пространства имён: его сигнатура, параметры, что он возвращает, и пример.
Методы
Named lists of contacts. Every contact is in the default audience, and you make the rest.
Audiences.ListAsyncAudiences.ListAllAsyncAudiences.IterateAsyncAudiences.GrowthAsyncAudiences.GetAsyncAudiences.CreateAsyncAudiences.UpdateAsyncAudiences.DeleteAsyncAudiences.EmptyAsyncAudiences.ListContactsAsyncAudiences.ListAllContactsAsyncAudiences.IterateContactsAsyncAudiences.AddContactAsyncAudiences.RemoveContactAsyncAudiences.AddContactsAsyncAudiences.RemoveContactsAsyncAudiences.ImportContactsAsync
Audiences.ListAsync
List one page of the workspace audiences
Task<Page> ListAsync( int? limit = null, string? cursor = null, string? apiKey = null, CancellationToken cancellationToken = default)Returns one page of the audiences in the workspace, with the default audience first and the rest newest first. Paging is keyset: limit: takes 1 to 100 and defaults to 25, and nextCursor goes back as cursor: while hasMore is true, so every audience is reachable. ListAllAsync and IterateAsync do that walk for you.
builtin tells the default audience apart from the ones you made. It is default on exactly one row per workspace, the audience that holds every contact, and null on everything else. Branch on builtin rather than on the name, which anybody can change.
contactCount is counted at the moment of the read, so two reads either side of a Contacts.CreateAsync disagree by one.
Параметры
limitint?Rows per page, a whole number from 1 to 100. The server defaults to 25.
cursorstring?The
nextCursorfrom the previous page, an audience id. One that names no audience in the workspace is a 400invalid_cursor.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A Page with items, hasMore and nextCursor. Each item has id, name, description, builtin, contactCount, lastContactAt, createdAt and updatedAt.
Пример
var page = await client.Audiences.ListAsync(); foreach (var audience in page){ var label = (string?)audience["builtin"] == "default" ? " (everyone)" : ""; Console.WriteLine($"{audience["name"]}{label}: {audience["contactCount"]} contacts");}Примечания
The default audience is resolved on the first read of the workspace, so a workspace that has never had an audience made still lists it.
Names are not unique. Two audiences can both be called Newsletter, so match on
idin stored configuration.
Также доступно в
- API
GET /audiences- TypeScript
audiences.list()- Python
audiences.list()- Ruby
audiences.list- PHP
audiences->list- Go
Audiences.List- Java
audiences().list- CLI
openemail audiences list
Audiences.ListAllAsync
Collect every audience in the workspace into one object
Task<IReadOnlyList<JsonObject>> ListAllAsync( int? limit = null, string? cursor = null, string? apiKey = null, CancellationToken cancellationToken = default)Follows nextCursor from page to page and returns every audience in the workspace, the default audience first and the rest newest first. limit: sets the page size of each request, not the total.
Параметры
limitint?Page size per request, from 1 to 100, defaulting to 25 on the server.
cursorstring?An audience id to start after.
apiKeystring?Overrides the client's API key for every page of this walk.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A list of JsonObject items holding every audience across all pages.
Пример
var audiences = await client.Audiences.ListAllAsync(limit: 100); Console.WriteLine(audiences.Count);Примечания
A failure on any page throws out of the whole call.
Также доступно в
- API
GET /audiences- TypeScript
audiences.listAll()- Python
audiences.list_all()- Ruby
audiences.list_all- PHP
audiences->listAll- Go
Audiences.ListAll- Java
audiences().listAll
Audiences.IterateAsync
Stream the workspace audiences one at a time
IAsyncEnumerable<JsonObject> IterateAsync( int? limit = null, string? cursor = null, string? apiKey = null, CancellationToken cancellationToken = default)Returns an IAsyncEnumerable<JsonObject> that yields audiences one at a time, the default audience first, and requests the next page only once the current one is drained. Breaking out of the loop stops the requests.
Параметры
limitint?Page size per request, from 1 to 100, defaulting to 25 on the server.
cursorstring?An audience id to start after.
apiKeystring?Overrides the client's API key for every page of this walk.
cancellationTokenCancellationTokenCancels the request.
Возвращает
An IAsyncEnumerable<JsonObject> that yields one audience per step.
Пример
await foreach (var audience in client.Audiences.IterateAsync()){ if ((int?)audience["contactCount"] == 0) { Console.WriteLine($"Empty: {audience["name"]}"); }}Примечания
The generator is lazy, so an abandoned loop costs only the pages you consumed.
Также доступно в
- API
GET /audiences- TypeScript
audiences.iterate()- Python
audiences.iterate()- Ruby
audiences.iterate- PHP
audiences->iterate- Go
Audiences.Iterate- Java
audiences().iterate
Audiences.GrowthAsync
Read how audiences grew over a time window
Task<JsonObject> GrowthAsync( IEnumerable<string>? audienceIds = null, int? days = null, int? minutes = null, string? grain = null, int? offsetMinutes = null, string? apiKey = null, CancellationToken cancellationToken = default)Returns the numbers behind the growth chart on the Audiences page in one request. For each audience it reports total, the contacts in it now, before, how many of those joined before the window, added, how many joined inside it, subscribed, how many of them are still subscribed, unsubscribed, how many unsubscribed inside the window through a broadcast link, and buckets, when they joined and unsubscribed, cut to grain. totals sums the audiences read.
An audience records the date each contact joined it and never the date one left. A series therefore counts the contacts still in the list today by the date they joined, and it never falls: a contact who joined inside the window and was removed since is not in it at all. Read it as the growth of the list as it stands, not as a history of every change.
totals.contacts counts each person once, however many of the audiences they are in. totals.memberships adds the lists up, and the default audience holds every contact, so a person in two other audiences counts three times there. totals.subscribed counts each person still subscribed to at least one of the audiences read, which is who a broadcast to them would reach, and totals.unsubscribed adds up the unsubscribes inside the window. totals.busiest is the bucket with the most joins, or null.
buckets is sparse and oldest first: a bucket in which nobody joined or unsubscribed has no entry, so a chart must fill the gaps. grain: sets the bucket width and the key shape, YYYY-MM-DD, YYYY-MM-DDTHH or YYYY-MM-DDTHH:MM, and offsetMinutes: shifts the boundaries so days break where the reader's day does. The window starts at the beginning of its oldest bucket, reported as since, and ends now, reported as until.
Параметры
audienceIdsIEnumerable<string>?Up to 50 audience ids to read, as a dictionary or one comma-separated string, sent comma separated. Leave it out, or pass an empty dictionary, to read every audience in the workspace, the default one included. An id that is not an audience of this workspace is a 404
audience_not_foundonaudienceIds, and more than 50 is a 422.daysint?Window length in days, from 1 to 1095, defaulting to 30.
minutesint?Window length in minutes, from 1 to 1576800. Takes precedence over
days, and only useful below a day with a finergrain.grainstring?Bucket width:
minute,hourorday, defaulting today.offsetMinutesint?Minutes east of UTC to cut the buckets in, from -840 to 840, defaulting to 0. Pass
(int)TimeZoneInfo.Local.GetUtcOffset(DateTimeOffset.Now).TotalMinutesfor the zone of the machine.apiKeystring?Reads with this key instead of the client's.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience_growth, since, until, grain, offsetMinutes, totals and series. totals has contacts, subscribed, memberships, added, unsubscribed, lists and busiest. Each entry of series has id, name, builtin as a boolean, total, subscribed, before, added, unsubscribed and buckets, each an object with bucket, added and unsubscribed. The series come largest first, then by name.
Пример
var offsetMinutes = (int)TimeZoneInfo.Local.GetUtcOffset(DateTimeOffset.Now).TotalMinutes;var growth = await client.Audiences.GrowthAsync(days: 90, grain: "day", offsetMinutes: offsetMinutes);var totals = growth["totals"]; Console.WriteLine($"{totals?["added"]} joins since {growth["since"]}, busiest {totals?["busiest"]?.ToString() ?? "none"}"); foreach (var series in growth["series"]?.AsArray() ?? []){ Console.WriteLine($"{series?["name"]}: {series?["before"]} then {series?["total"]}");}Примечания
Read only, so the SDK retries it after a network failure like any other read.
builtinon a series is a boolean, true on the default audience. On the audience objectsListAsyncandGetAsyncreturn, the same fact is the stringdefault.A running total per bucket is
beforeplus theaddedof every bucket up to it.
Также доступно в
Audiences.GetAsync
Read one audience by id
Task<JsonObject> GetAsync( string id, string? apiKey = null, CancellationToken cancellationToken = default)Returns a single audience in the same shape as ListAsync, with a fresh contactCount. This is the cheap way to watch a count move without pulling the contacts behind it.
The id is the one from ListAsync or CreateAsync, such as aud_9f2c4b7e1a0d63d84c5f2e7b. An id from another workspace is a 404 rather than a 403, since the API never tells you that something exists somewhere you cannot see.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with id, name, description, builtin, contactCount, lastContactAt, the moment the most recent contact joined or null while it is empty, createdAt and updatedAt.
Пример
var audience = await client.Audiences.GetAsync("aud_9f2c4b7e1a0d63d84c5f2e7b"); Console.WriteLine($"{audience["name"]}: {audience["contactCount"]} contacts, last joined {audience["lastContactAt"]?.ToString() ?? "never"}");Примечания
A missing audience throws an
OpenEmailApiExceptionwhoseIsNotFoundis true, withCodeaudience_not_found.The default audience can be read here like any other, and
builtinisdefaulton it.
Также доступно в
- API
GET /audiences/{id}- TypeScript
audiences.get()- Python
audiences.get()- Ruby
audiences.get- PHP
audiences->get- Go
Audiences.Get- Java
audiences().get- CLI
openemail audiences get
Audiences.CreateAsync
Create an audience
Task<JsonObject> CreateAsync( IReadOnlyDictionary<string, object?> body, string? apiKey = null, CancellationToken cancellationToken = default)Makes a new, empty audience in the workspace and returns it with its id. name is trimmed and must then be 1 to 120 characters. description is optional free text for whoever reads the list later.
The audience comes back with builtin null and contactCount zero. Only the default audience carries a builtin, and it cannot be made or copied here.
Names are not checked for duplicates, so two calls with the same name make two audiences. Fill it with Audiences.AddContactAsync, one contact at a time, and the contacts must already be in the book.
Параметры
namestringОбязательноDisplay name, trimmed, 1 to 120 characters. Not unique.
descriptionstringWhat the audience is for. Leave it out to create the audience without one.
apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject for the new audience, with its id, builtin null and contactCount zero.
Пример
var audience = await client.Audiences.CreateAsync(new Body{ ["name"] = "Product updates", ["description"] = "Customers who asked to hear about releases",}); await client.Audiences.AddContactAsync(audience["id"]!.GetValue<string>(), new Body { ["email"] = "[email protected]" }); Console.WriteLine($"{audience["id"]}");Примечания
The SDK does not retry a create after a network failure, and nothing here deduplicates by name, so a retry after a lost response can leave two audiences. List them and delete the spare.
A workspace holds at most 100 audiences. The 101st is refused with 422
audience_limit_reachedonname.Audiences belong to the workspace, not to the key or the person who made them.
Также доступно в
Audiences.UpdateAsync
Rename an audience or change its description
Task<JsonObject> UpdateAsync( string id, IReadOnlyDictionary<string, object?> patch, string? apiKey = null, CancellationToken cancellationToken = default)Changes the fields you send and leaves the rest alone. A key you leave out keeps its stored value and an explicit null clears it, so new Body { ["description"] = null } empties the description while an empty patch changes nothing.
The default audience can be renamed like any other, and renaming it does not change builtin or what it holds. builtin itself cannot be set, moved or cleared from here.
The id never changes, and membership is untouched.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.namestringNew display name, trimmed, 1 to 120 characters.
descriptionstringNew description. Null clears it.
apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject, the audience as it stands after the change, with the unchanged id and builtin.
Пример
var audience = await client.Audiences.UpdateAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", new Body { ["name"] = "Release notes", ["description"] = null }); Console.WriteLine($"{audience["name"]}, updated {audience["updatedAt"]}");Примечания
The SDK retries this call after a network failure, since the same patch sent twice leaves the same audience.
Renaming does not move anybody. Contacts stay in the audience under its new name.
Также доступно в
Audiences.DeleteAsync
Delete an audience and keep its contacts
Task<JsonObject> DeleteAsync( string id, string? apiKey = null, CancellationToken cancellationToken = default)Deletes the audience and drops every membership it held, in one transaction. The contacts themselves are not touched: they stay in the address book, in the default audience, and in any other audience they were in.
The default audience cannot be deleted. The call is refused with 409 audience_immutable on id, because it is what makes the book readable as a list. Delete the contacts instead if you mean to empty it.
There is no undo, and a new audience with the same name comes back empty.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b. Not the default audience.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience, id and deleted set to true.
Пример
var removed = await client.Audiences.DeleteAsync("aud_9f2c4b7e1a0d63d84c5f2e7b"); Console.WriteLine($"{removed["id"]}{((bool?)removed["deleted"] == true ? " is gone, its contacts kept" : " is still there")}");Примечания
The SDK does not retry a delete. A 404 on your own second attempt after a lost response means the first one worked.
An audience from another workspace is a 404, never a 403.
To keep the audience and take its contacts out, use
EmptyAsync.
Также доступно в
Audiences.EmptyAsync
Take every contact out of an audience and keep the audience
Task<JsonObject> EmptyAsync( string id, string? apiKey = null, CancellationToken cancellationToken = default)Removes every membership of the audience in one transaction and returns the audience as it now stands, contactCount 0, plus removed, the number of contacts taken out. The audience keeps its id, name and description, so anything that points at it still works. The contacts are not touched: each one stays in the address book, in the default audience and in every other audience it is in.
The default audience cannot be emptied. The call is refused with 409 audience_immutable on id, because that audience holds every contact for as long as it is a contact.
There is no undo. The app asks the person to confirm before it empties a list, but this call asks nothing: it needs no verification code, whether it is made with an API key or with the OAuth access token of an app the person connected. Check the id before you call it.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b. Not the default audience.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject, the audience as GetAsync returns it with contactCount 0, plus removed, the number of contacts taken out.
Пример
var emptied = await client.Audiences.EmptyAsync("aud_9f2c4b7e1a0d63d84c5f2e7b"); Console.WriteLine($"{emptied["removed"]} removed from {emptied["name"]}");Примечания
The SDK does not retry this call after a network failure. Emptying twice leaves the same empty audience, but the second call reports
removed: 0, so read the audience withGetAsyncif a response was lost.Emptying an audience that is already empty succeeds with
removed: 0.To take out only some contacts, use
RemoveContactsAsync. To delete the audience as well, useDeleteAsync, which also leaves the contacts alone.
Также доступно в
Audiences.ListContactsAsync
List one page of the contacts in one audience
Task<Page> ListContactsAsync( string id, string? q = null, string? source = null, string? sort = null, IEnumerable<string>? statuses = null, int? limit = null, string? cursor = null, string? apiKey = null, CancellationToken cancellationToken = default)Returns one page of the contacts in the audience. The rows are the contacts themselves, not membership records, so they carry email, name, source, notes, lastSeenAt, createdAt and updatedAt, plus addedAt, the date the contact joined this audience, and unsubscribedAt, when it unsubscribed from a broadcast sent to this audience, or null while it is subscribed. An unsubscribed contact stays in the audience and broadcasts to it skip it.
By default the order is the one Contacts.ListAsync uses: the contacts most recently written to first, and those never written to last. sort: picks another order, q: searches names and addresses, source: keeps only contacts saved by hand or only those recorded from the composer, and statuses: keeps only the subscribed or only the unsubscribed. These are the controls on the audience page in the app.
Paging is keyset: limit: takes 1 to 200 and defaults to 50, and nextCursor goes back as cursor: while hasMore is true, so every contact in the audience is reachable however large it grows. Send the same q:, source:, sort: and statuses: with every page. ListAllContactsAsync and IterateContactsAsync do that walk for you, which is also how to export an audience.
Reading the default audience here returns the whole address book.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.qstring?Narrows to contacts whose name or address matches, up to 200 characters. When nothing matches exactly the search allows for a typo instead.
sourcestring?Narrows to contacts recorded that way:
manualfor one somebody saved,autofor one recorded by a send from the app composer,formfor one a sign-up form added.sortstring?How the page is ordered.
last-heard-newest, the default, puts the contacts most recently written to first and those never written to last,last-heard-oldestreverses it,added-newestandadded-oldestorder byaddedAt, andnameis alphabetical without case, with a contact that has no name sorting by its address.statusesIEnumerable<string>?Keeps only
subscribedmembers, onlyunsubscribedones, or both, as a dictionary or one comma-separated string. Leave it out, or name both, for everyone in the audience.OpenEmail\Constants\AudienceMemberStatusesholds the values.limitint?Rows per page, a whole number from 1 to 200. The server defaults to 50.
cursorstring?The
nextCursorfrom the previous page. Never build one yourself. One that names no contact in this audience is a 400invalid_cursor.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A Page with items, hasMore and nextCursor. Each item is a contact object, as Contacts.ListAsync returns it, plus addedAt, when the contact joined this audience, and unsubscribedAt, null unless it unsubscribed from a broadcast.
Пример
using OpenEmail.Constants; var page = await client.Audiences.ListContactsAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", sort: "added-newest", statuses: new[] { AudienceMemberStatuses.Subscribed }, limit: 200); foreach (var contact in page){ Console.WriteLine($"{contact["email"]} joined {contact["addedAt"]}");}Примечания
Only
audiences:readis needed. A key with that scope reads the contacts in an audience without holdingcontacts:read.A contact in no audience of your own is still in the default one, so nothing is invisible to this route.
An audience from another workspace is a 404.
An unknown
sort,sourceor status is a 422invalid_parameter.
Также доступно в
Audiences.ListAllContactsAsync
Collect every contact in one audience into one object
Task<IReadOnlyList<JsonObject>> ListAllContactsAsync( string id, string? q = null, string? source = null, string? sort = null, IEnumerable<string>? statuses = null, int? limit = null, string? cursor = null, string? apiKey = null, CancellationToken cancellationToken = default)Walks every page of one audience and returns all of its contacts, each with addedAt, in the order ListContactsAsync returns them. q:, source:, sort: and statuses: are sent with every page, so the walk returns the filtered list in the order you asked for. This is the way to export an audience. On the default audience that is the whole address book, so prefer IterateContactsAsync when you can stop early. limit: sets the page size of each request, not the total.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.qstring?Narrows to contacts whose name or address matches, up to 200 characters. When nothing matches exactly the search allows for a typo instead.
sourcestring?Narrows to contacts recorded that way:
manualfor one somebody saved,autofor one recorded by a send from the app composer,formfor one a sign-up form added.sortstring?The order of the walk, as for
ListContactsAsync. Defaults tolast-heard-newest.statusesIEnumerable<string>?Keeps only
subscribedmembers, onlyunsubscribedones, or both, as a dictionary or one comma-separated string. Leave it out, or name both, for everyone in the audience.OpenEmail\Constants\AudienceMemberStatusesholds the values.limitint?Page size per request, from 1 to 200, defaulting to 50 on the server.
cursorstring?A cursor from an earlier page to start after.
apiKeystring?Overrides the client's API key for every page of this walk.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A list of JsonObject items holding every contact in the audience that matches, each a contact object plus addedAt and unsubscribedAt.
Пример
var contacts = await client.Audiences.ListAllContactsAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", limit: 200); foreach (var contact in contacts){ Console.WriteLine($"{contact["email"]},{contact["name"]},{contact["addedAt"]}");}Примечания
A failure on any page throws out of the whole call, and the contacts already fetched are discarded.
An audience from another workspace is a 404 on the first page.
Также доступно в
Audiences.IterateContactsAsync
Stream the contacts in one audience one at a time
IAsyncEnumerable<JsonObject> IterateContactsAsync( string id, string? q = null, string? source = null, string? sort = null, IEnumerable<string>? statuses = null, int? limit = null, string? cursor = null, string? apiKey = null, CancellationToken cancellationToken = default)Returns an IAsyncEnumerable<JsonObject> over one audience that yields contacts one at a time, each with addedAt, and fetches the next page only when the current one is drained. q:, source:, sort: and statuses: are sent with every page. Nothing is requested until you consume it, and breaking out of the loop stops further requests, which suits a send loop or an export that works through a large audience.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.qstring?Narrows to contacts whose name or address matches, up to 200 characters. When nothing matches exactly the search allows for a typo instead.
sourcestring?Narrows to contacts recorded that way:
manualfor one somebody saved,autofor one recorded by a send from the app composer,formfor one a sign-up form added.sortstring?The order of the walk, as for
ListContactsAsync. Defaults tolast-heard-newest.statusesIEnumerable<string>?Keeps only
subscribedmembers, onlyunsubscribedones, or both, as a dictionary or one comma-separated string. Leave it out, or name both, for everyone in the audience.OpenEmail\Constants\AudienceMemberStatusesholds the values.limitint?Page size per request, from 1 to 200, defaulting to 50 on the server.
cursorstring?A cursor from an earlier page to start after.
apiKeystring?Overrides the client's API key for every page of this walk.
cancellationTokenCancellationTokenCancels the request.
Возвращает
An IAsyncEnumerable<JsonObject> that yields one contact per step, each a contact object plus addedAt and unsubscribedAt.
Пример
using OpenEmail.Constants; var subscribed = client.Audiences.IterateContactsAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", statuses: new[] { AudienceMemberStatuses.Subscribed }); await foreach (var contact in subscribed){ await client.Emails.SendAsync(new Body { ["from"] = "[email protected]", ["to"] = contact["email"], ["subject"] = "Doors open on Friday", ["text"] = $"Hi {contact["name"]?.ToString() ?? "there"}, doors open at nine.", });}Примечания
The generator is lazy, so an abandoned loop costs only the pages you consumed.
Также доступно в
Audiences.AddContactAsync
Put a contact in an audience
Task<JsonObject> AddContactAsync( string id, IReadOnlyDictionary<string, object?> body, string? apiKey = null, CancellationToken cancellationToken = default)Adds one contact to one audience and returns the membership, with the contact it points at. The address is trimmed and lower cased before the lookup, and it has to be a contact in this workspace already: an address that is not in the book is refused with 422 contact_not_found on email. Save it with Contacts.CreateAsync first.
There is one membership per audience and contact, so adding somebody who is already in the audience returns the membership that is there, with its original addedAt, rather than adding a second one or failing. That makes the call safe to replay, and the SDK retries it after a network failure.
Adding to the default audience is accepted and changes nothing, since every contact is already in it.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.emailstringОбязательноThe address of a contact already in the workspace book, matched case insensitively.
apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience_member, audienceId, addedAt and contact.
Пример
await client.Contacts.CreateAsync(new Body { ["email"] = "[email protected]", ["name"] = "Grace Hopper" }); var membership = await client.Audiences.AddContactAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", new Body { ["email"] = "[email protected]" }); Console.WriteLine($"{membership["contact"]?["email"]} joined {membership["audienceId"]} at {membership["addedAt"]}");Примечания
To add up to 200 contacts in one call, use
AddContactsAsync. To create contacts as you add them, useImportContactsAsync.audiences:writeis the only scope checked. Adding a contact to an audience is not a write to the contact.Deleting the contact later drops this membership with it.
Также доступно в
Audiences.RemoveContactAsync
Take a contact out of an audience
Task<JsonObject> RemoveContactAsync( string id, string email, string? apiKey = null, CancellationToken cancellationToken = default)Drops one membership and leaves everything else alone. The contact stays in the address book, in the default audience and in every other audience it was in. The address is trimmed and lower cased, and the SDK URL encodes it for the path.
A contact that is not in this audience is a 404, so a typo cannot report a removal that never happened.
The default audience cannot be thinned. Removing a contact from it is refused with 409 audience_immutable, because it holds every contact by definition. Use Contacts.DeleteAsync when you mean the contact to go.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b. Not the default audience.emailstringОбязательноThe contact's address, matched case insensitively.
apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience_member, audienceId, email and deleted set to true.
Пример
var removed = await client.Audiences.RemoveContactAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", "[email protected]"); Console.WriteLine($"{removed["email"]} left {removed["audienceId"]}");Примечания
The SDK does not retry a delete. A 404 on your own second attempt after a lost response means the first one worked.
Removing the last contact leaves the audience in place and empty.
Также доступно в
Audiences.AddContactsAsync
Put up to 200 existing contacts in an audience in one call
Task<JsonObject> AddContactsAsync( string id, IReadOnlyDictionary<string, object?> body, string? apiKey = null, CancellationToken cancellationToken = default)Adds many contacts to one audience in one transaction and reports what happened to each address. Each address is trimmed and lower cased, a repeat counts once, and each has to be a contact in this workspace already.
Nothing is refused for one address. An address that is not a contact is returned in missing and the others are still added, and a contact that is in the audience already is counted in unchanged and keeps its original addedAt. added counts the contacts that joined in this call.
This never creates a contact. To save new addresses and put them in the audience in the same call, use ImportContactsAsync. Adding to the default audience succeeds with added: 0, since every contact is already in it.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b.emailsIEnumerable<string>ОбязательноFrom 1 to 200 addresses of contacts already in the workspace book, matched case insensitively. An empty dictionary or more than 200 is a 422
invalid_parameteronemails, and an empty or overlong address is the same error on that entry, such asemails.2.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience_batch, audienceId, added, unchanged and missing. missing lists the addresses that are not contacts, trimmed, lower cased and once each.
Пример
var result = await client.Audiences.AddContactsAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", new Body{ ["emails"] = new[] { "[email protected]", "[email protected]", "[email protected]" },}); Console.WriteLine($"{result["added"]} added, {result["unchanged"]} already in it"); if ((result["missing"]?.AsArray().Count ?? 0) > 0){ Console.WriteLine($"Not contacts yet: {string.Join(", ", result["missing"]?.AsArray() ?? [])}");}Примечания
Safe to replay: a second call with the same addresses adds nothing and reports them as
unchanged. The SDK retries it after a network failure.Send a longer list in chunks of 200.
audiences:writeis the only scope checked. Adding contacts to an audience is not a write to the contacts.An audience from another workspace is a 404
audience_not_found.
Также доступно в
Audiences.RemoveContactsAsync
Take up to 200 contacts out of an audience in one call
Task<JsonObject> RemoveContactsAsync( string id, IReadOnlyDictionary<string, object?> body, string? apiKey = null, CancellationToken cancellationToken = default)Removes many contacts from one audience in one transaction and reports what happened to each address. Each address is trimmed and lower cased and a repeat counts once. The contacts stay in the address book, in the default audience and in every other audience they are in.
Nothing is refused for one address, which is where this differs from RemoveContactAsync. A contact that is not in this audience is returned in notInAudience, an address that is not a contact at all in missing, and the rest are still removed. removed counts the contacts taken out in this call.
The default audience cannot be thinned. The call is refused with 409 audience_immutable on id, because that audience holds every contact by definition. Use Contacts.DeleteAsync when you mean a contact to go.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b. Not the default audience.emailsIEnumerable<string>ОбязательноFrom 1 to 200 addresses, matched case insensitively. An empty dictionary or more than 200 is a 422
invalid_parameteronemails, and an empty or overlong address is the same error on that entry, such asemails.2.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience_batch, audienceId, removed, notInAudience and missing.
Пример
var result = await client.Audiences.RemoveContactsAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", new Body { ["emails"] = new[] { "[email protected]", "[email protected]" } }); Console.WriteLine($"{result["removed"]} removed. Not in it: {string.Join(", ", result["notInAudience"]?.AsArray() ?? [])}");Примечания
Safe to replay, and the SDK retries it after a network failure. A replay after a lost response succeeds and reports the contacts the first call removed under
notInAudience, soremovedon the retry can read 0.Send a longer list in chunks of 200. To take everyone out, use
EmptyAsync.Removing the last contacts leaves the audience in place and empty.
Также доступно в
Audiences.ImportContactsAsync
Import up to 500 addresses into an audience, creating contacts as needed
Task<JsonObject> ImportContactsAsync( string id, IReadOnlyDictionary<string, object?> body, string? apiKey = null, CancellationToken cancellationToken = default)Does what the CSV import on an audience page does, without the file. Each row is an address and an optional name, and the whole call runs in one transaction.
An address that is not a contact yet is saved as one, with source set to manual, and joins the default audience as every new contact does. An address that is a contact already is reused as it stands: its name is kept, and a name sent here only fills one that is empty. Every imported contact ends up in this audience. Importing an address whose contact was deleted brings it back.
A row whose address is not well formed is skipped rather than failing the call. It is counted in skipped and its address is returned in invalid exactly as you sent it, and every other row is still imported. Rows with the same address count once.
Параметры
idstringОбязательноAudience id such as
aud_9f2c4b7e1a0d63d84c5f2e7b. The default audience is accepted and saves the contacts without putting them in any other list.contactslistОбязательноFrom 1 to 500 rows, each a dictionary with
emailandname.emailis required, at most 320 characters, and trimmed and lower cased.nameis optional, at most 200 characters, and used for a new contact or for an existing one whose name is empty. An empty list, more than 500 rows, an emptyemailor any other key in a row is a 422.apiKeystring?Overrides the client's API key for this call only.
cancellationTokenCancellationTokenCancels the request.
Возвращает
A JsonObject with object set to audience_import, audienceId, created, added, skipped and invalid. created counts new contacts, added the contacts that joined this audience in this call, new and existing together.
Пример
var result = await client.Audiences.ImportContactsAsync("aud_9f2c4b7e1a0d63d84c5f2e7b", new Body{ ["contacts"] = new[] { new Body { ["email"] = "[email protected]", ["name"] = "Grace Hopper" }, new Body { ["email"] = "[email protected]" }, new Body { ["email"] = "not an address" }, },}); Console.WriteLine($"{result["created"]} created, {result["added"]} added");Console.WriteLine($"Skipped: {string.Join(", ", result["invalid"]?.AsArray() ?? [])}");Примечания
Needs both
audiences:writeandcontacts:write, because it creates contacts as well as memberships. A key without either is refused with 403insufficient_scopebefore anything is saved.Safe to replay: running the same rows again creates nothing twice and adds nothing twice. The SDK retries it after a network failure.
Send a longer list in chunks of 500.
To add contacts that already exist without creating any, use
AddContactsAsync, which reports the addresses that are not contacts instead of saving them.