This morning my weekly long post on X failed with this:
403 {"detail":"This account cannot create Posts longer than 280 characters. Shorten the text,
or subscribe to X Premium to create longer Posts. A link counts as 23 characters and an emoji as 2.",
"status":403,"title":"Forbidden"}
The text was 1,931 characters, and the account has no Premium subscription. The API said so in the clearest way it could, with 403, not 400.
That status code is the interesting part. A naive fallback looks like if r.status_code == 403: post_as_thread(). But 403 is also what you get for a suspended app, missing write permission or a duplicate post. Retrying all of those as a thread would post 11 replies into the void, or hide the real problem. So the fallback has to be specific.
Disclosure: I run small data pipelines and AI-agent automations, including the X account this is from. The helper is in a public repo, linked below.
The helper
x_long_or_thread.py, the posting part:
def post(text, sleep=2.0):
s = OAuth1Session(*(os.environ[k] for k in
("X_API_KEY", "X_API_SECRET", "X_ACCESS_TOKEN", "X_ACCESS_TOKEN_SECRET")))
r = s.post("https://api.x.com/2/tweets", json={"text": text})
if r.status_code == 201:
return [r.json()["data"]["id"]]
if not (r.status_code == 403 and "longer than 280" in r.text):
raise RuntimeError(f"X said {r.status_code}: {r.text[:200]}")
ids, prev = [], None
for part in split_thread(text):
body = {"text": part}
if prev:
body["reply"] = {"in_reply_to_tweet_id": prev}
r = s.post("https://api.x.com/2/tweets", json=body)
if r.status_code != 201:
raise RuntimeError(f"thread stopped after {len(ids)} posts: {r.status_code}")
prev = r.json()["data"]["id"]
ids.append(prev)
time.sleep(sleep)
return ids
Two decisions in there:
- Fall back only on the length error. Matching on the message text is brittle if X rewords it, but the failure mode is safe: you get an exception instead of a wrong thread. I'd rather fix a string than explain 11 stray posts.
- If the thread breaks halfway, say how far it got. A half-posted thread is the worst state to be in silently. The error says "stopped after 4 posts", so you know whether to delete or continue.
Counting length the way X does
X's error message itself gives the two rules that matter most: a link counts as 23 characters, an emoji as 2. Python's len() knows neither.
URL = re.compile(r"https?://\S+")
def x_len(text):
n, pos = 0, 0
for m in URL.finditer(text):
n += _weigh(text[pos:m.start()]) + 23
pos = m.end()
return n + _weigh(text[pos:])
def _weigh(s):
return sum(2 if ord(c) >= 0x1100 else 1 for c in s)
This is an approximation. X's real counter (the open-source twitter-text library) has a full table of weighted Unicode ranges. For English and German text with the occasional emoji, the shortcut above has matched for me; for CJK-heavy text, use the real library.
| Text | len() |
X-weighted |
|---|---|---|
| A 300-character URL alone | 300 | 23 |
Most posts get zero likes. |
26 | 26 |
Done 🚀 |
6 | 7 (emoji as 2) |
| My long post from this morning | 1,931 | 1,920 |
Splitting without wrecking the structure
My first version split on paragraphs, then sentences, then words. The dry run showed the problem right away: a bullet list got cut mid-line (29% got zero | likes, median 135), and section headings ended up as the last line of the previous post.
The fix was two rules:
- Split levels: paragraphs, then lines, then sentences, then words. Each piece remembers which separator it had, so line breaks inside a list survive.
-
A line starting with
â–¸or#always opens a new post. Headings belong at the top.
LEVELS = [("\n\n", "\n\n"), ("\n", "\n"), (r"(?<=[.!?])\s+", " "), (" ", " ")]
def split_thread(text, limit=280, number=True):
reserve = 6 if number else 0 # room for " 10/12"
out, cur = [], ""
for piece, joiner in _units(text.strip(), limit - reserve):
heading = piece.startswith(("â–¸", "#"))
cand = f"{cur}{joiner}{piece}" if cur else piece
if cur and (heading or x_len(cand) > limit - reserve):
out.append(cur)
cur = piece
else:
cur = cand
if cur:
out.append(cur)
if number and len(out) > 1:
out = [f"{p} {i}/{len(out)}" for i, p in enumerate(out, 1)]
return out
Run it without --post and it only prints the split with each part's weighted length. On this morning's text it made 11 parts, the longest at 273. Every list item stayed whole and every heading started a post. (In the end I posted a hand-written 6-post version instead: a thread written as a thread reads better than a split article. The helper is for scheduled jobs where nobody is around to rewrite.)
Another free-tier surprise from the same day
My search query used min_faves:20 to find popular posts. The API answered:
Reference to invalid operator 'min_faves'. Operator is not available
in current product or product packaging.
So some search operators depend on your API plan, and the error tells you directly. I removed the operator and filtered on public_metrics.like_count in Python instead. It costs more reads, because you fetch posts you'll discard, but it works on any plan.
Takeaways
- Treat 403 as many different errors. Branch on the specific one you can handle, raise on the rest.
- Count length with X's weights (URLs 23, emoji 2), not
len(). - Split on structure first (paragraphs, lines), sentences later, words last.
- Dry-run every split before posting. My first version looked fine in tests and broke on the first real text with a list in it.
Question: when your scheduled job hits a plan limit like this, do you fall back automatically, or stop and alert a human? I went with "fall back only on one exact error", but I can see the case for always stopping.
Top comments (0)