Monitoring Twitter (X) via API: Account Activity API, Polling and Webhooks

By Sarah Wong•17 min read
TL;DR
  • Account Activity API is being deprecated on docs.x.com; its replacement is the X Activity API (XAA), with webhook or stream delivery.
  • XAA bills post.create at $0.005 per event; post.delete is not billed; self-serve accounts get up to 1,500 subscriptions.
  • XAA mentions, replies, quotes, reposts and likes are private events: the watched user must authorize your app via OAuth 2.0.
  • Polling advanced_search on TwitterAPI.io: $0.15 per 1,000 posts, $0.00015 minimum per check, $6.48 a month per query at 60 s.
  • A TwitterAPI.io filter rule + webhook (/oapi/tweet_filter/add_rule) runs the same query for you and pushes matches; each check is billed like a poll.
  • Per post returned the named rate cards differ about 33x: $5 per 1,000 post reads on X pay-per-use vs $0.15 per 1,000 tweets on TwitterAPI.io.

Monitoring a Twitter (X) account, a brand mention, or a keyword in close-to-real-time is one of the most common production uses of the X API. Marketing teams set up brand-mention alerts; trading desks watch for market-moving posts; brand-safety teams scan for crisis signals; analytics teams capture timelines for downstream analysis. Each use case has a different latency requirement and a different cost profile, and the architectural choice you make at the start (polling, push via webhook, or a persistent stream) locks those properties in for the life of the system.

This guide starts with the question most people searching for the Account Activity API actually have: is it still the way to get X events pushed to you, what does it cost, and what replaces it. Then it compares X's push route with polling and with a webhook filter rule on TwitterAPI.io, gives one runnable Python script that runs the same query in both polling and webhook mode, and works through the monthly cost for 1, 25, 100 and 1,000 watched accounts on both named rate cards.

Every X fact below comes from docs.x.com pages fetched while writing (Account Activity API, X Activity API, V2 Webhooks, Filtered Stream, pay-per-usage pricing); every TwitterAPI.io fact comes from docs.twitterapi.io and the pricing page. They are listed in the sources at the end.

Polling floor per monitored query

$6.48/month at a 60-second interval

01 — Section

Account Activity API in 2026: status, limits and cost vs polling vs a webhook rule

Status. The Account Activity API (AAA) introduction on docs.x.com opens with a warning: the API "is being deprecated", and developers should use the X Activity API (XAA) "for real-time user activity delivery going forward". AAA still documents its V2 endpoints (POST /2/account_activity/webhooks/:webhook_id/subscriptions/all and friends), but new builds should target XAA.

What AAA did, and its limits. AAA sends every activity of a subscribed account (posts, deletes, @mentions, replies, reposts, quotes, likes, follows, blocks, mutes, DMs) to one registered webhook. Subscribing a user requires OAuth 1.0a three-legged consent from that user, so it only ever covered accounts that authorized your app. The tier table on the same page lists Pay Per Use at 3 unique subscriptions and 1 webhook, Enterprise at 5,000+ subscriptions and 5+ webhooks, and notes that posts delivered through AAA count toward the monthly Post cap. The pricing page has no separate AAA line.

What XAA does instead. XAA (POST /2/activity/subscriptions, delivery by webhook or the persistent GET /2/activity/stream) subscribes to individual event types per user_id: post.create, post.delete, post.mention.create, post.reply.create, post.quote.create, post.repost.create, like.create, follows, profile updates, DMs, Spaces and more. The docs split them into public and private events. Post creation and deletion and profile updates are public: you can subscribe to them for any public account. Mentions, replies, quotes, reposts and likes are private and need the watched user to authorize your app with OAuth 2.0 (tweet.read scope for the post events). Self-serve accounts can hold up to 1,500 subscriptions (Enterprise 75,000, Partner 150,000). XAA filters by user, not by keyword; for keywords X points to Filtered Stream.

What XAA costs. The Webhook events table on the X pay-per-usage pricing page bills each delivered event: post.create $0.005, post.delete not billed, follow.follow $0.010, profile.update.* $0.005, dm.received $0.010. The XAA page adds that every delivered post event (create, delete, mention, reply, quote, repost) is billed as a Post. Events are deduplicated within a 24-hour UTC window, and pay-per-usage is capped at 3 million Post reads per monthly billing cycle, with Enterprise above that.

The four routes side by side. Prices are from the X pay-per-usage rate card (docs.x.com) and the TwitterAPI.io pricing page.

