Twitter (X) to WhatsApp: Forward New Posts to a WhatsApp Number

By TwitterAPI.io Team•18 min read
Decision flow for a Twitter (X) to WhatsApp forwarder. Step 1: new posts from a since_time search on twitterapi.io, query (from:BBCBreaking OR from:NWS), an empty check costs $0.00015. A diamond asks whether the 24-hour window is open (less than 24 hours since the subscriber's last reply). Yes leads to a free-form text message, type text, up to 4,096 characters, service messages with 1,000 a month free per number. No leads to a template message, type template, pre-approved, body up to 1,024 characters, paid per delivered message by market. A dashed arrow shows that the subscriber's reply re-opens the 24-hour window. Both paths end at the WhatsApp Cloud API POST /<phone-number-id>/messages and the subscriber's phone. Footer: 788 posts from @BBCBreaking and @NWS collected in 2026, 6.17 forwarded a day, 13.7% need a template if each template is answered at once.
The whole design in one picture: free-form text while the subscriber's 24-hour window is open, one paid template when it is closed. Study data collected in 2026.
TL;DR
  • Sharing one post: use the share icon under the post in the X app, then WhatsApp or Copy link to Post. Everything below is for forwarding new posts automatically.
  • Two calls do the job: /twitter/tweet/advanced_search with (from:BBCBreaking OR from:NWS) since_time:<unix> finds new posts (an empty check costs the $0.00015 minimum), and POST /<phone-number-id>/messages on the WhatsApp Cloud API sends them.
  • The 24-hour window decides the price: free-form "type": "text" messages only go out within 24 hours of the subscriber's last message; outside it you need an approved "type": "template", charged per delivered message (North America: $0.025 marketing, $0.0034 utility).
  • Measured volume: @BBCBreaking forwarded 3.62 posts a day and @NWS 2.41 (after dropping its 50.5% reposts); together 6.17 a day, 20 on the busiest UTC day.
  • Template only when the window is closed: if the subscriber answers each template at once, 69 of 504 posts (13.7%) needed a template; the other 435 went as free-form service messages, about 160 a month, inside Meta's 1,000 free service messages per number.
  • Length is rarely the problem: median formatted message 221 characters, longest 1,659, none near the 4,096-character text limit; 1.2% would not fit the room left in a 1,024-character template body, and a full-text daily digest would overflow it on 76.5% of days.

This page is about getting posts from X (Twitter) into WhatsApp: first the one-tap way to share a single post, then a working forwarder that sends every new post from accounts you choose to a WhatsApp number. It is the WhatsApp counterpart of our Twitter to SMS guide and our Telegram bot guide, and the difference matters: a text message or a Telegram bot can send whenever it likes, while WhatsApp's Business Platform only lets a business send free-form messages within 24 hours of the person's last message, and charges per delivered template outside that window. That one rule decides how the forwarder is built and what it costs.

We did not send any WhatsApp messages for this page and did not submit a template for approval, so everything about the delivery leg (window rules, categories, limits, prices) comes from Meta's and Twilio's own documentation, fetched for this build and named in each section. What we did measure is the X side: 788 recent posts from two organization accounts people commonly want alerts from, @BBCBreaking and @NWS, collected in 2026, run through the window rules to count how many messages would need a paid template, how long they are against WhatsApp's limits, and what a day of forwarding costs.

If you only want to share one post, you need nothing below this paragraph. In the X app, tap the share icon under the post. X's Help Center describes the share menu, including Share Post via and Copy link to Post (help.x.com/en/using-x/post-and-moment-url), and keeps a separate article on sharing posts to WhatsApp (help.x.com/en/using-x/whatsapp-share). Pick WhatsApp from the share options if it is listed on your phone, or copy the link and paste it into any WhatsApp chat or into WhatsApp Web on a computer. Saving a post's video to send as a file is a download question, covered by our Twitter video downloader. Forwarding every new post automatically needs two pieces, something that notices new posts on X and something allowed to send WhatsApp messages on its own, and the rest of the page builds both.

Forwarded posts that needed a paid WhatsApp template when a reply re-opened the 24-hour window (@BBCBreaking + @NWS, collected in 2026)

13.7%

01 — Section

How a Twitter to WhatsApp forwarder works

The forwarder is one small program with two halves. The X half asks TwitterAPI.io for posts newer than its last check, one combined search for every account on the list. The WhatsApp half sends each new post to the subscriber's number through Meta's WhatsApp Business Cloud API, either directly (graph.facebook.com) or through a provider such as Twilio that wraps the same platform. No X account, X developer app or personal WhatsApp account is involved: reads on TwitterAPI.io need only an API key, and WhatsApp sending needs a WhatsApp Business phone number registered in Meta's developer dashboard.

The rule that shapes the design. Meta's pricing page states that non-template messages ("type":"text", "type":"image" and so on) "can only be sent in an open 24-hour customer service window, which opens and resets with each user message". Template messages ("type":"template") "can be delivered at any time" but must be created and approved first, and every delivered template is charged at the rate for its category and the recipient's country. Meta's error reference lists code 131047, "More than 24 hours have passed since the recipient last replied to the sender number", with the advice to send a template instead.

Three ways to live with it. (A) Send every post as a template: simple, and the subscriber never has to do anything, but every message is billed. (B) Send a template only when the window is closed, ask the subscriber to reply, and send everything else as free-form text while the window is open. (C) Send one digest template a day. The study below counts what each would send for two real accounts, and the example script implements (B).

Message typeWhen it can be sentLength limitWhat Meta charges
Free-form text (type: text)Only inside the 24-hour window4,096 charactersService rate; first 1,000 a month per number free
Template, utilityAny time, after approvalBody 1,024 charactersUtility rate per delivered message
Template, marketingAny time, after approvalBody 1,024 charactersMarketing rate per delivered message
02 — Section

Step 1: set up the WhatsApp Cloud API and a template

Meta's get-started guide walks through the setup: create a Meta app with the WhatsApp use case, connect a business portfolio, and use the API Setup panel to generate a temporary access token and send a first message from a test number to your own phone. Note the phone number ID; every send goes to POST /<WHATSAPP_BUSINESS_PHONE_NUMBER_ID>/messages. The temporary token is for that first hello_world test only. For a forwarder that runs for months, the guide has you create a system user in Business Settings and generate a token with whatsapp_business_messaging and whatsapp_business_management permissions.

Webhooks are not optional here. The forwarder has to know when the subscriber last wrote, because that is when the 24-hour window opened. Meta reports inbound messages to a webhook you host. Per the webhook docs, Meta first sends a GET with hub.mode=subscribe, hub.verify_token and hub.challenge; you answer 200 with the challenge if the token matches the string you entered in the App Dashboard. Each later POST carries an X-Hub-Signature-256 header, an HMAC-SHA256 of the body keyed with your app secret, which you should check. Failed deliveries are retried for up to 7 days, so deduplicate.

Create the template. Templates have a header (optional, up to 60 characters), a body (required, up to 1,024 characters), an optional footer and buttons, and numbered {{1}} or named {{name}} parameters filled in at send time. A forwarding template can be as short as New post from {{1}}: followed by {{2}} and Reply to get updates. Per Meta's template docs, review is automatic and "can take up to 24 hours"; an approved template has status APPROVED, and templates that collect negative feedback can later be paused.

Which category your template lands in. You request a category, but Meta's guidelines decide it. A utility template must be non-promotional and either specific to something the user requested or "essential or critical" to them; the guidelines list severe weather alerts as an example of essential public-safety messages. Templates "where contents are unclear (for example, where contents are only '{{1}}')" are treated as marketing. So a template that relays NWS warnings to someone who asked for them has a plausible utility case, while a general news or brand feed should be expected to be categorized as marketing. We could not submit a template for this page, so treat this as a reading of the guidelines, not a tested outcome.

United States numbers. Twilio's changelog of March 5, 2025 states that from April 1, 2025 Meta blocks WhatsApp marketing template messages to U.S. (+1) phone numbers (Twilio error 63049). We found no notice lifting it while building this page. If your subscriber has a U.S. number, plan on utility templates or the open-window path, not marketing templates.

Messaging limits. Meta's messaging limits cap how many unique users a business can reach outside a customer service window in a moving 24 hours: newly created business portfolios start at 250. A personal forwarder to one or a few numbers stays far below that; a public subscribe-by-WhatsApp service would not.

03 — Section

Step 2: find new posts with one search per minute

On the X side the forwarder needs only one endpoint. /twitter/tweet/advanced_search with queryType=Latest and a query like (from:BBCBreaking OR from:NWS) -filter:replies since_time:1767225600 returns only posts newer than the timestamp, newest first, in pages of up to 20 with has_next_page and next_cursor. The script keeps the time of its last check, re-reads a 60-second overlap so a post indexed a little late is not missed, and drops IDs it has already forwarded.

What it costs. TwitterAPI.io bills 15 credits ($0.00015) per post returned, with a 15-credit minimum per request. A check that finds nothing therefore costs $0.00015, and once a minute for a month that is 43,200 checks, $6.48; every 5 minutes it is $1.30. For our two accounts the posts themselves add almost nothing on top: about 6 posts a day, each already covered by the minimum of the check that returned it. The official X API rate card at docs.x.com/x-api/getting-started/pricing prices a post read at $0.005, about 33 times TwitterAPI.io's $0.15 per 1,000 posts.

Why not one call per account. /twitter/user/last_tweets returns an account's latest page of 20 posts every time, billed as 20 posts ($0.003), with no since filter, so polling it every minute costs far more than a combined search that usually comes back empty. Keep one query per pass for the whole list; split very long watch lists into a few queries.

Push instead of poll. If you would rather not run a timer, a TwitterAPI.io filter rule (/oapi/tweet_filter/add_rule with a tag, the query as value and an interval_seconds, then /oapi/tweet_filter/update_rule with is_effect to switch it on) delivers matching posts to an HTTPS endpoint you host, and the same WhatsApp sending code runs inside that endpoint. Our guide to Twitter webhooks and filter rules covers the payload and setup.

python
import requests, time

BASE = "https://api.twitterapi.io"
KEY = "YOUR_TWITTERAPI_IO_KEY"

since = int(time.time()) - 3600          # first run: the last hour
query = f"(from:BBCBreaking OR from:NWS) -filter:replies since_time:{since}"
params, posts = {"query": query, "queryType": "Latest"}, []
while True:
    r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
                     headers={"X-API-Key": KEY}, params=params, timeout=30)
    r.raise_for_status()
    page = r.json()
    posts += page.get("tweets") or []
    if not page.get("has_next_page") or not page.get("next_cursor"):
        break
    params["cursor"] = page["next_cursor"]

