Home Assistant and Twitter (X): Notify, Sensors and Automations

- The core integration is send-only.
platform: twitterundernotify:posts or DMs from your X developer app; it is marked legacy and has no read side. - Reading posts = RESTful sensor. A
rest:block calls/twitter/tweet/advanced_searchwithX-API-Key: !secret twitterapi_key; the state is the newest post id. - Keep the text out of the state. Home Assistant drops any state over 255 characters to
unknown; 15.1% of the posts we replayed were longer. Truncate to 250 or use an attribute. - Changes are rare. Median account: 0.21% of 1-minute polls and 2.68% of 15-minute polls changed the sensor (219 posts, 10 organization accounts, collected in 2026).
- Query since the last poll. A sensor at 5 minutes costs about $0.043/day that way, versus $0.86/day re-reading a 20-post page. The REST default of 30 s is $8.64/day on the page pattern.
- Posting is a
rest_command./twitter/create_tweet_v2acts as a logged-in account at $0.0006 per successful call; the core notify needs your own X app and pays X's write rate.
This page is about Home Assistant specifically: the YAML for a rest: sensor, secrets.yaml, the 255-character state limit and automations that fire on a new post. If you want new posts relayed into a chat channel, the Twitter to Discord bot guide covers that pipeline; if you want a general real-time monitor written in code, the guide to monitoring Twitter accounts for new tweets covers polling and webhooks outside Home Assistant. Here, Home Assistant is the poller, and everything is configuration.
Searches for "home assistant twitter" usually come from one of three people: someone who found the old Twitter notify integration and wonders if it still works, someone who wants a sensor that shows the latest post of an account (a weather service, a transit agency, a launch provider), or someone who wants an automation that posts to X when something happens at home. Each needs a different piece, and the built-in integration only covers the third.
We checked the integration's current state in the Home Assistant docs and the home-assistant/core source, wrote the REST sensor and automation YAML against the rest integration's docs and code, rendered the sensor templates against real API responses, and replayed 219 posts from 10 organization accounts to see how often a "latest post" sensor would actually change at 1-, 5- and 15-minute scan intervals and what each polling pattern costs. We do not run a Home Assistant instance for this page; the section on validation says exactly what was checked.
0.21% for the median of 10 organization accounts (219 posts replayed, collected in 2026). At 15 minutes it is 2.68%, and 14.2% of posts share a poll with a newer one.
What happened to the Home Assistant Twitter integration
It was not removed. As of this writing the integration lives in homeassistant/components/twitter in the home-assistant/core repository, with recent maintenance commits (the latest one converts its action fields to enums). Its documentation page is now titled "X", and it states that the integration "uses X to deliver notifications from Home Assistant", that it was introduced in Home Assistant 0.12, and that it is "used by 38 active installations".
It is a legacy, YAML-only notify platform. The integration's manifest.json carries "quality_scale": "legacy"; the label was added to every integration that had not moved to UI configuration (core pull request 131171, November 2024). You configure it under notify: with platform: twitter and four keys from an X developer app: consumer_key, consumer_secret, access_token and access_token_secret. An optional username turns the post into a direct message to that handle. The docs ask for an app with "Read and write" permission.
It only sends. The code in notify.py calls the v1.1 resources statuses/update (post), media/upload (attachments, chunked) and direct_messages/events/new (DM) through the TwitterAPI Python package, pinned at TwitterAPI==2.7.12. There is no sensor platform and no read call apart from a user lookup for DMs, so the integration cannot tell you that an account posted.
What it costs to use. It sends through your own X developer app, so X bills you directly. The official pay-per-usage rate card on docs.x.com/x-api/getting-started/pricing lists Post: Create at $0.015 per request, $0.200 per request when the post contains a URL, and DM Interaction: Create at $0.015 per request. A post such as "Front door left open, see http://..." falls into the URL tier.
Should you still use it? For a few posts a day from your own account it is the shortest path, as long as your X app works with the v1.1 calls it makes. Two cautions: its manifest lists no code owner, so fixes depend on whoever picks it up, and it depends on X keeping those v1.1 calls available to your app. The rest of this page covers the read side, which the integration never had, and an alternative send path.
Step 1: put the API key in secrets.yaml
Home Assistant keeps credentials out of configuration.yaml with the !secret tag: you write X-API-Key: !secret twitterapi_key in the configuration, and the value lives in secrets.yaml in the same folder. Per the secrets docs, when configuration is split into subfolders, Home Assistant looks for secrets.yaml in the referencing file's folder first, then in parent folders up to the one holding configuration.yaml.
Where not to use it. The docs warn that the UI YAML editor does not support secrets in automations.yaml and scripts.yaml (those automations become non-editable in the UI), and that secrets used in automations are visible to administrators in the YAML view and in traces. Keep the API key in the rest: block in configuration.yaml, where neither applies.
Getting a key. Sign in at twitterapi.io; new accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days), and the amount is listed on the pricing page. Reads need no X account and no X developer app. Before the first payment the key is limited to 0.2 requests per second, which is far above what a Home Assistant sensor needs: even the 30-second REST default is one request every 30 seconds per sensor.
# secrets.yaml (same folder as configuration.yaml)
twitterapi_key: "YOUR_TWITTERAPI_IO_KEY"Step 2: a RESTful sensor for the newest post of an account
The rest: integration makes one HTTP request per scan_interval and lets several sensors read the same response. The sensor docs list resource, method (GET or POST), headers and params (both accept templates), value_template, json_attributes, json_attributes_path (a JSONPath), scan_interval (default 30 seconds) and timeout (default 10 seconds). In the rest integration's code, headers and params are rendered again on every update, which is what makes a moving since_time window possible.
The query. /twitter/tweet/advanced_search takes query and queryType. from:NASA limits it to one account, since_time:<unix seconds> returns only posts created after that moment, and -filter:replies drops replies. In our check, the same three-hour from: query on a brand account returned 8 posts with 5 replies; adding -filter:replies returned 3. The response is a top-level tweets array, newest first, plus has_next_page and next_cursor; a quiet window returns tweets: [].
Why the state is the post id. An automation should fire once per new post. The post id is a numeric string of 19 digits, unique, and grows over time, so max over the ids is the newest post even if the array order ever surprises you. Identical ids on consecutive polls mean no state change and no trigger, so the 10-minute lookback can overlap the 5-minute scan without double alerts. The overlap covers a poll that runs late; the price is that a post returned twice is billed twice.
Why this.state. When the window is empty, the value template returns the sensor's own previous state, so the entity does not flip to an empty string and back (each flip would trigger the automation). The rest sensor passes this, value and value_json to its templates; we confirmed this in the integration's code, not on a running instance.
Why a second sensor for the text. Home Assistant rejects any state longer than 255 characters: MAX_LENGTH_STATE_STATE is 255 in homeassistant/const.py, and the state machine logs an error and falls back to unknown. The text sensor truncates to 250 characters with [:250]. We did not use json_attributes here because an empty search result has no first element, and the rest integration logs a warning and clears the attributes on every such poll; with a 5-minute scan that is a warning on nearly every poll.
# configuration.yaml: new posts from @NASA, checked every 5 minutes
rest:
- resource: https://api.twitterapi.io/twitter/tweet/advanced_search
method: GET
headers:
X-API-Key: !secret twitterapi_key
params:
# only posts from the last 10 minutes; overlap on purpose, the id keeps it idempotent
query: "from:NASA -filter:replies since_time:{{ (as_timestamp(now()) - 600) | int }}"
queryType: Latest
scan_interval: 300
timeout: 20
sensor:
- name: "NASA latest post text"
unique_id: x_nasa_latest_post_text
value_template: >-
{% set t = value_json.tweets | default([]) %}
{% if t | count > 0 %}{{ t[0].text[:250] }}{% else %}{{ this.state }}{% endif %}
- name: "NASA latest post id"
unique_id: x_nasa_latest_post_id
value_template: >-
{% set t = value_json.tweets | default([]) %}
{% if t | count > 0 %}{{ t | map(attribute='id') | map('int') | max }}{% else %}{{ this.state }}{% endif %}Step 3: an automation that fires on a new post
Trigger on the id sensor, not the text sensor: two posts can share a text, two posts never share an id. The trigger: state syntax with triggers:, conditions: and actions: follows the current automation docs. For a state trigger, trigger.from_state and trigger.to_state are the old and new state objects, and from_state is None when the entity was just created.
The condition matters on restart. When Home Assistant starts, the sensor goes from unknown (or unavailable) to the current newest id. Without the template condition, every restart would send a notification for a post you already saw. The condition skips any transition from or to those two values.
Reading the text. Both sensors are filled from the same response by the same refresh; the action reads sensor.nasa_latest_post_text and builds the link from the new id. Replace notify.mobile_app_your_phone with your own notify action; the post link is appended to the message text so it works with any notify target.
Ideas that use the same pattern. Flash a light when a weather service posts (@NWS, @NWSSPC), announce a launch account's post on a speaker, or log a transit agency's service alerts to a logbook entry. For alerts that matter, the 15-minute numbers further down are worth reading first: a long interval can hide posts.
# automations: push a phone notification when the post id changes
automation:
- alias: "Phone alert on new NASA post"
triggers:
- trigger: state
entity_id: sensor.nasa_latest_post_id
conditions:
- condition: template
value_template: >-
{{ trigger.from_state is not none
and trigger.from_state.state not in ['unknown', 'unavailable']
and trigger.to_state.state not in ['unknown', 'unavailable'] }}
actions:
- action: notify.mobile_app_your_phone
data:
title: "New post from @NASA"
message: >-
{{ states('sensor.nasa_latest_post_text') }}
https://x.com/NASA/status/{{ trigger.to_state.state }}How often a "latest post" sensor actually changes (real-data replay)
We pulled the latest posts of 10 organization accounts with /twitter/user/last_tweets (987 posts, 50 requests, collected in 2026), then replayed a sensor polling each account at fixed 1-, 5- and 15-minute intervals over the last 7 days (shorter for the two busiest accounts, whose 100 posts covered 1.4 and 2 days). A poll changes the state when at least one post was created since the previous poll. 219 posts fell inside the windows.
The headline. For the median account, 0.21% of 1-minute polls changed the state, 0.99% of 5-minute polls and 2.68% of 15-minute polls. At the REST default of 30 seconds it was 0.11%. Everything else is a request that finds nothing. Even the busiest account in the set, the Storm Prediction Center at 27.1 posts a day, changed on 23.91% of 15-minute polls.
What it means for the YAML. The scan interval is a latency choice, not a data-volume choice: nearly every poll comes back empty at any interval below an hour for these accounts. Choose the delay you can live with (next section), then pick a query whose empty answer is cheap.