RouteWhat it can watchWhat you needCost basis
X Account Activity API (being deprecated)All activity of accounts that authorized your appDeveloper account, app, OAuth 1.0a per user, webhook with CRC; Pay Per Use: 3 subscriptions, 1 webhookDelivered posts count toward the Post cap
X Activity API (XAA)Posts and deletes of any public account by user_id; mentions, replies, likes only with the user's OAuth consentDeveloper account, app, OAuth, webhook or persistent stream$0.005 per post.create event
Polling search on TwitterAPI.ioAny public accounts or keywords in X search syntaxAn API key; no X account$0.15 per 1,000 posts returned; $0.00015 minimum per check
Filter rule + webhook on TwitterAPI.ioThe same query, pushed to your endpointAn API key and an HTTPS endpoint that answers within 1 sEach rule check billed like a poll, plus $0.00015 per post

The short answer for the common searches. If you want to monitor X accounts you do not control, including mentions of a brand or a competitor's replies, AAA never covered that and XAA covers only the public part (their own posts and deletes). Keyword monitoring is a Filtered Stream or search problem on X, and a search or filter-rule problem on TwitterAPI.io. If the accounts are your own users who log in with X, XAA is the native fit.

02 — Section

One query, two delivery modes: runnable polling and webhook code on TwitterAPI.io

The script below runs one X search query in either mode, so you can start with polling, check what the query returns, and switch to push without rewriting anything. Save it as monitor.py, put your key in TWITTERAPI_IO_KEY, and pip install requests flask.

Mode poll. One GET /twitter/tweet/advanced_search call with queryType=Latest and a since_time operator (unix seconds) returns only posts newer than the last run, in the top-level tweets array, with has_next_page and next_cursor for busy windows. The script re-reads one minute of overlap and de-duplicates on id, so a post indexed just after a run starts is not lost. Run it from cron every minute (* * * * * python3 monitor.py poll). Cost: $0.00015 for an empty check, $0.00015 per post returned, so $6.48 a month for the query at 60 seconds or $1.30 at 5 minutes.

Mode rule. Registers the same query with POST /oapi/tweet_filter/add_rule (tag, value up to 255 characters, interval_seconds from 0.05 to 86,400, default 60). The docs state that a new rule is not active until you call POST /oapi/tweet_filter/update_rule with is_effect: 1, which the script does. You set the callback URL for your rules in the dashboard. Billing follows the checks: each evaluation of the rule costs at least $0.00015 and matched posts $0.00015 each, so at the same interval a rule costs about the same as polling.