for t in sorted(posts, key=lambda t: int(t["id"])):   # oldest first
    a = t.get("author") or {}
    print(t["createdAt"], "@" + a.get("userName", ""), len(t.get("text") or ""), t.get("url"))
04 — Section

Step 3: send to WhatsApp, text inside the window, template outside

A free-form message is one POST to https://graph.facebook.com/<version>/<phone-number-id>/messages with a bearer token and a JSON body: messaging_product set to whatsapp, recipient_type individual, the subscriber's number in to, type text and a text object holding body (up to 4,096 characters) and preview_url. With preview_url: true the WhatsApp client tries to render a preview of the first URL in the body, so the x.com link at the end of each message shows the post card. WhatsApp renders text between asterisks as bold (per WhatsApp's help center, faq.whatsapp.com), which the script uses for the account name.

A template message uses type template and a template object with the approved name, a language code such as en_US, and components holding the body parameters in order. The parameter values must fit the template: Meta returns 132000 when the count does not match the template and 132001 when the template is not approved in that language. The script flattens the post text to one line and cuts it to 850 characters so name, text and link stay inside the 1,024-character body.

The window logic. The webhook handler records the timestamp of the subscriber's last inbound message. On each pass, if that is less than 24 hours old (the script uses 23 h 55 min to stay clear of the edge), queued posts go out as free-form text. If it is older, the script sends the oldest queued post as a template with a count of how many more are waiting, then holds the rest until the subscriber replies; one reply re-opens the window and the backlog follows as free-form text. That is scenario (B) from the study below, and it is why the forwarder sends no more than one paid template per closed window.

