Skip to content

Twitter scheduler CLI

This Twitter scheduler CLI tutorial shows how to build a small typescript command-line tool that loads a connected account, drafts or polishes tweets with AI, picks a smart posting time, and schedules the result through an sdk. It is a practical automation example for people who want the workflow in code they can read and change, rather than a dashboard they cannot inspect.

What this CLI does and who it is for

This Twitter scheduler CLI does five things in sequence. It loads your connected Twitter account and recent posts, asks whether you want AI drafting from scratch or polishing of your own draft, generates three options, picks a posting time that avoids clustering, and schedules the chosen tweet. The result is a twitter scheduler you can run from a terminal, put on a cron schedule, or adapt into a broader automation workflow. The tutorial assumes you are comfortable opening a terminal and running npm install; you do not need deep typescript experience to follow the steps.

Build your own vs use a dashboard scheduler

Building your own scheduler makes sense when you want control over prompts and voice, want to avoid a recurring dashboard subscription for a task you touch briefly each day, want the tool wired into your own workflow such as cron, CI, a Slack command or a keybinding, or simply want transparency about the code that publishes on your behalf. If those priorities do not apply and a visual interface is preferable, a dashboard scheduler is the simpler choice. This tutorial is for the first group: people who value a small, readable cli and an sdk call they can inspect.

Prerequisites and input contract

You need Node.js 20 or newer, a connected Twitter account, an API key for the posting service, and an AI provider key. The example uses Google Gemini for short structured output, but the same pattern works with other providers by changing the model setup. Create a .env file with POSTING_API_KEY and AI_API_KEY, and never commit that file. Before starting, confirm Node is installed by running node --version in your terminal. If any key is missing, the script will fail when it tries to create a client or call the model, so check the environment first.

Project setup and dependencies

Create a project folder, initialize npm, and install the prompt library, AI sdk, and zod for structured output validation, plus typescript, tsx and Node types as development dependencies. tsx lets you run typescript directly without a build step. Add a start script that runs the entry file with the .env file loaded, then run npm start to launch the cli. The terminal experience uses a spinner while loading, a select menu for the writing mode, text inputs for your day or draft, and an intro and outro so the flow is clear at each step.

SDK setup

The script creates a client with your API key and a base URL, then creates an AI model from your AI provider key. Keep those values in environment variables rather than hard-coding them. The client is used for every posting call, and the model is used for drafting and for choosing a time. If you swap AI providers later, you change the model creation and import while keeping the rest of the flow the same.

Load connected account and recent posts

Before scheduling anything, the script loads two things in parallel: the list of connected integrations and your recent posts on Twitter, limited to 20 and sorted descending. It finds the integration whose platform is twitter and extracts its id as the accountId for later calls. Recent post content is collected so the AI can match your voice and avoid repeating themes or phrasing. If no Twitter integration is found, the script stops and tells you to connect Twitter first; that failure check prevents a scheduling call with no valid target.

Two tweet-writing modes

The first mode asks about your day and generates three distinct tweet ideas. A zod schema forces the model to return exactly three strings, each at most 280 characters, so the script can rely on the shape. The prompt asks for casual first-person writing with no hashtags and no emojis, and includes your recent tweets as examples to avoid. The second mode takes a draft you wrote and polishes it into three variants that preserve meaning, do not invent new ideas, and differ in line breaks and tightness. In both modes you choose the final tweet from the three options, which keeps a human decision in the loop.

Smart posting time selection

To avoid stacking posts at the same time, the script first lists already-scheduled posts and collects their scheduledFor values. It then asks the model to pick a time strictly in the future within the next 48 hours, preferring weekday peaks of 13:00 to 16:00 UTC or 22:00 to 01:00 UTC, staying at least 4 hours from any already-scheduled post, and avoiding :00, :15, :30 and :45 minutes. The model must return an ISO datetime with offset in the scheduledFor field. Treat these as starting rules and adjust the windows and spacing for your own audience and timezone.

Schedule the tweet

Scheduling is a single create call. You pass content, a platforms array containing an object with platform set to twitter and the accountId you loaded earlier, and either scheduledFor for a future post or publishNow set to true for immediate publishing. The response includes a status and a postId that you can log so you can find the post later. To cross-post, add another entry to platforms with a different platform and its accountId; the same call, content and scheduling fields apply. Always verify the returned status before treating the post as scheduled, and check that scheduledFor is in the future before calling create.

Wiring the main flow

The main function ties the steps together in order: load the account, ask for the writing mode, draft or polish, ask when to post, then schedule. If any step returns nothing, the flow stops instead of calling the API with incomplete data. A top-level catch logs the error message and exits with a non-zero status, which makes failures visible in cron or CI. That structure keeps the cli easy to extend: each step is a small function you can test or replace independently.

Running the CLI