Mode serve. The receiver. Each push is a JSON POST with event_type (tweet; the dashboard's test button sends test_webhook_url), rule_id, rule_tag, rule_value, timestamp in milliseconds and a tweets array of the same objects advanced_search returns. The request carries your own API key in an x-api-key header and has no HMAC signature, so compare that header in constant time and answer 401 otherwise. The push times out after one second and is not retried: the receiver answers 200 first and does the work on a background thread.

How to choose between the two. Polling gives you every request and response in your own logs, a schedule you control, and nothing to host but a cron job. The rule removes the scheduler and pushes posts within the rule interval, at the cost of hosting an endpoint that stays fast and up. A sensible path is to tune the query in poll mode for a day, then move the same value into a rule if you need push. If a push is dropped (timeout or non-200), run one poll with a since_time from before the gap to backfill it.

python
"""monitor.py - watch X (Twitter) accounts or keywords, polling or webhook, same query.

  python3 monitor.py poll    # pull: run every 60 s from cron, prints new posts
  python3 monitor.py rule    # push: create + activate a filter rule (run once)
  python3 monitor.py serve   # push: webhook receiver; set its URL in the dashboard

pip install requests flask
"""
import hmac
import json
import os
import queue
import sys
import threading
import time

import requests

BASE = "https://api.twitterapi.io"
API_KEY = os.environ["TWITTERAPI_IO_KEY"]
HEADERS = {"X-API-Key": API_KEY}
QUERY = "from:NASA OR from:SpaceX OR from:ESA"  # X search syntax; max 255 chars for a rule
TAG = "space-watch"
STATE = "monitor-state.json"


def handle(tweet, via):
    author = (tweet.get("author") or {}).get("userName", "?")
    text = (tweet.get("text") or "").replace("\n", " ")[:120]
    print(f"[{via}] @{author}: {text} {tweet.get('url')}")  # swap for Slack, email, a DB


def poll():
    if os.path.exists(STATE):
        with open(STATE) as f:
            state = json.load(f)
    else:
        state = {"since_time": int(time.time()) - 300, "seen": []}
    started = int(time.time())
    seen = list(state["seen"])
    params = {"query": f"({QUERY}) since_time:{state['since_time'] - 60}", "queryType": "Latest"}
    for _ in range(5):  # page cap per run
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search", headers=HEADERS, params=params, timeout=30)
        r.raise_for_status()
        page = r.json()
        for t in page.get("tweets") or []:
            if t["id"] not in seen:
                seen.append(t["id"])
                handle(t, "poll")
        if not page.get("has_next_page") or not page.get("next_cursor"):
            break
        params["cursor"] = page["next_cursor"]
    with open(STATE, "w") as f:
        json.dump({"since_time": started, "seen": seen[-2000:]}, f)


def create_rule():
    rule = {"tag": TAG, "value": QUERY, "interval_seconds": 60}
    added = requests.post(f"{BASE}/oapi/tweet_filter/add_rule", headers=HEADERS, json=rule, timeout=30)
    added.raise_for_status()
    status, rule_id, msg = (added.json().get(k) for k in ("status", "rule_id", "msg"))
    if status != "success":
        sys.exit(f"add_rule failed: {msg}")
    # New rules start inactive: activate with update_rule (all fields required)
    rule.update({"rule_id": rule_id, "is_effect": 1})
    upd = requests.post(f"{BASE}/oapi/tweet_filter/update_rule", headers=HEADERS, json=rule, timeout=30)
    upd.raise_for_status()
    print("rule active:", rule["rule_id"], "- set your webhook URL in the dashboard")


def serve():
    from flask import Flask, request

    app = Flask(__name__)
    jobs = queue.Queue()
    seen = set()  # use Redis or a DB table in production

    @app.post("/x-webhook")
    def receive():
        # twitterapi.io sends your own API key in x-api-key (no HMAC signature)
        if not hmac.compare_digest(request.headers.get("x-api-key", ""), API_KEY):
            return "", 401
        jobs.put(request.get_data())
        return "", 200  # answer first: 1 s timeout, no retries

    def worker():
        while True:
            push = json.loads(jobs.get())
            if push.get("event_type") != "tweet":  # e.g. test_webhook_url
                continue
            for t in push.get("tweets") or []:
                if t["id"] not in seen:  # overlapping rules can repeat a post
                    seen.add(t["id"])
                    handle(t, "push")

    threading.Thread(target=worker, daemon=True).start()
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))


if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else "poll"
    {"poll": poll, "rule": create_rule, "serve": serve}[mode]()
03 — Section

Three architectural patterns — pick the right one before you write code

There are three architecturally distinct ways to monitor Twitter (X) in production. Picking one is the highest-leverage decision in a monitoring system; switching after you have shipped is more work than picking right the first time.

PatternLatencyWhat you operateBest for
1. Polling a search (pull)Your interval, typically 60 sA cron job or scheduled functionAccount lists, keywords, analytics, digests
2. Persistent stream (push)SecondsA long-running worker holding a connectionReal-time alerting where you already run a server
3. Webhook (push)Seconds to one rule intervalAn HTTPS endpoint that answers fastAlerts into serverless or event-driven systems

1. Polling. Periodically run a search for new posts from your accounts or keywords, de-duplicate against what you saw, and store or forward the new items. Freshness is limited by your interval; the logic and logs stay entirely on your side. On TwitterAPI.io this is advanced_search with a since_time window; on the official X API it is recent search.

2. Persistent stream. You register rules and keep one connection open while matching posts arrive. On TwitterAPI.io that is a filter rule plus the WebSocket at wss://ws.twitterapi.io/twitter/tweet/websocket; on X it is Filtered Stream for keywords or the XAA stream for per-user events.

3. Webhook. Same push semantics, but the provider calls your HTTPS endpoint, so there is no long-lived process on your side. On TwitterAPI.io that is a filter rule with a callback URL; on X it is XAA (or AAA while it lasts) with a registered webhook that must pass X's CRC challenge.

A simple decision rule: if a minute of delay is fine, poll. If you need push and do not want to run a worker, use a webhook. If you already run a server and want the lowest latency on a rule set, hold a stream.

04 — Section