Twilio instead of Meta directly. Twilio's WhatsApp API wraps the same platform, with the same window and template rules. Per Twilio's pricing page, it adds its own fee of $0.005 per message, inbound or outbound, plus a $0.001 processing fee on failed messages, and passes Meta's per-template fee through. For our two accounts that is about 185 outbound messages a month, $0.93 in Twilio fees, plus $0.13 for the subscriber's replies. Twilio is a reasonable choice if you already use it for SMS and want one console; going direct avoids the per-message fee.

05 — Section

What the forwarder would send: 788 posts from @BBCBreaking and @NWS

We pulled the latest 20 timeline pages of each account (reposts included, replies excluded by default), 788 posts in all, and kept what a forwarder would actually send: original posts and quotes. That removes 3 reposts from @BBCBreaking and 202 from @NWS, which reposts regional weather offices heavily (50.5% of its timeline).

AccountPostsDays coveredForwarded per dayBusiest UTC dayMedian gap
@BBCBreaking388106.53.6293.3 h
@NWS40082.02.41155.2 h
Both, one subscriber504 forwarded81.6 (overlap)6.1720n/a

The gaps are what matter for WhatsApp. A 24-hour window only helps if the next post arrives before it closes. For @BBCBreaking the 90th percentile gap between forwarded posts was 17.7 hours and only 2.9% of gaps exceeded 24 hours (longest 61.0 hours). @NWS is burstier: 90th percentile 21.8 hours, 8.1% of gaps over 24 hours, longest 66.4 hours, and 17.1% of days with nothing to forward. Weather accounts post in storms and go quiet between them.