Run npm start from the project folder. The cli walks you through picking a mode, entering your day or draft, choosing one of three generated tweets, and choosing a time. When it finishes, it logs the status and postId from the create call. If you see an error about a missing key, check your .env file; if you see a message about no connected account, connect Twitter and run again; if the model returns an unexpected shape, the zod validation will reject it rather than passing bad data to the scheduler.

MCP customization

An mcp server exposes the posting API as typed tools inside an AI assistant, so you can ask the assistant to customize the script with knowledge of the actual calls. In Claude Code you add the hosted server over HTTP transport with an Authorization header carrying your API key. In Claude Desktop you add the server URL and the same header to the desktop configuration file, then restart the app. Once connected, you can ask for changes such as a platform flag, a list of upcoming scheduled posts, or a thread mode, and the assistant can use the real tool definitions instead of guessing the API shape.

Extensions

This single-file script is a starting point you can fork in several directions. Add entries to platforms to cross-post to multiple networks in one call. Replace AI drafting with tweets read from a markdown file or spreadsheet while keeping the same scheduling call. Schedule the script to empty a backlog of prepared posts at well-spaced times. Add a thread mode that schedules several posts in sequence, or expose the script as a Slack slash command for a team. Each extension reuses the same load, draft, pick-time and schedule structure.

Wrap up

The value of this approach is a small surface area: the sdk handles platform-specific work such as authentication, rate limits and format conversions, while your script owns the prompts, timing logic and workflow shape. Keep the failure checks in place, validate AI output with a strict schema, and confirm the returned status and postId after every create call. With those pieces in place, you have a twitter scheduler cli that is easy to read, easy to change, and easy to run from your terminal whenever you need it.

SDK field map for the scheduler flow
FieldTypeRequiredRole
integrationsarrayReturned by list callConnected social accounts to search for Twitter
postsarrayReturned by list callRecent posts used for voice and duplicate avoidance
contentstringRequired on createTweet text to schedule or publish
platformsarrayRequired on createTargets; each entry has platform and accountId
accountIdstringRequired per targetID of the connected Twitter account
scheduledForstring (ISO datetime with offset)Optional; alternative to publishNowFuture time to schedule the post
publishNowbooleanOptional; alternative to scheduledForPublish immediately when scheduledFor is not set
postIdstringReturned on createIdentifier of the created post
statusstringReturned on createResult status to log and verify

Field names and types preserved from source SDK example; illustrative only.

Failure matrix and checks
FailureCheckAction
No Twitter account connectedintegrations list has no twitter entryStop and prompt to connect Twitter before scheduling
Missing API or AI keyPOSTING_API_KEY or AI_API_KEY emptyFix .env before running; do not hard-code keys
AI output wrong shapeZod schema: 3 tweets, max 280 chars; scheduledFor ISO datetimeReject output and regenerate or ask user to retry
Time in past or beyond 48 hoursscheduledFor must be future and within 48 hoursPick a new time before calling create
Time too close to scheduled postAt least 4 hours from existing scheduledFor valuesChoose a different slot
Create call failsCheck returned status and errorLog error, exit non-zero, do not assume post was scheduled

Based on source flow; no live testing claimed.

Frequently asked questions

What do I need before building this Twitter scheduler CLI?

You need Node.js 20 or newer, a connected Twitter account, an API key for the posting service, and an AI provider key. The script reads POSTING_API_KEY and AI_API_KEY from a .env file.

How do the two tweet-writing modes differ?

The AI-from-scratch mode asks about your day and returns 3 tweets, each at most 280 characters. The polish mode keeps your meaning and returns 3 reshaped variants. Both use a strict structured-output schema so the script can validate the shape before you choose one.

What rules does the smart posting time use?

The example asks the model to choose a time strictly in the future within 48 hours, preferring 13:00 to 16:00 UTC or 22:00 to 01:00 UTC on weekdays, at least 4 hours from already-scheduled posts, and avoiding :00, :15, :30, and :45 minutes. Adjust those rules for your audience.

What happens if I do not provide scheduledFor?

If scheduledFor is set, the post is scheduled for that ISO datetime. If it is not set, the example sets publishNow to true so the post publishes immediately. The platforms array determines the targets, each with a platform and accountId.

How do I cross-post to another platform?

Add another entry to the platforms array with that platform name and its accountId. The same create call then targets multiple platforms, using the same content and scheduling fields.

What if no Twitter account is connected?

The script stops with a message telling you to connect Twitter first. No scheduling call is made until a Twitter integration is found.

Start script in package.json
{
  "scripts": {
    "start": "tsx --env-file=.env tweet.ts"
  }
}
Add MCP server in Claude Code
claude mcp add social-api --transport http --header "Authorization: Bearer YOUR_API_KEY" {{MCP_BASE_URL}}/mcp
MCP client configuration placeholder
{
  "mcpServers": {
    "social-api": {
      "url": "{{MCP_BASE_URL}}/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_API_KEY"
      }
    }
  }
}