The Twitter (X) API surface you'll use — endpoints, auth, and the official-vs-third-party choice

For each monitoring pattern, there is a specific subset of the API surface that gets used. Knowing the names up front saves time when you are debugging.

Polling endpoints. GET /twitter/tweet/advanced_search takes X search syntax; with from:<handle> since_time:<unix seconds> it returns only posts newer than the last one you saw, which makes it the polling endpoint in this guide. X equivalent: GET /2/tweets/search/recent. GET /twitter/user/info resolves a handle and reports suspended or missing accounts (X: GET /2/users/by/username/:username). GET /twitter/user/last_tweets returns the latest 20 posts of one account and is billed per post on the page, so use it for a one-off fetch rather than a recurring poll.

Push endpoints on TwitterAPI.io. POST /oapi/tweet_filter/add_rule, POST /oapi/tweet_filter/update_rule, GET /oapi/tweet_filter/get_rules and DELETE /oapi/tweet_filter/delete_rule manage rules; matches go to your webhook or to the WebSocket at wss://ws.twitterapi.io/twitter/tweet/websocket. For a fixed account list there is also POST /oapi/x_user_stream/add_user_to_monitor_tweet (Twitter Stream), which watches an account's posts, quotes, replies and reposts.

Push endpoints on X. POST /2/tweets/search/stream/rules plus GET /2/tweets/search/stream (Filtered Stream: 1,000 rules of up to 1,024 characters and 1 connection on pay-per-use), and POST /2/activity/subscriptions with GET /2/activity/stream or a registered webhook (XAA).

Authentication. TwitterAPI.io uses a single X-API-Key header, with no OAuth flow and no X developer account. The official X API needs a developer account and an app in a project; XAA private events and AAA subscriptions also need each watched user's OAuth consent, and webhooks must answer X's CRC challenge with an HMAC-SHA256 of the token.

Cost per post returned, on the named rate cards:

PathPer 1,000 posts returnedMinimum per callX developer account
Official X API, pay-per-usage (post read or post.create event)$5.00none listedRequired
TwitterAPI.io$0.15$0.00015Not required

Per post returned the gap is about 33x ($5 / $0.15). The TwitterAPI.io minimum matters for polling, because most checks find nothing; the cost section below puts both effects into monthly numbers.

05 — Section

Runnable Python — a timeline-polling monitor with engagement re-fetch

The full script at the end of this page is the single-account version of the polling pattern with engagement re-fetch. It polls advanced_search every 60 seconds with from:<handle> since_time:<unix seconds of the newest post seen>, de-duplicates against local state, appends new posts to JSONL, and schedules engagement re-fetches at T+15m, T+1h, T+6h and T+24h. Polling cost at this cadence is $6.48 a month per query (43,200 checks x $0.00015), plus $0.00015 for each new post returned and for each re-fetched ID. The search pattern is what keeps it that low: a check with nothing new returns 0 posts and costs the 15-credit minimum, whereas a last_tweets poll bills every post on the page (20 posts, $0.003 a call, about $130 a month at 60 seconds).

Handle check at startup. The script calls user/info once, so a suspended or missing account is flagged instead of polled. The poll itself needs only the handle.

Restart-safe state. It stores the next since_time (one second after the newest post seen) in a local file and also de-duplicates on the post id, so restarts do not replay posts. The first run is seeded with the current time, so it reports only posts published after you start it.

Engagement checkpoints. Re-reading likes and reposts at several points after first sight lets you measure how fast a post picks up engagement rather than relying on one final count. Events carry a kind field (new_tweet vs velocity_checkpoint) so downstream consumers can join them with one GROUP BY.

Change the target. Replace HANDLE = "elonmusk" with your account. For a watch list, join handles with OR in one query (from:a OR from:b) so the list shares one polling floor, as in the two-mode script above.

Alerting hook. The print("SPIKE: ...") line is where Slack, PagerDuty or email goes. The condition engagement > median * SPIKE_MULTIPLIER is a simple spike detector that does not fire on baseline noise; tune SPIKE_MULTIPLIER per account.

06 — Section

Persistent streams: when polling is not fast enough

Move from polling to a stream or webhook when one of these holds.

Latency matters more than a minute. Alerting products and trading workflows that act on a post within seconds.

Busy keywords. A keyword with many posts a minute makes each poll return full pages; a push rule hands you matches as they are found instead.

