FoPost.Sdk

Official .NET SDK for the FoPost API. Schedule and publish to +30 social
platforms from your code.
dotnet add package FoPost.Sdk
Requires .NET 8 or newer. No third-party dependencies.
0.x release. The public API is still settling and minor versions may contain breaking
changes. Pin an exact version if that matters to you.
Quick start
using FoPost;
using var client = new FoPostClient(Environment.GetEnvironmentVariable("FOPOST_API_KEY")!);
// List your accounts
var accounts = await client.Accounts.ListAsync("9b2f6c1e-…");
// Create a post, then publish it immediately
var post = await client.Posts.CreateAsync(
workspaceId: "9b2f6c1e-…",
text: "Hello from the SDK",
accounts: accounts.Select(account => account.Id));
await client.Posts.PublishAsync(post.Id);
// Schedule for later
await client.Posts.CreateAsync(new CreatePostOptions
{
WorkspaceId = "9b2f6c1e-…",
Status = PostStatuses.Scheduled,
ScheduleAt = new DateTimeOffset(2026, 6, 1, 10, 0, 0, TimeSpan.Zero),
Content = new List<PostContent> { new("Scheduled with the SDK") },
Accounts = new List<string> { accounts[0].Id },
});
Create an API key in the dashboard under Settings → API Keys. A key is limited to the scopes
granted at creation — the calls above need posts and accounts.
Configuration
using var client = new FoPostClient(new FoPostClientOptions
{
ApiKey = "fp_…", // defaults to $FOPOST_API_KEY
BaseUrl = "https://api.fopost.com", // override for staging or self-hosted
Timeout = TimeSpan.FromSeconds(30),
MaxRetries = 3, // total attempts on a 429, including the first
HttpClient = httpClientFromFactory, // optional; the SDK will not dispose it
});
| Env var |
Used for |
FOPOST_API_KEY |
API key, when ApiKey is not passed |
FoPostClient is thread-safe and meant to be long-lived — register it as a singleton rather than
constructing one per request. With IHttpClientFactory:
services.AddHttpClient("fopost");
services.AddSingleton(provider => new FoPostClient(new FoPostClientOptions
{
HttpClient = provider.GetRequiredService<IHttpClientFactory>().CreateClient("fopost"),
}));
Paging
ListAsync returns one page plus its Meta. ListAllAsync walks every page for you:
await foreach (var post in client.Posts.ListAllAsync(new ListPostsOptions
{
WorkspaceId = "9b2f6c1e-…",
Status = PostStatuses.Scheduled,
}))
{
Console.WriteLine($"{post.ScheduleAt:u} {post.Content.FirstOrDefault()?.Text}");
}
Partial updates
Every field on UpdatePostOptions is an Optional<T>, so “leave this alone” and “clear this” stay
different things:
await client.Posts.UpdateAsync(post.Id, new UpdatePostOptions
{
Title = "New title", // sent
Summary = Optional<string?>.Of(null), // sent as null, clearing it
// ScheduleAt is untouched — not sent at all
});
AI features
// Caption assist — accepts an API key carrying the `ai` scope
var caption = await client.Ai.GenerateCaptionAsync(new GenerateCaptionOptions
{
CurrentCaption = "shipping a new feature",
Platforms = new List<string> { Platforms.Twitter, Platforms.LinkedIn },
});
// Check your balance
var balance = await client.Ai.CreditsAsync();
Console.WriteLine($"{balance.CreditsRemaining} of {balance.CreditsTotal} credits left");
RewriteAsync and RepurposeUrlAsync are dashboard-session endpoints: they need a
BearerToken rather than an API key, and answer 401 to a key.
Inbox and ads
// Unanswered comments and mentions from the last week, then answer one
var unanswered = await client.Inbox.ListAsync(new ListInboxOptions
{
WorkspaceId = "9b2f6c1e-…",
Status = InboxStatuses.Unanswered,
Since = DateTimeOffset.UtcNow.AddDays(-7),
});
await client.Inbox.ReplyAsync(unanswered[0].Id, "Thanks for reaching out!");
// Resolve every unanswered comment older than a week, without replying
await client.Inbox.ResolveAsync(new ResolveInboxOptions
{
WorkspaceId = "9b2f6c1e-…",
Type = InboxItemTypes.Comment,
Before = DateTimeOffset.UtcNow.AddDays(-7),
});
// Boost a published post; it starts paused until you resume it
var ad = await client.Ads.BoostAsync(new BoostPostOptions
{
WorkspaceId = "9b2f6c1e-…",
ConnectionId = "c1d2e3f4-…",
AdAccountId = "act_123",
PostId = post.Id,
AccountId = post.Accounts[0].Id,
Name = "Launch boost",
Goal = AdGoals.Engagement,
Budget = new AdBudget(2000, AdBudgetTypes.Daily),
Targeting = new AdTargeting { Countries = new List<string> { "US" } },
});
await client.Ads.SetStatusAsync(ad.Id, ad.WorkspaceId!, AdStatuses.Active);
On X an item can also be reposted and bookmarked where CanRepost or CanBookmark is true, an
account can follow a user by numeric id, and a post can be looked up or searched with the
account’s token:
await client.Inbox.RepostAsync(item.Id);
await client.Accounts.FollowXUserAsync(xAccount.Id, "2244994945");
var page = await client.Accounts.SearchXPostsAsync(new XSearchOptions
{
AccountId = xAccount.Id,
Query = "from:yourbrand",
});
var post = await client.Accounts.GetXPostAsync(page[0].Id, xAccount.Id);
Every one of these is an X API call metered to the workspace; a 402 platform_balance_spent
means X’s own pay-per-use balance is spent. An X account connected before the bookmark and
follow permissions were asked for answers 409 reconnect_required until it is reconnected.
Pixels and conversions
PixelsAsync, CreatePixelAsync, PixelAsync, UpdatePixelAsync, SharePixelAsync,
PixelStatsAsync and EventMatchQualityAsync manage the ad account’s pixels, and
CustomConversionsAsync, CreateCustomConversionAsync, CustomConversionAsync,
UpdateCustomConversionAsync and DeleteCustomConversionAsync the custom conversions on them.
SendPixelConversionsAsync is the Conversions API send: it needs an Idempotency-Key, so the same
key answers the stored batch with Replayed true and nothing is sent twice. ConversionBatchesAsync
lists what was stored, with hashed identifiers only.
var result = await client.Ads.SendPixelConversionsAsync(new UploadConversionsOptions
{
WorkspaceId = "9b2f6c1e-…",
ConnectionId = "c1d2e3f4-…",
AdAccountId = "act_123",
PixelId = "1234567890",
Events = new List<ConversionEvent>
{
new()
{
EventName = "Purchase",
OccurredAt = "2026-10-18T10:04:00Z",
EventId = "order-77",
ActionSource = ConversionActionSources.Website,
ClickId = "fb.1.1700000000.abc",
ValueMinor = 4999,
Currency = "USD",
},
},
}, idempotencyKey: "order-77");
Analytics
// How long a post keeps earning, from the repeated readings of each post
var decay = await client.Analytics.DecayAsync(new AnalyticsScopeOptions { Days = 30 });
Console.WriteLine(decay.HalfLifeBucket); // e.g. "1h_3h"
// Whether posting more earned more
var cadence = await client.Analytics.FrequencyAsync(new AnalyticsScopeOptions { Days = 90 });
Console.WriteLine(cadence.Best?.Label); // e.g. "3-5 a week"
// Every reading held for one post, with what moved between them
var timeline = await client.Analytics.TimelineAsync(post.Id);
// Mirror the metrics into your own store, without refetching everything
DateTimeOffset? cursor = null;
while (true)
{
var page = await client.Analytics.ChangesAsync(new MetricChangesOptions { Since = cursor });
Save(page.Changes);
if (!page.HasMore || page.Cursor is null)
{
break;
}
cursor = page.Cursor;
}
// Refresh one post now instead of waiting for the next collection run
await client.Analytics.CollectPostAsync(post.Id);
// Posts on the account that never went out through FoPost
var native = await client.Analytics.NativePostsAsync(accounts[0].Id);
A post is addressed by its FoPost id or by its permalink, so a post made by
hand on the network works the same way:
await client.Analytics.TimelineAsync("https://x.com/acme/status/1");
## Contacts
The people behind the inbox: one person however many handles they write from. An inbound item files its author, a reply files whoever you answered, and both fold into whatever is already on file.
```csharp
var page = await client.Contacts.ListAsync(new ListContactsOptions
{
WorkspaceId = workspaceId,
Search = "ada",
});
foreach (var contact in page)
{
Console.WriteLine($"{contact.DisplayName} — {contact.Channels.Count} handles");
}
// Folds into whoever already holds the first channel, so this cannot duplicate someone.
var contact = await client.Contacts.CreateAsync(new CreateContactOptions
{
WorkspaceId = workspaceId,
Channels = new[] { ContactChannel.Of("x", "ada_writes") },
DisplayName = "Ada Okafor",
Fields = new Dictionary<string, string> { ["plan_tier"] = "Pro" },
});
// A field set to null is cleared; everything unset is left alone.
await client.Contacts.UpdateAsync(contact.Id, new UpdateContactOptions
{
Fields = new Dictionary<string, string?> { ["region"] = null },
});
await client.Contacts.DeleteAsync(contact.Id); // the messages stay in the inbox
// The threads this person appears in, newest first.
foreach (var thread in await client.Contacts.ConversationsAsync(contact.Id))
{
Console.WriteLine($"{thread.Platform} {thread.Messages} messages");
}
// platform and handle are required columns; any other column is a custom field key.
var result = await client.Contacts.ImportAsync(workspaceId, "platform,handle\nx,ada_writes");
Console.WriteLine($"{result.Created} created, {result.Merged} merged");
// The columns your workspace keeps.
var field = await client.Contacts.CreateFieldAsync(workspaceId, new CreateContactFieldOptions
{
Key = "plan_tier",
Name = "Plan Tier",
Type = ContactFieldTypes.Select,
Options = new[] { "Free", "Pro" },
});
await client.Contacts.DeleteFieldAsync(field.Id); // removes every answer to it
// Volume and median reply time per thread. Needs the `analytics` scope.
var report = await client.Contacts.ConversationAnalyticsAsync(new ConversationAnalyticsOptions
{
Days = 30,
Sort = ConversationSorts.Slowest,
});
Broadcasts and sequences
A broadcast is one message into every conversation you already have with a segment of your contacts; a sequence is a series of them on a delay. Neither opens a cold DM.
Nothing is sent into a closed messaging window: Messenger and Instagram take a business-initiated message only within 24 hours of the contact’s last one, so recipients outside it come back skipped with window_closed rather than attempted. Telegram, Slack, Bluesky and Reddit have no window. The number sent is therefore often lower than the audience, and that is correct rather than a failure.
Reading needs the inbox scope; SendAsync, CancelAsync, EnrollAsync and UnenrollAsync also need publish.
var broadcast = await client.Broadcasts.CreateAsync(new CreateBroadcastOptions
{
WorkspaceId = workspaceId,
AccountId = accountId,
Name = "September check-in",
Text = "New colours just landed. Want a look?",
Audience = AudienceFilter.OnPlatforms("instagram"),
});
// Recipients is how many contacts matched, not how many will be messaged.
var sent = await client.Broadcasts.SendAsync(broadcast.Id);
// Who was skipped, and why.
var skipped = await client.Broadcasts.RecipientsAsync(
broadcast.Id,
new ListRecipientsOptions { Status = RecipientStatuses.Skipped });
foreach (var recipient in skipped)
{
Console.WriteLine($"{recipient.DisplayName}: {recipient.SkipReason}");
}
var sequence = await client.Sequences.CreateAsync(new CreateSequenceOptions
{
WorkspaceId = workspaceId,
AccountId = accountId,
Name = "Welcome",
Steps = new[]
{
SequenceStep.Of(0, "Thanks for the follow — anything I can help with?"),
SequenceStep.Of(48, "Here is what people usually ask us first."),
},
});
// By id, or by the same audience filter a broadcast takes.
await client.Sequences.EnrollAsync(sequence.Id, new EnrollOptions { ContactIds = new[] { contactId } });
// Nothing further fires for them.
await client.Sequences.UnenrollAsync(sequence.Id, new[] { contactId });
Webhooks
FoPostWebhooks.Verify checks the raw request bytes against the headers, prefers the timestamped
signature and refuses one older than five minutes, then hands back the envelope:
// rawBody is the request body exactly as received, never re-serialised JSON.
var envelope = FoPostWebhooks.Verify(rawBody, headers, secret);
if (envelope.Event == "post.published")
{
Console.WriteLine(envelope.Data.GetProperty("id").GetString());
}
A failed check throws FoPostWebhookVerificationException.
Error handling
Every non-2xx response raises a FoPostException carrying the API’s status, error code, and body.
try
{
await client.Posts.PublishAsync(post.Id);
}
catch (FoPostRateLimitException error)
{
Console.WriteLine($"Slow down for {error.RetryAfter}");
}
catch (FoPostPaymentRequiredException error)
{
Console.WriteLine($"Upgrade at {error.UpgradeUrl}");
}
catch (FoPostException error)
{
Console.WriteLine($"API {error.Status} ({error.Code}): {error.Message}");
}
| Status |
Exception |
| 400, 422 |
FoPostValidationException |
| 401 |
FoPostAuthenticationException |
| 402 |
FoPostPaymentRequiredException |
| 403 |
FoPostPermissionDeniedException |
| 404 |
FoPostNotFoundException |
| 429 |
FoPostRateLimitException |
| any other |
FoPostException |
A 429 is retried automatically, up to MaxRetries attempts, waiting for the interval the API asks
for in Retry-After. The exception is raised only once the retries are spent.
Resources
| Namespace |
Methods |
Posts |
ListAsync, ListAllAsync, GetAsync, CreateAsync, UpdateAsync, DeleteAsync, PublishAsync, CancelAsync, RetryAsync, UnpublishAsync, PreflightAsync, DuplicateAsync, DeliveriesAsync |
Accounts |
ListAsync, GetAsync, RenameAsync, MoveAsync, HealthAsync, CreateTelegramConnectCodeAsync, GetTelegramConnectStatusAsync, GetTelegramBotCommandsAsync, SetTelegramBotCommandsAsync, DeleteTelegramBotCommandsAsync, ListSlackChannelsAsync, ListSlackMembersAsync, GetSlackIdentityAsync, UpdateSlackIdentityAsync, GetIceBreakersAsync, SetIceBreakersAsync, DeleteIceBreakersAsync, GetPersistentMenuAsync, SetPersistentMenuAsync, DeletePersistentMenuAsync, GetGreetingAsync, SetGreetingAsync, DeleteGreetingAsync, GetWebhookSubscriptionAsync, ResubscribeWebhookAsync, ListDiscordChannelsAsync, SwitchDiscordChannelAsync, GetDiscordIdentityAsync, UpdateDiscordIdentityAsync, ListDiscordPinsAsync, DeleteDiscordMessageAsync, PinDiscordMessageAsync, UnpinDiscordMessageAsync, CrosspostDiscordMessageAsync, CreateDiscordThreadAsync, SendDiscordDmAsync, ListDiscordEventsAsync, GetDiscordEventAsync, CreateDiscordEventAsync, UpdateDiscordEventAsync, DeleteDiscordEventAsync, ListDiscordMembersAsync, GetDiscordMemberAsync, ListDiscordRolesAsync, CreateDiscordRoleAsync, UpdateDiscordRoleAsync, DeleteDiscordRoleAsync, AddDiscordMemberRoleAsync, RemoveDiscordMemberRoleAsync, PlatformMetricsAsync, ListRedditSubredditsAsync, ListRedditSubredditRulesAsync, ListRedditFlairsAsync, SetRedditDefaultSubredditAsync, ListCommunitiesAsync, SyncCommunitiesAsync, SearchCommunitiesAsync, AddCommunityAsync, RemoveCommunityAsync, FollowXUserAsync, UnfollowXUserAsync, GetXPostAsync, SearchXPostsAsync |
AccountGroups |
ListAsync, GetAsync, CreateAsync, UpdateAsync, DeleteAsync, SetMembersAsync |
Workspaces |
ListAsync, GetAsync, CreateAsync, UpdateAsync, DeleteAsync |
Labels |
ListAsync, GetAsync, CreateAsync, UpdateAsync, DeleteAsync |
Ai |
CreditsAsync, GenerateCaptionAsync, RewriteAsync, RepurposeUrlAsync |
Inbox |
ListAsync, ThreadsAsync, ConversationsAsync, UnreadCountAsync, AccountsAsync, PlatformsAsync, MarkThreadReadAsync, RefreshAsync, UpdateAsync, ResolveAsync, EditCommentAsync, ReplyAsync, HideAsync, UnhideAsync, LikeAsync, UnlikeAsync, RepostAsync, UnrepostAsync, BookmarkAsync, UnbookmarkAsync, VoteAsync, PinAsync, UnpinAsync, ReactAsync, DeleteAsync, StartConversationAsync, SetTypingAsync, HandoverAsync, ApprovalsAsync, ApproveReplyAsync, RejectReplyAsync |
Contacts |
ListAsync, GetAsync, CreateAsync, UpdateAsync, DeleteAsync, ConversationsAsync, ImportAsync, ListFieldsAsync, CreateFieldAsync, UpdateFieldAsync, DeleteFieldAsync, ConversationAnalyticsAsync |
Knowledge |
ListAsync, CreateAsync, UpdateAsync, DeleteAsync, SyncAsync, SearchAsync |
Whatsapp |
GetProfileAsync, UpdateProfileAsync, RequestDisplayNameAsync, SetUsernameAsync, ListTemplatesAsync, ListTemplateLibraryAsync, GetTemplateAsync, CreateTemplateAsync, ImportTemplateAsync, UpdateTemplateAsync, DeleteTemplateAsync, ListGroupsAsync, CreateGroupAsync, GetGroupAsync, UpdateGroupAsync, DeleteGroupAsync, GetGroupInviteLinkAsync, ResetGroupInviteLinkAsync, RemoveGroupParticipantsAsync, ListBlockedAsync, BlockUsersAsync, UnblockUsersAsync, GetCommerceSettingsAsync, UpdateCommerceSettingsAsync, LinkCatalogAsync, ListFlowsAsync, GetFlowAsync, CreateFlowAsync, UpdateFlowAsync, DeleteFlowAsync, UploadFlowJsonAsync, PublishFlowAsync, DeprecateFlowAsync, ListFlowResponsesAsync, GetEncryptionKeyStatusAsync, SetEncryptionKeyAsync, GetAccountEventsAsync, ListSandboxSessionsAsync, CreateSandboxSessionAsync |
Validate |
PostAsync, LengthAsync, MediaAsync, SubredditAsync |
Analytics |
OverviewAsync, TimeSeriesAsync, TopPostsAsync, LabelsAsync, PostsTableAsync, PostingStreakAsync, DemographicsAsync, InboxAsync, CollectAsync, DecayAsync, FrequencyAsync, TimelineAsync, ChangesAsync, CollectPostAsync, NativePostsAsync |
Ads |
ListAsync, ExternalAsync, BoostableAsync, ConnectionsAsync, SourcesAsync, AuthorizeMetaAsync, DeleteConnectionAsync, BoostAsync, CreateAsync, RefreshAsync, SetStatusAsync, DeleteAsync, BulkSetStatusAsync, AudiencesAsync, CreateAudienceAsync, GetAudienceAsync, UpdateAudienceAsync, DeleteAudienceAsync, AddAudienceUsersAsync, SearchTargetingAsync, EstimateReachAsync, InsightsAsync, AdInsightsAsync, LeadFormsAsync, CreateLeadFormAsync, GetLeadFormAsync, ArchiveLeadFormAsync, LeadsAsync, LeadsFeedAsync, LeadPagesAsync, SubscribeLeadPageAsync, UnsubscribeLeadPageAsync |
Ads |
ListAsync, ExternalAsync, BoostableAsync, ConnectionsAsync, SourcesAsync, ProvidersAsync, AuthorizeAsync, DeleteConnectionAsync, BoostAsync, CreateAsync, RefreshAsync, SetStatusAsync, DeleteAsync, BulkSetStatusAsync, AudiencesAsync, CreateAudienceAsync, GetAudienceAsync, UpdateAudienceAsync, DeleteAudienceAsync, AddAudienceUsersAsync, AddAudienceCompaniesAsync, SearchTargetingAsync, EstimateReachAsync, InsightsAsync, AdInsightsAsync, LeadFormsAsync, CreateLeadFormAsync, GetLeadFormAsync, ArchiveLeadFormAsync, LeadsAsync, LeadsFeedAsync, LeadPagesAsync, SubscribeLeadPageAsync, UnsubscribeLeadPageAsync, GoalsAsync, ReachFrequencyAsync, CreateReachFrequencyAsync, GetReachFrequencyAsync, ReserveReachFrequencyAsync, CancelReachFrequencyAsync, PartnershipCreatorsAsync, RequestPartnershipAsync, RevokePartnershipAsync, AccountActivityAsync, LabelsAsync, CreateLabelAsync, UpdateLabelAsync, DeleteLabelAsync, ApplyLabelAsync, StudiesAsync, CreateStudyAsync, GetStudyAsync, DeleteStudyAsync, IosCampaignLimitsAsync, HighDemandPeriodsAsync, CreateHighDemandPeriodAsync, DeleteHighDemandPeriodAsync, ValueRuleSetsAsync, CreateValueRuleSetAsync, DeleteValueRuleSetAsync, BidPricingAsync, SupplyForecastAsync, ConversionRulesAsync, CreateConversionRuleAsync, ConversionRuleAsync, UpdateConversionRuleAsync, DeleteConversionRuleAsync, AttachConversionRuleAsync, DetachConversionRuleAsync, ConversionMetricsAsync, SendConversionEventsAsync, UploadConversionsAsync, SendPixelConversionsAsync, ConversionBatchesAsync, PixelsAsync, CreatePixelAsync, PixelAsync, UpdatePixelAsync, SharePixelAsync, PixelStatsAsync, EventMatchQualityAsync, CustomConversionsAsync, CreateCustomConversionAsync, CustomConversionAsync, UpdateCustomConversionAsync, DeleteCustomConversionAsync |
Media |
LimitsAsync, PresignAsync, CompleteAsync, UploadDirectAsync, GenerateAltTextAsync, FileUrlAsync |
Activity |
ListAsync |
Ads |
ListAsync, ExternalAsync, BoostableAsync, ConnectionsAsync, SourcesAsync, AuthorizeMetaAsync, DeleteConnectionAsync, BoostAsync, CreateAsync, RefreshAsync, SetStatusAsync, DeleteAsync, BulkSetStatusAsync, AudiencesAsync, CreateAudienceAsync, GetAudienceAsync, UpdateAudienceAsync, DeleteAudienceAsync, AddAudienceUsersAsync, SearchTargetingAsync, EstimateReachAsync, InsightsAsync, AdInsightsAsync, LeadFormsAsync, CreateLeadFormAsync, GetLeadFormAsync, ArchiveLeadFormAsync, LeadsAsync, LeadsFeedAsync, LeadPagesAsync, SubscribeLeadPageAsync, UnsubscribeLeadPageAsync |
Media |
LimitsAsync, PresignAsync, CompleteAsync, UploadDirectAsync |
GoogleBusiness |
GetLocationAsync, UpdateLocationAsync, GetAttributesAsync, UpdateAttributesAsync, GetMenusAsync, ReplaceMenusAsync, GetServicesAsync, ReplaceServicesAsync, ListMediaAsync, AddMediaAsync, DeleteMediaAsync, ListPlaceActionsAsync, CreatePlaceActionAsync, UpdatePlaceActionAsync, DeletePlaceActionAsync, GetVerificationOptionsAsync, StartVerificationAsync, CompleteVerificationAsync, GetPerformanceAsync, GetSearchKeywordsAsync, AssignAsync |
Blogs |
ListBlogsAsync, ListArticlesAsync, GetArticleAsync, CreateArticleAsync, UpdateArticleAsync, DeleteArticleAsync, ListProductsAsync, UpdateProductAsync |
Queue |
ListSlotsAsync, CreateSlotAsync, UpdateSlotAsync, DeleteSlotAsync, NextAsync, PreviewAsync |
ConnectSessions |
CreateAsync, GetAsync |
Webhooks |
ListAsync, CreateAsync, UpdateAsync, DeleteAsync, TestAsync, DeliveriesAsync, GetDeliveryAsync, RedeliverAsync |
Logs |
ListAsync |
Automations |
ListAsync, CreateAsync, StatsAsync, GetAsync, UpdateAsync, DeleteAsync, ToggleAsync, ListVersionsAsync, GetVersionAsync, RestoreVersionAsync, ListRunsAsync, GetRunAsync |
Designs |
ListAsync, CreateAsync, GetAsync, UpdateAsync, DeleteAsync, ListVersionsAsync, RestoreVersionAsync, DuplicateAsync, ExportAsync, BulkCreateAsync, ListPostsAsync, TextToSlidesAsync, FromPostAsync |
Fonts |
ListAsync, UploadAsync, DeleteAsync |
VideoEdits |
OpsAsync, ListAsync, CreateAsync, GetAsync |
Validate checks a draft, its length, or a media URL against platform rules without creating
anything; it needs the posts scope.
var check = await client.Validate.PostAsync(new ValidatePostOptions
{
Content = "Hello from the SDK",
Platforms = new List<string> { Platforms.Twitter, Platforms.LinkedIn },
});
foreach (var platform in check.Platforms.Where(p => !p.Ready))
{
Console.WriteLine($"{platform.Platform}: {string.Join(", ", platform.Issues)}");
}
Contacts needs the inbox scope too, except ConversationAnalyticsAsync, which needs analytics. Inbox needs an API key with the inbox scope; the calls that act on the platform as the account
(EditCommentAsync, LikeAsync, UnlikeAsync, RepostAsync, UnrepostAsync, BookmarkAsync, UnbookmarkAsync, VoteAsync, PinAsync, UnpinAsync, ReactAsync,
StartConversationAsync, SetTypingAsync, HandoverAsync, a reply with media or quick replies, and deleting our
own reply) need publish as well. Ads needs the ads scope, and the calls
that spend money (BoostAsync, CreateAsync, SetStatusAsync, DeleteAsync and BulkSetStatusAsync)
need publish as well. Anything created starts paused unless Paused = false, so nothing spends
until it is resumed. Audiences take the ad platform’s own ids plus a connectionId, and are read
live rather than stored.
Media uploads a file straight to storage with the posts scope: UploadDirectAsync presigns,
streams the file, and completes in one call, or drive the three steps yourself. Pass a Stream
of known length so a large video is never buffered in memory; PresignOptions adds the optional
FolderId, Origin, BrandRole, BrandVoiceId and PersonConsent.
await using var file = File.OpenRead("launch.mp4");
var media = await client.Media.UploadDirectAsync("9b2f6c1e-…", "launch.mp4", "video/mp4", file);
Files on posts
CreatePostOptions.Files and UpdatePostOptions.Files take up to five PostFiles, stored in
the workspace library and attached to the first content block. The SDK picks the route: files at
or under the multipart ceiling travel in one multipart/form-data request to the post endpoint;
anything larger is uploaded directly first and attached as media. Either way the result is the
same post.
using var video = PostFile.FromPath("launch.mp4", "video/mp4");
var post = await client.Posts.CreateAsync(new CreatePostOptions
{
WorkspaceId = "9b2f6c1e-…",
Content = new List<PostContent> { new("Shipped!") },
Accounts = accountIds,
Files = new List<PostFile> { video },
});
Upload limits
Media.LimitsAsync answers what the account may upload: MaxFileBytes is the largest file by any
route (it grows with connected accounts, or with the Large Uploads add-on), MultipartMaxFileBytes
is what a multipart request carries per file, and NextTier is the ceiling more accounts would
unlock. A file over the limit answers 413 with the code file_too_large; the FoPostException
carries the status and the body, so max_file_bytes is one read away.
var limits = await client.Media.LimitsAsync("9b2f6c1e-…");
Console.WriteLine($"Up to {limits.MaxFileBytes} bytes per file");
try
{
await client.Posts.CreateAsync(options);
}
catch (FoPostException error) when (error.Status == 413)
{
var max = (long)error.Body!["max_file_bytes"]!;
}
The API has more endpoints than the SDK wraps — analytics, webhooks, automations, and
communities among them. RequestAsync reaches any of them with the same auth, retries, and error
handling:
var overview = await client.RequestAsync(
HttpMethod.Get,
"/v1/analytics/overview",
query: new Dictionary<string, object?> { ["workspace_id"] = "9b2f6c1e-…" });
The full surface is documented in the
API collection.
Designs, fonts and video edits
Designs, Fonts and VideoEdits need the posts scope. Designs.TextToSlidesAsync,
Media.GenerateAltTextAsync and any video edit operation whose UsesAi is true spend AI
balance and need ai as well. A design’s document (its pages and layers) is passed through as
given: send a dictionary or a JsonNode, and read it back as Design.Document.
var design = await client.Designs.CreateAsync(new CreateDesignOptions
{
WorkspaceId = "9b2f6c1e-…",
Kind = DesignKinds.Post,
Name = "Launch card",
});
var export = await client.Designs.ExportAsync(design.Id, new ExportDesignOptions { Format = DesignExportFormats.Png });
var font = await client.Fonts.UploadAsync("9b2f6c1e-…", "fonts/Brand-Bold.woff2",
new UploadFontOptions { Family = "Brand", Weight = 700 });
var job = await client.VideoEdits.CreateAsync(mediaId, new[]
{
new VideoEditOperation(VideoEditOps.Trim, new Dictionary<string, object?> { ["startSec"] = 2, ["endSec"] = 12 }),
});
job = await client.VideoEdits.GetAsync(job.Id); // queued, running, succeeded or failed
A video edit runs in the background, so read it back with GetAsync until its Status is
succeeded or failed. Media.FileUrlAsync returns a short-lived signed URL for a library file;
that endpoint takes a session rather than an API key, so it needs BearerToken.
Chatbots and the inbox
The chat adapter turns the FoPost inbox into one send/receive channel for a chatbot
framework. It ships in the TypeScript and Python SDKs. There is no dedicated adapter here and no
API change behind it, so the same loop is three pieces with this client:
- Verify the
inbox.message_received webhook. The payload is ids only, on purpose, so
nothing a customer wrote sits in your logs. The signing scheme
is HMAC-SHA256 over {timestamp}.{body}, refused past a five minute tolerance.
- Read the item back with
client.Inbox.ListAsync(new ListInboxOptions { … }), filtered to the payload’s
accountId and matched on its itemId.
- Answer with
client.Inbox.ReplyAsync(item.Id, text), or open a thread with
client.Inbox.StartConversationAsync(…).
Reading needs the inbox scope; answering needs publish as well.
Contributing
Issues and pull requests are welcome at
fopost/fopost-dotnet.
dotnet build
dotnet test
dotnet pack src/FoPost/FoPost.csproj -c Release
License
MIT
Google Ads
Ads, audiences, and insights are on client.Ads and dispatch by connection. What only
Google has is under client.Ads.Google:
var scope = new GoogleAdsScope { ConnectionId = "c4d5e6f7-…", CustomerId = "1234567890" };
var strategies = await client.Ads.Google.BidStrategiesAsync(scope);
await client.Ads.Google.CreateBidStrategyAsync(new CreateGoogleBidStrategyOptions
{
WorkspaceId = "7d2b8c11-…",
ConnectionId = "c4d5e6f7-…",
CustomerId = "1234567890",
Name = "Target CPA",
Type = GoogleBidStrategyTypes.TargetCpa,
TargetMinor = 1500,
});
Also AdScheduleAsync and SetAdScheduleAsync, LocalServicesLeadsAsync, the conversion
methods, and QueryAsync for a raw read-only GAQL SELECT. Changes need the publish scope as well as ads;
CustomerId has to name an account the connection’s grant reaches.
评论