Delay and hidden posts: what a longer scan interval costs you
A sensor holds one value. If two posts land between polls, the state jumps once, to the newer id, and the automation fires once. The older post is never shown unless your automation reads the whole list. Our replay counted those collapsed posts, and the delay between a post and the state change, for each interval.
Bursty accounts lose more. @Tesla posts in clusters: at a 15-minute interval 39.1% of its posts in the window shared a poll with a newer one, against 8.7% at 1 minute. @Spotify reached 23.1% at 15 minutes. Accounts that post a few times a day at spread-out times (@NASA, @github, @home_assistant) collapsed nothing at any interval.
The fix if every post matters. Keep the interval and loop over the list instead of the head: a rest_command with response_variable returns the full JSON to a script, which can notify once per post. Or shorten the interval for the few accounts where seconds count; with the since-the-last-poll query an empty poll costs the same at any interval, so a 1-minute sensor costs five times a 5-minute one, not more.
What each polling pattern costs per day
Tweet endpoints bill 15 credits per post returned, which is $0.15 per 1,000 posts, with a minimum of 15 credits ($0.00015) per request. That makes the choice of endpoint more important than the interval.
Pattern A: re-read the timeline page. /twitter/user/last_tweets returns a page of up to 20 of the account's latest posts on every call, new or not, so each poll costs $0.003. It is the simplest YAML (below), and json_attributes_path: "$.data.tweets[0]" can fill attributes because the page is never empty.
Pattern B: ask only for posts since the last poll. The since_time query of Step 2 returns an empty list on almost every poll, billed at the $0.00015 minimum, plus $0.00015 for each post it does return.
Ten sensors. Ten accounts at 1 minute cost $43.20 a day on Pattern A and $2.16 on Pattern B. At 15 minutes Pattern B is $0.14 a day for all ten. You can also merge accounts into one sensor with from:NWS OR from:NWSSPC, which turns ten empty requests into one; the state then tracks the newest post of the whole group.
Against the official X API. Reading the same posts through X's pay-per-usage API is $0.005 per post read per the docs.x.com rate card, about 33 times $0.15 per 1,000. For one hobby sensor either bill is small; the difference grows with the number of accounts and how often you re-read pages.
Watch the default. If you leave out scan_interval, the rest integration polls every 30 seconds: 2,880 requests a day per resource, $8.64 a day on Pattern A. Set it explicitly.
# configuration.yaml: simplest version, re-reads the latest 20 posts every 15 minutes
rest:
- resource: https://api.twitterapi.io/twitter/user/last_tweets
headers:
X-API-Key: !secret twitterapi_key
params:
userName: NASA
scan_interval: 900
timeout: 20
sensor:
- name: "NASA timeline head"
unique_id: x_nasa_timeline_head
value_template: "{{ value_json.data.tweets | map(attribute='id') | map('int') | max }}"
json_attributes_path: "$.data.tweets[0]"
json_attributes:
- text
- url
- createdAt
- likeCount
- viewCount
Posting to X from Home Assistant without the legacy integration
If the core notify does not work with your X app, or you do not want a developer app, a rest_command can post through /twitter/create_tweet_v2. The docs list a JSON body with login_cookies, tweet_text and proxy (required), plus optional reply_to_tweet_id, attachment_url (quote), community_id and media_ids; the response carries tweet_id, status and message.
How the session works. One /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies; each post is then 60 credits = $0.0006 per successful call, and calls that return status: error are not charged. The call acts as that account, so X can rate-limit, lock or suspend it: keep a normal human pace (an alert when the garage door opens, not a post per sensor tick), and expect the session to need a fresh login from time to time.
Secrets and traces. !secret must be a whole YAML value, so the script passes login_cookies and proxy as data to the rest_command, whose payload template builds the JSON with tojson. Per the secrets docs, values used in scripts and automations are visible to administrators in traces; treat the cookies like a password and keep the script in configuration.yaml rather than scripts.yaml.
Reading the result. The rest_command docs say the action returns a dictionary with status when you set response_variable; the script writes it to a persistent notification so a failed post is visible. For the core notify path the equivalent check is the Home Assistant log, since a notify action returns nothing.
# configuration.yaml: post to X from Home Assistant (acts as the logged-in account)
rest_command:
x_post:
url: https://api.twitterapi.io/twitter/create_tweet_v2
method: post
headers:
X-API-Key: !secret twitterapi_key
content_type: "application/json"
timeout: 30
payload: >-
{{ {"login_cookies": login_cookies, "proxy": proxy, "tweet_text": tweet_text} | tojson }}
script:
post_to_x:
alias: "Post to X"
fields:
message:
description: "Text of the post"
sequence:
- action: rest_command.x_post
data:
login_cookies: !secret x_login_cookies
proxy: !secret x_proxy
tweet_text: "{{ message }}"
response_variable: x_result
- action: persistent_notification.create
data:
title: "X post"
message: "HTTP {{ x_result['status'] }}: {{ x_result['content'] }}"How we collected this, and what we validated
Question. How often would a Home Assistant sensor whose state is an account's newest post change at 1-, 5- and 15-minute scan intervals, how many posts would collapse into one change, how late would the automation fire, and what does each polling pattern cost?
Accounts and sample. @home_assistant, @NWS, @NWSSPC, @NASA, @SpaceX, @Tesla, @github, @Spotify, @BBCBreaking and @AP, all public organization accounts. Up to 5 pages (100 posts) per account from /twitter/user/last_tweets with replies excluded (the endpoint default), 987 posts in 50 requests, collected in 2026. A handle we first picked for a smart-home project turned out to belong to an unrelated small account and was dropped before analysis. Four /twitter/tweet/advanced_search calls checked the empty and non-empty shapes of the since-the-last-poll query.
Method. Posts were deduplicated by id and sorted by createdAt. Each account's replay window is the last 7 days before collection or, for the two busiest accounts, the span of its first 40 returned posts. Those first two pages came back in strict newest-first order for every account; 5 of the 10 timelines had a few out-of-order items from position 45 on, which is why the YAML takes max of the ids instead of trusting position. In all 10, tweets[0] of the first page was the newest post.
What the sample cannot show. It is a retrospective replay on 10 accounts, not a live sensor; real polls drift by a few seconds, and search indexing can lag post creation, which is why the YAML overlaps its lookback window. Post rates change with news cycles and launches. Reposts count as posts (they move the sensor too). Costs assume one request per poll and 20 posts per timeline page.
What we validated without a Home Assistant instance. We do not run Home Assistant for this page. We parsed every YAML block with PyYAML's safe_load using a custom loader that resolves the !secret tag (plain safe_load rejects it), and rendered the two value templates with Jinja2 against real API responses: a non-empty search, an empty search (the template returned the stubbed previous state) and a timeline page (the max id equaled tweets[0].id). The this variable, the per-update rendering of params, the attribute parsing and the 255-character fallback were read from the home-assistant/core source. Treat the YAML as checked against the docs and code, not as tested on a running instance.
Privacy. Aggregates only, organization accounts only; no reposted or quoted authors were analyzed. Search check pages are not published.
"""Dry-run the two Home Assistant REST sensors from Python before you paste the YAML.
Makes the same requests the rest: integration will make, prints what each sensor's state
would be, and what the polling would cost per day. Needs: pip install requests
"""
import time
import requests
API_KEY = "YOUR_TWITTERAPI_IO_KEY" # the value you put in secrets.yaml
ACCOUNT = "NASA"
SCAN_INTERVAL = 300 # seconds, same as scan_interval in the YAML
LOOKBACK = 600 # seconds, same as the since_time offset in the YAML
HEADERS = {"X-API-Key": API_KEY}
BASE = "https://api.twitterapi.io"
def latest_since(account: str, lookback_s: int) -> list[dict]:
"""Pattern B: only posts created in the last lookback_s seconds (replies excluded)."""
since = int(time.time()) - lookback_s
params = {"query": f"from:{account} -filter:replies since_time:{since}", "queryType": "Latest"}
tweets, cursor = [], None
for _ in range(5): # a quiet account returns one empty page
if cursor:
params["cursor"] = cursor
r = requests.get(f"{BASE}/twitter/tweet/advanced_search", headers=HEADERS, params=params, timeout=20)
r.raise_for_status()
body = r.json()
tweets += body.get("tweets", [])
if not body.get("has_next_page"):
break
cursor = body.get("next_cursor")
return tweets
def timeline_head(account: str) -> dict | None:
"""Pattern A: the newest post on the account's timeline (one page of up to 20 posts)."""
r = requests.get(f"{BASE}/twitter/user/last_tweets", headers=HEADERS,
params={"userName": account}, timeout=20)
r.raise_for_status()
body = r.json()
if body.get("status") != "success":
raise SystemExit(f"API error: {body.get('msg')}")
tweets = body["data"]["tweets"]
return max(tweets, key=lambda t: int(t["id"])) if tweets else None
new = latest_since(ACCOUNT, LOOKBACK)
if new:
head = max(new, key=lambda t: int(t["id"]))
print("Pattern B state (id): ", head["id"])
print("Pattern B state (text):", head["text"][:250])
else:
print("Pattern B: nothing new, the sensor keeps its previous state (this.state)")
head = timeline_head(ACCOUNT)
if head:
print("Pattern A state (id): ", head["id"], "created", head["createdAt"])
print("Pattern A attributes: ", {k: head.get(k) for k in ("url", "likeCount", "viewCount")})
if len(head["text"]) > 255:
print("Note: this text is longer than 255 characters; keep it in an attribute, not the state")
polls_per_day = 86400 / SCAN_INTERVAL
print(f"Pattern A cost: {polls_per_day:.0f} polls x $0.003 (20 posts x 15 credits) = ${polls_per_day * 0.003:.2f}/day")
print(f"Pattern B floor: {polls_per_day:.0f} polls x $0.00015 (empty result) = ${polls_per_day * 0.00015:.3f}/day,"
" plus $0.00015 per post actually returned")
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Was the Twitter integration removed from Home Assistant?
No. As of this writing it is still in home-assistant/core under homeassistant/components/twitter, documented as "X" and marked legacy (YAML-only). The docs count 38 active installations. It is a notify platform that posts or sends DMs through your own X developer app; it has never had a sensor for reading posts.
How do I show the latest tweet of an account in Home Assistant?
Use the rest: integration: call an X data endpoint such as /twitter/tweet/advanced_search with from:<account> and your API key from secrets.yaml, set the sensor state to the newest post id, and put the text in a second sensor truncated to 250 characters or in an attribute. The YAML in Step 2 does exactly that.
Why does my REST sensor show unknown instead of the tweet text?
Home Assistant states are limited to 255 characters (MAX_LENGTH_STATE_STATE in the core source); a longer value is logged as an error and replaced with unknown. 15.1% of the posts in our replay were longer than 255 characters. Truncate with [:250] or move the text to an attribute.
What scan_interval should I use for a Twitter sensor?
It is a latency choice. In our replay the median account changed the sensor on 0.99% of 5-minute polls and posts reached the state in 2 to 3 minutes on average; at 15 minutes the average delay was about 6 to 10 minutes and 14.2% of posts were hidden behind a newer one. Always set it: the REST default is 30 seconds.
How much does a Home Assistant Twitter sensor cost to run?
With the since-the-last-poll search, almost every poll is empty and billed at the $0.00015 minimum: about $0.043 a day per sensor at 5 minutes and $0.216 at 1 minute. Re-reading a full 20-post timeline page costs $0.003 per poll, $0.86 a day at 5 minutes. The official X API lists $0.005 per post read.
Can Home Assistant post to X automatically?
Yes, two ways. The core notify platform twitter posts from your X developer app, billed by X at $0.015 per post ($0.200 with a URL). Or a rest_command calls /twitter/create_tweet_v2 with login cookies at $0.0006 per successful call; it acts as that account, so keep a normal human pace and expect occasional re-login.
Do I need an X developer account to read tweets in Home Assistant?
Not with the REST sensor on this page: reads need only an API key, no X account. The core integration needs an X developer app with read and write permission, but it only sends.
Can one sensor watch several accounts?
Yes. Join accounts in one query, for example from:NWS OR from:NWSSPC -filter:replies; the state then tracks the newest post of the group, and one empty request replaces several. Add the author to the text sensor (t[0].author.userName) so the notification says who posted.
Continue
- Home Assistant docs: X (twitter) notify integration, configuration and legacy status
- home-assistant/core on GitHub: the twitter component (manifest.json, notify.py)
- Home Assistant docs: RESTful integration (rest:, scan_interval, headers, params)
- Home Assistant docs: RESTful Command (payload, content_type, response_variable)
- Home Assistant docs: Storing secrets (secrets.yaml and !secret)
- X developer docs: pay-per-usage pricing (post read, post create, DM create)
- Twitter (X) API overview: endpoints, auth and pricing
- Monitor Twitter accounts for new tweets in real time (code, outside Home Assistant)
- Build a Twitter (X) to Discord bot with a since_time poller
- Node-RED and Twitter (X): flows for new posts
- Keyword alerts on Twitter (X) for developers
- Log in and post to X through the API
- TwitterAPI.io pricing: credits per post and per profile
- 01How to Mute a Conversation on Twitter (X): Mute This Conversation, Step by Step
- 02How to Hide Replies on Twitter (X), and What a Hidden Reply Still Shows
- 03Twitter (X) Ad Examples by Format, With Real Brand Data
- 04Twitter (X) Affiliate Marketing in 2026: Rules, Disclosure and What Link Posts Really Reach
- 05Tweets to CSV: Export Twitter (X) Posts to a Clean CSV File
- 06Most-Liked Tweets — Build Your Own Leaderboard via API
- 07Twitter (X) 2FA: How to Turn On Two-Factor Authentication
- 08Twitter (X) and the EU Digital Services Act (DSA): What the Commission Found, and What It Means for X Data
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.