Templates needed per scenario. If every post is a template (A), that is 6.17 paid messages a day for both accounts together. If the forwarder sends a template only when the window is closed and the subscriber replies at once (B), 69 of 504 posts (13.7%) needed a template, 0.85 a day, and 435 went as free-form text. Per account on its own the template share is higher, 20.8% for @BBCBreaking and 28.8% for @NWS, because a single quieter feed lets the window lapse more often. A daily digest (C) is always one template a day.

Free service messages cover the rest. Scenario (B) sends about 160 free-form messages a month for both accounts. Meta gives every business phone number 1,000 free service messages a month, so a forwarder like this one never reaches a paid service message.

Scenario (B) is a best case. It assumes the subscriber replies as soon as a template arrives. A subscriber who replies hours later still gets everything, just later, and still costs only one template per closed window; a subscriber who never replies gets one template and a growing queue. That is a product decision for you, not a technical one: decide whether the queue holds, drops or digests.

Horizontal bar chart of WhatsApp messages per day for both accounts to one subscriber, 504 forwarded posts from @BBCBreaking and @NWS over 81.6 days, collected in 2026. A, template for every post: 6.17 paid templates. B, template only when the window is closed: 0.85 templates plus 5.33 free-form service messages. C, one digest template a day: 1.00 template. Side panel, Meta cost for 30 days at USD list rates: North America A marketing $4.63, A utility $0.63, B utility $0.09, C marketing $0.75; United Kingdom A marketing $11.76, A utility $4.08, B utility $0.56, C marketing $1.91.
Paid templates versus free-form messages per day under three sending strategies, both accounts to one subscriber. Data collected in 2026; Meta list rates from developers.facebook.com.
06 — Section

Message length against WhatsApp's limits

We formatted every forwarded post the way the script does (a bold name line, the post text, the x.com link) and measured it. The median message was 221 characters and the 95th percentile 498. @BBCBreaking headlines are short and uniform (median 211, longest 272); @NWS posts run longer (median 376, longest 1,659) and 84.3% of its forwarded posts carry photos or video, which the link preview shows but the text does not.

