Back to use cases

    Use case / X DATA / Python 3 / Published

    Twitter Trends by City: See What Is Trending Where with Python

    Compare Twitter trends across cities with Python. Fetch top posts and replies, then save shared and local trends in Markdown, CSVs and a heatmap.

    Card for Twitter Trends by City: See What Is Trending Where with Python

    City Trends Pulse is a small Python script that answers "what is trending on Twitter where, right now". For a list of places it pulls the current X trends, fetches the top posts for the leading trends, and writes a snapshot of which trends are shared across places and which are local.

    The problem

    Trend lists are easy to see one place at a time, but comparing several cities or countries is manual work. A trend name alone also says little: you need the top posts to know what it is about and whether those posts are fresh and on topic.

    What the app does

    • Takes a list of places by WOEID (worldwide, countries, cities).
    • Pulls up to 30 current trends per place.
    • Fetches top posts from the last day for the leading trends and keeps the 3 most engaged.
    • Pulls replies for the top post of each place.
    • Shows shared vs local trends, relevance and freshness checks.
    • Writes a Markdown snapshot, CSVs and a heatmap chart.

    How it works

    1. Trends. GET /twitter/trends per place, through the desearch-py SDK.
    2. Top posts. GET /twitter with sort=Top and a start date of yesterday for each trend.
    3. Replies. GET /twitter/replies/post for the top post per place.
    4. Compare. Overlap between places, relevance of each post to its trend, post age and language mix.
    5. Write the snapshot, CSVs, chart and a cost log from the X-Desearch-Cost-Usd header.

    The code

    PYTHON
    async def collect(top_n, posts_count, replies):
        from desearch_py import Desearch
        key = os.environ.get("DESEARCH_API_KEY")
        if not key:
            sys.exit("Set DESEARCH_API_KEY (create a key at console.desearch.ai).")
        costs, raw = [], {"fetched_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
                          "params": {"top_n": top_n, "posts_count": posts_count, "replies": replies},
                          "trends": {}, "searches": {}, "replies": {}}
        start_date = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=1)).strftime("%Y-%m-%d")
        raw["params"]["start_date"] = start_date
        async with Desearch(api_key=key) as d:
            print("1) trends per WOEID")
            for label, woeid in LOCATIONS:
                data = await timed(costs, f"x_trends {label} ({woeid})", d.x_trends(woeid=woeid, count=30, include_metadata=True))
                raw["trends"][label] = {"requested_woeid": woeid, "response": dump(data)}
            # one search per unique trend query among the top N of each supported location
            queries = {}
            for label, t in raw["trends"].items():
                r = t["response"] or {}
                if not supported(t):
                    continue
                for tr in r.get("trends", [])[:top_n]:
                    queries.setdefault(tr.get("query") or tr["name"], tr["name"])
            print(f"2) X search for {len(queries)} unique trend queries (sort=Top, start_date={start_date})")
            for q, name in queries.items():
                data = await timed(costs, f"x_search {name[:40]}", d.x_search(query=q, sort="Top", start_date=start_date,
                                                                             count=posts_count, include_metadata=True))
                raw["searches"][q] = {"trend": name, "posts": dump(data) if data is not None else None}
            if replies:
                print("3) replies to the #1 post per location")
                for label, t in raw["trends"].items():
                    if not supported(t):
                        continue
                    top = top_posts_for_location(raw, label, top_n, 1)
                    if top:
                        pid = top[0]["id"]
                        data = await timed(costs, f"x_post_replies {label} {pid}", d.x_post_replies(post_id=pid, count=10, include_metadata=True))
                        raw["replies"][label] = {"post_id": pid, "replies": dump(data) if data is not None else None}
        raw["costs"] = costs
        return raw

    The folder has one script, trends.py, a sample report in sample-output.md and the chart from that run.

    Endpoints

    • GET /twitter/trends
    • GET /twitter
    • GET /twitter/replies/post

    Example output

    From a run on 2026-10-04 across worldwide, the US, the UK, New York, London and Istanbul:

    CheckResult
    Trends in 3 or more places9
    Trends only in Istanbul29 of 29
    Trends only in the UK0 of 30 (same list as London)
    Kept posts that mention their trend98%
    Median age of kept posts4.2 hours

    Run it yourself

    The public examples folder linked above includes the script and a README. Install its requirements, set DESEARCH_API_KEY from console.desearch.ai, and use the run command in that README.

    Useful flags: --top (trends per place to search posts for, default 4), --posts (posts per trend, default 20), --no-replies, --from-raw FILE (re-run the analysis with no API calls). Edit LOCATIONS in trends.py to change places.

    What it costs

    One run with the defaults on 2026-10-04 made 32 calls, took about 100 seconds and cost $0.0975, summed from the X-Desearch-Cost-Usd headers. See pricing.

    Ideas to extend it

    The Markdown snapshot gives analysts a report to read alongside the CSVs and heatmap. Shared trends show overlap between the selected places, while local trends stay tied to their location. Edit the location list to use the same report for a different set of cities.

    • Run it hourly and keep a history of when a trend reaches each city.
    • Alert when a trend in your niche appears in a city you care about.
    • Add more cities for a regional newsroom view.

    Use with AI agents

    Point an MCP client at the hosted Desearch server. Replace the placeholder with a key from the console. Do not commit the key.

    JSON
    {
      "mcpServers": {
        "desearch": {
          "url": "https://mcp.desearch.ai/mcp",
          "headers": {
            "Authorization": "Bearer <key>"
          }
        }
      }
    }

    Prompt you can paste for this example:

    Use Desearch to fetch current X trends for the cities I list, then pull the top posts for each trend. Tell me which trends show up in several places and which are local. Quote only posts you retrieve. Do not invent trend names.

    Build your own example.

    Give your agents access to web and social search. Get an API key to start building, or talk to us about your integration.

    Read docs