Deletions. Posts deleted within seconds can be gone before the next poll. On X, XAA's post.delete event is public and not billed, so a deletion record for a public account is a subscription away.

The trade-off. A stream needs a process that keeps a connection open: a process supervisor, reconnect logic, and monitoring of the monitor. It does not fit request-scoped serverless functions. The TwitterAPI.io WebSocket allows one connection per API key (a second connection takes over and the first is closed with code 4001), sends a ping event about every 20 seconds, and accepts one handshake per key every 5 seconds; X's Filtered Stream sends a keep-alive every 20 seconds and expects you to reconnect if none arrives.

Rule design. On both sides a rule is search-operator syntax: from:NASA OR from:SpaceX, or "product launch" -is:retweet. Prototype the query with a poll first, because a poll shows you exactly what the query returns before you depend on push.

Reconnection and gap fill. After any disconnect, back off, reconnect, and run one search over the gap with since_time set to the last post you received. That backfill step is the difference between a stream that is almost always live and one you can deploy.

07 — Section

Webhooks: the push pattern without a persistent worker

If you want push semantics but do not want to run a persistent worker, a webhook is the fit: each delivery is one HTTP POST to your endpoint, your handler answers and exits. The two-mode script above contains a complete receiver.

Webhook detailTwitterAPI.io filter ruleX Activity API / AAA
What triggers a deliveryPosts matching your search query, checked every interval_secondsEvents of subscribed user_ids
Endpoint verificationNone; the push carries your API key in x-api-keyCRC challenge on registration and hourly (HMAC-SHA256)
Request authenticityCompare x-api-key to your keyX-Twitter-Webhooks-Signature-OAuth2 header over the raw body
Timeout and retries1 second, no retriesRetry and recovery support (V2 Webhooks docs)
CostEach rule check $0.00015 minimum, plus $0.00015 per postPer delivered event, $0.005 for post.create

Receiver rules for TwitterAPI.io pushes. Answer 200 within one second and do the slow work after responding, on a queue or background thread. De-duplicate on the post id, because two overlapping rules can deliver the same post. Log the raw body for the first day so you see the exact payload before you depend on a field. Host it somewhere that stays warm (a small VM, Railway, Render, or a serverless function with minimum instances), since a cold start can exceed the one-second budget.

Receiver rules for X webhooks. Implement the CRC GET handler before registering, verify the signature header on every POST, and expect duplicates when two subscribed users interact: AAA documents one event per subscribed user, identified by for_user_id.

08 — Section

Cost at scale: 1 to 1,000 watched accounts on both rate cards

Both rate cards charge for posts, but they differ in what an empty check costs. X pay-per-usage charges per resource returned and lists no per-call minimum, and XAA charges per delivered event. TwitterAPI.io charges $0.15 per 1,000 posts plus a $0.00015 minimum per call, so the polling floor dominates small watch lists and the per-post rate dominates large ones.

Worked example. Each watched account posts 10 times a day (300 a month; an illustrative volume, change it to yours). On TwitterAPI.io, about 25 from: handles fit in one search query (keep it under 512 characters, as the tweet notification guide explains), so accounts are grouped into queries polled every 60 seconds ($6.48 a month each). On X, every delivered post is $0.005, by search or by XAA post.create event.

AccountsPosts a monthX pay-per-usage ($0.005 per post)TwitterAPI.io, 60 s polling
1300$1.50$6.53 (1 query: $6.48 + $0.05)
257,500$37.50$7.61 (1 query: $6.48 + $1.13)
10030,000$150$30.42 (4 queries: $25.92 + $4.50)
1,000300,000$1,500$304.20 (40 queries: $259.20 + $45)

Reading the table. For a single quiet account, X's per-event billing is lower, because a month of empty TwitterAPI.io checks ($6.48) costs more than 300 posts at $0.005 ($1.50); polling every 5 minutes instead brings that row to $1.34. From a couple of dozen accounts up, grouping handles into one query makes the polling floor irrelevant and the 33x per-post gap decides the bill. X's figures also assume you already have a developer account, and XAA's self-serve limit of 1,500 subscriptions and the 3 million Post reads a month pay-per-usage cap set the ceiling before Enterprise.

Fixed account lists. If the list is fixed and speed matters, Twitter Stream on TwitterAPI.io is the flat-price alternative: accounts added through /oapi/x_user_stream/add_user_to_monitor_tweet are pushed to your webhook, priced per plan rather than per call. Plans are on the Twitter Stream page.