Free-form text never hits the limit. None of the 583 forwarded posts came near the 4,096-character text body limit, so inside the window the forwarder can send the full post.

Templates are tighter. A template body holds 1,024 characters including its fixed text. With about 60 characters of fixed wording, 964 remain for the name, the text and the link, and 1.2% of posts (all from @NWS) would need cutting. The script cuts at 850 characters of text and keeps the link, so the subscriber can always open the full post.

Digests do not fit one template. A daily digest at 08:00 UTC would have carried a median of 6 posts and, on the busiest day, 20. With full text, the digest would pass 1,024 characters on 76.5% of days (median 1,675 characters). Links only, the busiest day's digest comes to about 1,020 characters, right at the limit. A digest template should therefore carry a count and one link, or a few headlines, and let the subscriber reply to receive the rest as free-form text.

Bar chart of formatted WhatsApp message length for 583 forwarded posts from @BBCBreaking and @NWS, collected in 2026: 0 posts at 1 to 100 characters, 95 at 101 to 200, 318 at 201 to 300, 101 at 301 to 400, 54 at 401 to 600, 8 at 601 to 1,000 and 7 at 1,001 to 4,096. Callout: 1.2% exceed the 964 characters left in a 1,024-character template body, 0 of 583 exceed the 4,096-character text limit, longest 1,659. Median 221, 95th percentile 498; a full-text daily digest would pass 1,024 characters on 76.5% of days.
Formatted message length per forwarded post against the 1,024-character template body and the 4,096-character text limit. Data collected in 2026.
07 — Section

What it costs a month, by country and strategy

Meta charges per delivered message, by category and by the recipient's country code, at the list rates on its pricing page (effective October 1, 2026). Messages from the subscriber to you are free, and only delivered messages are charged. Applied to the 6.17 forwarded posts a day from our two accounts, 30 days cost the following on the Meta side:

Recipient marketA: every post, marketingA: every post, utilityB: window, utilityC: digest, marketing
North America$4.63$0.63$0.09$0.75
United Kingdom$11.76$4.08$0.56$1.91
Germany$25.28$10.19$1.39$4.10
Brazil$11.58$1.26$0.17$1.88
India$2.19$0.26$0.04$0.35

The rates behind the table, per delivered message in USD: North America $0.025 marketing and $0.0034 utility; United Kingdom $0.0635 and $0.022; Germany $0.1365 and $0.055; Brazil $0.0625 and $0.0068; India $0.0118 and $0.0014. If scenario (B)'s templates are categorized as marketing instead of utility, North America comes to $0.63 a month and the United Kingdom $1.61. Remember the U.S. marketing block above: column A marketing and column C apply to Canadian numbers in the North America market, not U.S. ones. Meta's pricing page also announces a USD rate card change on January 1, 2027, with lower rates for messages to India and Indonesia, so check the current card before you budget.

Add the X side. Polling once a minute costs $6.48 a month, once every 5 minutes $1.30, whatever WhatsApp costs. So the full bill for forwarding @BBCBreaking and @NWS to one North American number with scenario (B) is about $6.57 a month at 1-minute polling, and the polling floor, not WhatsApp, is the larger part. Polling every 5 minutes brings it under $1.50. With Twilio in front, add its $0.005 per message.

What changes the numbers. More subscribers multiply the WhatsApp side but not the X side: one search serves every subscriber. More accounts add posts but not checks, as long as they share one query. A busier account, like a sports or brand account that posts dozens of times a day, keeps the window busy and pushes scenario (B) further toward free-form messages; a quiet account that posts every few days makes almost every message a template.

08 — Section

Troubleshooting a Twitter to WhatsApp forwarder

Error 131047 on a text message. More than 24 hours have passed since the subscriber's last message. Your window check is off, or the webhook is not recording replies; send the template instead and check that inbound webhooks reach your server.

Error 132001. The template name or language does not match an approved template. Template names are lowercase with underscores, and the language code must match the language you created it in.