09 — Section

Operational notes — rate limits, deletion archives, alerting design

Three operational notes that matter once you are past the prototype stage.

Rate limits. TwitterAPI.io allows 0.2 requests per second before the first payment, 20 once paid, 50 on Scale and 500 on Business. A 60-second poll is one request a minute per query, so even the unpaid limit (12 requests a minute) covers about a dozen queries. The official X API sets per-endpoint windows; our rate-limit guide lists them.

Deletion archives. A poll misses posts deleted between checks. To track deletions of posts you did see, re-fetch their IDs with /twitter/tweets at fixed checkpoints and flag the ones that no longer come back; on X, XAA's post.delete event reports deletions of a subscribed public account directly.

Alerting design. The most common failure of monitoring systems is alert fatigue. Tune spike thresholds per account or keyword (median x multiplier, not absolute counts), de-duplicate identical alerts within a window, and route high-urgency signals to a separate channel.

python
# pip install requests
import json
import time
import statistics
import pathlib
from datetime import datetime
import requests

API_KEY = "YOUR_TWITTERAPI_IO_KEY"
BASE = "https://api.twitterapi.io"
HANDLE = "elonmusk"             # change to whoever you're monitoring
POLL_INTERVAL = 60               # seconds
VELOCITY_CHECKPOINTS = [15, 60, 360, 1440]  # minutes after first-seen
SPIKE_MULTIPLIER = 3.0           # tune per account

STATE_DIR = pathlib.Path(".state")
STATE_DIR.mkdir(exist_ok=True)
IDS = STATE_DIR / f"{HANDLE}_seen.json"
VEL = STATE_DIR / f"{HANDLE}_velocity.json"
SINCE = STATE_DIR / f"{HANDLE}_since.json"
OUT = STATE_DIR / f"{HANDLE}_events.jsonl"

headers = {"X-API-Key": API_KEY}


def load_json(p, default):
    return json.loads(p.read_text()) if p.exists() else default


def save_json(p, obj):
    p.write_text(json.dumps(obj))


def emit(d):
    with OUT.open("a") as f:
        f.write(json.dumps(d) + "\n")


def resolve_uid(handle):
    r = requests.get(f"{BASE}/twitter/user/info",
                     params={"userName": handle}, headers=headers, timeout=10)
    r.raise_for_status()  # user/info answers HTTP 200 either way; the outcome is in the body
    body = r.json()
    data = body.get("data") or {}
    if body.get("status") != "success" or data.get("unavailable"):
        return None  # not found, or suspended (data["unavailableReason"])
    return str(data["id"])


def to_unix(created_at):
    # createdAt looks like "Tue Oct 13 16:42:56 +0000 2026"
    return int(datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y").timestamp())


def poll_once():
    # Ask only for tweets newer than the last one we saw. A poll with nothing
    # new returns 0 tweets and is billed the 15-credit minimum ($0.00015).
    since = load_json(SINCE, int(time.time()))  # first run: start from now
    r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
                     params={"query": f"from:{HANDLE} since_time:{since}",
                             "queryType": "Latest"},
                     headers=headers, timeout=10)
    r.raise_for_status()
    tweets = r.json().get("tweets") or []
    # next since_time = one second after the newest tweet seen
    save_json(SINCE, max([since] + [to_unix(t["createdAt"]) + 1 for t in tweets]))
    seen = set(load_json(IDS, []))
    vel = load_json(VEL, [])
    now = time.time()
    engagements = []
    for t in tweets:
        if t["id"] in seen:
            continue
        e = (t.get("likeCount", 0) + t.get("retweetCount", 0) +
             t.get("replyCount", 0))
        emit({"kind": "new_tweet", "id": t["id"], "text": t.get("text"),
              "first_seen_at": now, "engagement": e})
        # schedule velocity re-checks
        for m in VELOCITY_CHECKPOINTS:
            vel.append({"tid": t["id"], "at": now + m * 60})
        seen.add(t["id"]); engagements.append(e)
    save_json(IDS, sorted(seen)[-300:])
    save_json(VEL, vel)
    # Simple spike alert (replace with Slack / PagerDuty / SES)
    if engagements and len(seen) > 30:
        # rolling median of recent engagement
        recent = engagements + [e for e in load_json(STATE_DIR / f"{HANDLE}_eng.json", [])][-100:]
        save_json(STATE_DIR / f"{HANDLE}_eng.json", recent[-100:])
        if len(recent) >= 30:
            median = statistics.median(recent)
            for e in engagements:
                if median > 0 and e > median * SPIKE_MULTIPLIER:
                    print(f"SPIKE: handle={HANDLE} engagement={e} median={median:.0f}")