Error 132000 or 132018. The parameters do not match the template: wrong count, or values in the wrong format. Send exactly as many body parameters as the template has {{n}} placeholders, and keep the values short and on one line.

Error 131049 on a marketing template. Meta did not deliver the message "to maintain healthy ecosystem engagement"; per Meta's error reference, wait at least 24 hours before resending if you suspect the per-user marketing limit. Another reason to prefer utility templates or the open-window path for alert feeds.

The webhook never verifies. Meta's GET must get status 200 and the exact hub.challenge value back, and the verify token must match the string in the App Dashboard. The endpoint must be reachable over HTTPS from the internet.

Duplicate messages. The search overlap re-reads the last minute on purpose; keep the seen-ID list on disk so a restart does not forward the same posts again. Meta also retries webhooks, so record inbound messages idempotently.

Nothing arrives from X. Check the query in the search box first: handles without @, OR in capitals, and remember a from: search does not return reposts. Our guide to Twitter search operators lists them. A 429 means you are above your request rate: 0.2 requests per second before the first payment, 20 once paid.

09 — Section

How we collected this

Question. If you forward every new post from two organization accounts to one WhatsApp number, how many messages a day is that, how many need a paid template versus fit an open 24-hour window, how long are they against WhatsApp's limits, and what does a day cost on both sides?

Accounts and method. @BBCBreaking and @NWS, two public organization accounts. We called /twitter/user/last_tweets for each, 20 pages of up to 20 posts, newest first, with the default that excludes replies: 40 requests, 788 posts, $0.12 in API credits, collected in 2026. Forwarded posts are originals and quotes; reposts are dropped as the script does. Window scenarios replay the post timestamps against a 24-hour window; scenario (B) assumes the subscriber replies the moment a template arrives. Costs use Meta's USD list rates from its pricing page and TwitterAPI.io's published prices.

Window. The latest posts of each account at collection time: 106.5 days for @BBCBreaking, 82.0 days for @NWS, and an overlap of 81.6 days for the combined feed.

What the sample cannot show. We did not send WhatsApp messages, so there is no delivery latency, read rate or block rate here, and we did not submit a template, so the category Meta would assign is our reading of its guidelines. Two accounts are an illustration, not a benchmark: a high-volume account changes the template share a lot. Rates differ by country and change on Meta's pricing calendar.

Privacy. Aggregates only, from organization accounts; no analysis of reposted or quoted authors and no private individuals. The study files, including the analysis script, live in the site repository under data/studies/twitter-to-whatsapp/.

python
"""twitter_to_whatsapp.py - forward new posts from chosen X (Twitter) accounts to one WhatsApp number.

    pip install requests
    export TWITTERAPI_IO_KEY=...          # twitterapi.io dashboard
    export WA_TOKEN=...                   # Meta system user token (whatsapp_business_messaging)
    export WA_PHONE_NUMBER_ID=...         # API Setup panel in the Meta App Dashboard
    export WA_TO=447700900123             # subscriber's number, country code first, no +
    export WA_VERIFY_TOKEN=pick-a-string  # same string in the App Dashboard webhook settings
    export WA_APP_SECRET=...              # to check X-Hub-Signature-256 on inbound webhooks
    python twitter_to_whatsapp.py         # serves the webhook on :8080 and polls every 60 s

Logic: free-form text while the subscriber's 24-hour customer service window is open,
one approved template ("x_post_alert") when it is closed. The subscriber's reply re-opens it.
"""
import hashlib, hmac, json, os, threading, time
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse

import requests

BASE = "https://api.twitterapi.io"
GRAPH = "https://graph.facebook.com/v23.0"     # use the version shown in your App Dashboard
X_KEY = os.environ["TWITTERAPI_IO_KEY"]
WA_TOKEN = os.environ["WA_TOKEN"]
PHONE_ID = os.environ["WA_PHONE_NUMBER_ID"]
WA_TO = os.environ["WA_TO"]
VERIFY = os.environ["WA_VERIFY_TOKEN"]
APP_SECRET = os.environ["WA_APP_SECRET"].encode()
WATCH = ["BBCBreaking", "NWS"]                 # handles without @
INTERVAL = 60                                  # seconds; empty check = $0.00015
WINDOW = 24 * 3600 - 300                       # treat the window as closed 5 minutes early
TEMPLATE = "x_post_alert"                      # body: New post from {{1}}:\n{{2}}\nReply to get updates.
STATE_FILE = "wa-state.json"
MAX_QUEUE = 50                                 # posts held while waiting for a reply
lock = threading.Lock()


def load():
    if os.path.exists(STATE_FILE):
        return json.load(open(STATE_FILE))
    return {"since": int(time.time()) - INTERVAL, "seen": [], "queue": [], "last_reply": 0, "template_at": 0}


def save(state):
    state["seen"] = state["seen"][-3000:]
    json.dump(state, open(STATE_FILE, "w"))


class Webhook(BaseHTTPRequestHandler):
    def do_GET(self):                          # Meta's verification request
        q = parse_qs(urlparse(self.path).query)
        if q.get("hub.mode") == ["subscribe"] and q.get("hub.verify_token") == [VERIFY]:
            self.send_response(200); self.end_headers()
            self.wfile.write(q["hub.challenge"][0].encode())
        else:
            self.send_response(403); self.end_headers()

    def do_POST(self):                         # inbound messages and delivery statuses
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        sig = "sha256=" + hmac.new(APP_SECRET, body, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(sig, self.headers.get("X-Hub-Signature-256", "")):
            self.send_response(403); self.end_headers(); return
        self.send_response(200); self.end_headers()
        for entry in json.loads(body).get("entry", []):
            for change in entry.get("changes", []):
                for msg in change.get("value", {}).get("messages", []):
                    if msg.get("from") == WA_TO:   # the subscriber wrote: the window is open again
                        with lock:
                            s = load()
                            s["last_reply"] = max(s["last_reply"], int(msg["timestamp"]))
                            save(s)


def new_posts(since):
    """One combined search per tick; only posts newer than since come back."""
    query = "(" + " OR ".join(f"from:{h}" for h in WATCH) + f") -filter:replies since_time:{since}"
    params, found = {"query": query, "queryType": "Latest"}, []
    while True:
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
                         headers={"X-API-Key": X_KEY}, params=params, timeout=30)
        r.raise_for_status()
        page = r.json()
        found += page.get("tweets") or []
        if not page.get("has_next_page") or not page.get("next_cursor"):
            return found
        params["cursor"] = page["next_cursor"]


def send(payload):
    r = requests.post(f"{GRAPH}/{PHONE_ID}/messages", timeout=30,
                      headers={"Authorization": f"Bearer {WA_TOKEN}"},
                      json={"messaging_product": "whatsapp", "recipient_type": "individual", "to": WA_TO, **payload})
    if r.status_code != 200:
        print("WhatsApp error", r.status_code, r.text[:300])
    return r.status_code == 200


def as_item(t):
    a = t.get("author") or {}
    return {"id": t["id"], "who": f"{a.get('name', '')} (@{a.get('userName', '')})",
            "text": t.get("text") or "", "url": t.get("url") or ""}


def send_text(item):                           # free-form text, up to 4,096 characters
    body = f"*{item['who']}*\n{item['text'][:3900]}\n{item['url']}"
    return send({"type": "text", "text": {"preview_url": True, "body": body}})


def send_template(item, waiting):              # the template body caps at 1,024 characters
    flat = " ".join(item["text"].split())[:850]
    more = f" (+{waiting} more)" if waiting else ""
    return send({"type": "template", "template": {
        "name": TEMPLATE, "language": {"code": "en_US"},
        "components": [{"type": "body", "parameters": [
            {"type": "text", "text": item["who"]}, {"type": "text", "text": f"{flat} {item['url']}{more}"}]}]}})