def velocity_pass():
    vel = load_json(VEL, [])
    due = [c for c in vel if c["at"] <= time.time()]
    rest = [c for c in vel if c["at"] > time.time()]
    save_json(VEL, rest)
    for c in due:
        r = requests.get(f"{BASE}/twitter/tweets",
                         params={"tweet_ids": c["tid"]}, headers=headers, timeout=10)
        r.raise_for_status()
        found = [t for t in r.json().get("tweets", []) if t.get("id")]
        if not found:  # not returned (or empty id) = deleted
            emit({"kind": "velocity_checkpoint", "id": c["tid"], "present": False})
        else:
            d = found[0]
            emit({"kind": "velocity_checkpoint", "id": c["tid"], "present": True,
                  "likes": d.get("likeCount"), "retweets": d.get("retweetCount")})


if __name__ == "__main__":
    uid = resolve_uid(HANDLE)
    while True:
        try:
            if uid is None:
                emit({"kind": "handle_inactive", "at": time.time()})
                time.sleep(1800); uid = resolve_uid(HANDLE); continue
            poll_once(); velocity_pass()
        except Exception as e:
            print("err:", e)
        time.sleep(POLL_INTERVAL)

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Is the Twitter Account Activity API still available?

Its docs are still online, but the Account Activity API introduction on docs.x.com says it "is being deprecated" and directs developers to the X Activity API (XAA) for real-time user activity. XAA delivers per-user events (post.create, post.delete, mentions, replies, likes, follows, DMs and more) to a webhook or a persistent stream.

How much does the Account Activity API cost?

The X pay-per-usage pricing page has no separate AAA price; AAA notes that delivered posts count toward the monthly Post cap, and its Pay Per Use tier allows 3 subscriptions and 1 webhook. Its replacement, XAA, is billed per delivered event: post.create $0.005, follow.follow $0.010, dm.received $0.010, post.delete not billed.

Can the Account Activity API monitor accounts I don't own?

AAA could not: each subscribed account had to authorize your app with OAuth. XAA allows public events (posts, deletes, profile updates) for any public account by user_id, but mentions, replies, quotes, reposts and likes are private events that need the watched user's OAuth 2.0 consent. To watch mentions of any account, or keywords, use a search: Filtered Stream on X, or advanced_search and filter rules on TwitterAPI.io.

What does it cost to monitor one X account?

On TwitterAPI.io, polling from:<handle> since_time:<last seen> every 60 seconds costs $6.48 a month in checks (43,200 x the $0.00015 minimum), plus $0.00015 per new post; every 5 minutes it is $1.30. Up to about 25 handles can share that one query. On X pay-per-usage you pay $0.005 per post delivered, with no listed per-call minimum, after setting up a developer account.

Polling vs webhooks: which one should I use?

If a minute of latency is fine, poll: you control the schedule, see every request in your logs, and host nothing but a cron job. If you need push and do not want to run a scheduler, register the same query as a TwitterAPI.io filter rule and receive matches on a webhook; at the same interval it costs about the same as polling. If you already run a server and want the lowest latency, hold the WebSocket stream.

What happens if my monitored account gets suspended or deactivated?

user/info still returns HTTP 200, and the body tells you what happened: status is error (user not found) or data.unavailable is true (read unavailableReason, e.g. Suspended). Treat this as state, not an error: flag the pipeline as handle_inactive and back off to an occasional user/info check. The Python script in this guide handles this branch.

How do I detect tweet deletions in a monitoring pipeline?

Re-check the IDs you have seen at T+15m, T+1h, T+6h and T+24h via /twitter/tweets; an ID missing from the response at a checkpoint is a deletion event. Each ID you send is billed 15 credits, including IDs that come back missing. Posts deleted before your first poll are not visible to polling; on X, a subscription to XAA's post.delete event (not billed) reports deletions of a public account directly.

Is it legal to programmatically monitor public Twitter accounts?

Programmatic access to public posts through an API is governed by that API's terms rather than per-account consent, and covers public data only; protected accounts are excluded. For commercial downstream uses (brand-safety products, social listening, sentiment analytics), check your jurisdiction's data-protection rules on top of the API terms.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.