def tick(state):
    started = int(time.time())
    posts = new_posts(state["since"] - 60)     # 60 s overlap; seen ids drop the repeats
    posts = [p for p in posts if p["id"] not in state["seen"] and not p.get("retweeted_tweet")]
    for p in sorted(posts, key=lambda p: int(p["id"])):   # oldest first
        state["queue"].append(as_item(p))
        state["seen"].append(p["id"])
    state["queue"] = state["queue"][-MAX_QUEUE:]
    state["since"] = started
    window_open = time.time() - state["last_reply"] < WINDOW
    if window_open:
        while state["queue"] and send_text(state["queue"][0]):
            state["queue"].pop(0)
    elif state["queue"] and state["template_at"] <= state["last_reply"]:
        if send_template(state["queue"][0], len(state["queue"]) - 1):
            state["queue"].pop(0)
            state["template_at"] = int(time.time())   # one template per closed window, then wait


def poll_forever():
    while True:
        with lock:
            state = load()
            try:
                tick(state)
            except requests.RequestException as e:
                print("search failed, retry next tick:", e)
            save(state)
        time.sleep(INTERVAL)


if __name__ == "__main__":
    threading.Thread(target=lambda: HTTPServer(("", 8080), Webhook).serve_forever(), daemon=True).start()
    poll_forever()

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

10 — Questions

Questions readers ask

How do I share a tweet to WhatsApp?

In the X app, tap the share icon under the post and pick WhatsApp from the share options, or choose Copy link to Post and paste the link into a WhatsApp chat. On a computer, copy the link from the share menu and paste it into WhatsApp Web or the desktop app. WhatsApp shows a preview of the post from the link.

Can I get new tweets from an account sent to my WhatsApp automatically?

Yes, with a small forwarder: a script that checks TwitterAPI.io for new posts from the account once a minute (/twitter/tweet/advanced_search with from:handle since_time:<unix>) and sends each one to your number through the WhatsApp Business Cloud API or Twilio. You need a WhatsApp Business phone number set up in Meta's developer dashboard; your personal WhatsApp number receives the messages.

Why can't my bot just send a WhatsApp text whenever a tweet appears?

Meta's rules allow free-form messages only within 24 hours of the recipient's last message to you (the customer service window). Outside it, a business may only send a pre-approved template message, which is charged per delivered message. Meta returns error 131047 if you send free-form text after the window has closed.

How much does a Twitter to WhatsApp forwarder cost?

For @BBCBreaking and @NWS together (6.17 posts a day in our 2026 sample) to one North American number: about $0.09 a month in Meta utility templates if templates are sent only when the window is closed and the subscriber replies, or $4.63 a month if every post is a marketing template. Polling X once a minute adds $6.48 a month ($1.30 at 5 minutes). Twilio, if used, adds $0.005 per message.

Will Meta approve a template for forwarding tweets?

Templates are reviewed automatically, and review can take up to 24 hours per Meta's docs. Meta decides the category: its guidelines treat templates whose content is only a variable as marketing, and list severe weather alerts as an example of an essential utility message. Expect a general news or brand feed to be categorized as marketing. We did not submit one for this page.

Can I send WhatsApp marketing templates to US numbers?

Per Twilio's changelog of March 5, 2025, Meta blocks WhatsApp marketing template messages to U.S. (+1) numbers from April 1, 2025, and we found no notice lifting it. For U.S. subscribers use a utility template, where the content qualifies, or keep the 24-hour window open so posts go out as free-form messages.

Is there a free way to forward tweets to WhatsApp?

Not fully. Meta gives each business phone number 1,000 free service messages a month, which covers free-form messages inside the window, but templates are charged, and reading new posts from X costs at least the $0.00015 minimum per check on TwitterAPI.io. New TwitterAPI.io accounts get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the amount.

Can I forward tweets that mention a keyword instead of one account?

Yes. Replace the from: part of the search query with the keyword or phrase, for example "your brand" -filter:replies since_time:<unix>, or create a TwitterAPI.io filter rule with that query so matches are pushed to your endpoint. The WhatsApp half stays the same.

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.