From 69f07f2ef38af5af1103bef485312c0a932a6d6a Mon Sep 17 00:00:00 2001 From: kasparasizi1 <132673909+kasparasizi1@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:52:05 +0200 Subject: [PATCH] feat(twitter): search tweets across communities (0.85.0, SCR-756) GET /v1/twitter/communities/search_tweets is the Top and Latest tabs of X's community search page: tweets across every community, each with the community it was posted in. - twitter.communities.search_tweets_across_communities(query, *, tweet_type, count, cursor) -> PaginatedResponse[CommunityTweet] - twitter.communities.search_tweets_across_communities_all(...) with automatic pagination - CommunityTweet: a Tweet with community_id and community_name (the plain Tweet model would drop them) - CommunitySearchTweetType: TOP, LATEST Fixed: CommunityTweetType was not exported from scrapebadger.twitter, so the Twitter guide's own import raised ImportError. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 11 ++ docs/twitter.md | 13 +- pyproject.toml | 2 +- src/scrapebadger/__init__.py | 2 +- src/scrapebadger/_internal/client.py | 2 +- src/scrapebadger/twitter/__init__.py | 6 + src/scrapebadger/twitter/communities.py | 89 ++++++++++++- src/scrapebadger/twitter/models.py | 29 +++++ .../test_twitter_communities_search_tweets.py | 117 ++++++++++++++++++ uv.lock | 2 +- 10 files changed, 267 insertions(+), 6 deletions(-) create mode 100644 tests/test_twitter_communities_search_tweets.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 585710a..84f24e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [0.85.0] - 2026-11-30 + +### Added +- **`twitter.communities.search_tweets_across_communities(query, *, tweet_type, count, cursor)`**: search tweets posted in communities, across every community (`GET /v1/twitter/communities/search_tweets`, the Top and Latest tabs of X's community search page). Returns `PaginatedResponse[CommunityTweet]`. `tweet_type` is `CommunitySearchTweetType.TOP` (default) or `.LATEST`. (SCR-756) +- **`twitter.communities.search_tweets_across_communities_all(query, *, tweet_type, max_pages, max_items)`**: the same search with automatic pagination. +- **`CommunityTweet`**: a `Tweet` with `community_id` and `community_name`, the community the tweet was posted in. Pass the id to `communities.get_detail()` or `communities.get_tweets()`. Both are `None` for the rare result X returns without a community. +- `communities.search()` finds communities by name and `communities.search_tweets(community_id, query)` searches inside one community; both are unchanged. + +### Fixed +- `from scrapebadger.twitter import CommunityTweetType` raised `ImportError`, although the Twitter guide's example imports it that way. `CommunityTweetType`, `CommunitySearchTweetType` and `CommunityTweet` are exported from `scrapebadger.twitter`. + ## [0.84.0] - 2026-11-29 ScrapeBadger replaced rate-limit tiers and per-minute limits with one number per account: **max concurrency**, how many requests the account may run at the same time across all of its API keys. There is no per-minute limit any more. (SCR-736) diff --git a/docs/twitter.md b/docs/twitter.md index 1a64b76..2f905e8 100644 --- a/docs/twitter.md +++ b/docs/twitter.md @@ -127,6 +127,17 @@ async with ScrapeBadger(api_key="your-key") as client: # Get members members = await client.twitter.communities.get_members("123456") + + # Search tweets across every community (X's Top and Latest tabs). + # Each tweet names the community it was posted in. + from scrapebadger.twitter import CommunitySearchTweetType + + page = await client.twitter.communities.search_tweets_across_communities( + "web scraping", + tweet_type=CommunitySearchTweetType.LATEST, + ) + for tweet in page.data: + print(tweet.community_id, tweet.community_name, tweet.text) ``` ### Trending Topics @@ -239,7 +250,7 @@ async def handle_webhook(request): | **Tweets** | `get_by_id`, `get_by_ids`, `search`, `search_all`, `get_user_tweets`, `get_user_tweets_all`, `get_replies`, `get_retweeters`, `get_favoriters`, `get_similar` | | **Users** | `get_by_id`, `get_by_username`, `get_about`, `search`, `search_all`, `get_followers`, `get_followers_all`, `get_following`, `get_following_all`, `get_follower_ids`, `get_following_ids`, `get_latest_followers`, `get_latest_following`, `get_verified_followers`, `get_followers_you_know`, `get_subscriptions`, `get_highlights` | | **Lists** | `get_detail`, `search`, `get_tweets`, `get_tweets_all`, `get_members`, `get_members_all`, `get_subscribers`, `get_my_lists` | -| **Communities** | `get_detail`, `search`, `get_tweets`, `get_tweets_all`, `get_members`, `get_moderators`, `search_tweets`, `get_timeline` | +| **Communities** | `get_detail`, `search`, `get_tweets`, `get_tweets_all`, `get_members`, `get_moderators`, `search_tweets`, `search_tweets_across_communities`, `search_tweets_across_communities_all`, `get_timeline` | | **Trends** | `get_trends`, `get_place_trends`, `get_available_locations` | | **Geo** | `get_detail`, `search` | | **Streams** | `create_monitor`, `list_monitors`, `get_monitor`, `update_monitor`, `pause_monitor`, `resume_monitor`, `delete_monitor`, `list_billing_logs`, `connect` (`list_delivery_logs` is deprecated: delivered tweets are no longer stored) | diff --git a/pyproject.toml b/pyproject.toml index fbfa0af..231178d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "scrapebadger" -version = "0.84.0" +version = "0.85.0" description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more" readme = "README.md" license = { text = "MIT" } diff --git a/src/scrapebadger/__init__.py b/src/scrapebadger/__init__.py index 1c31bdc..367af22 100644 --- a/src/scrapebadger/__init__.py +++ b/src/scrapebadger/__init__.py @@ -1356,7 +1356,7 @@ async def main(): ZestimateHistoryPoint as ZillowZestimateHistoryPoint, ) -__version__ = "0.84.0" +__version__ = "0.85.0" __all__ = [ # TikTok core models diff --git a/src/scrapebadger/_internal/client.py b/src/scrapebadger/_internal/client.py index 5de6623..a1f35b3 100644 --- a/src/scrapebadger/_internal/client.py +++ b/src/scrapebadger/_internal/client.py @@ -59,7 +59,7 @@ _CONCURRENCY_ERRORS = frozenset({"concurrency_limit_exceeded", "trial_concurrency"}) # User agent for SDK requests -SDK_VERSION = "0.84.0" +SDK_VERSION = "0.85.0" USER_AGENT = f"scrapebadger-python/{SDK_VERSION}" diff --git a/src/scrapebadger/twitter/__init__.py b/src/scrapebadger/twitter/__init__.py index 88d1363..6ab6003 100644 --- a/src/scrapebadger/twitter/__init__.py +++ b/src/scrapebadger/twitter/__init__.py @@ -30,6 +30,9 @@ CommunityBanner, CommunityMember, CommunityRule, + CommunitySearchTweetType, + CommunityTweet, + CommunityTweetType, Hashtag, List, Location, @@ -81,6 +84,9 @@ "CommunityBanner", "CommunityMember", "CommunityRule", + "CommunitySearchTweetType", + "CommunityTweet", + "CommunityTweetType", # Stream WebSocket event models "ConnectedEvent", "DeliveryLog", diff --git a/src/scrapebadger/twitter/communities.py b/src/scrapebadger/twitter/communities.py index 9b136ac..e889b7d 100644 --- a/src/scrapebadger/twitter/communities.py +++ b/src/scrapebadger/twitter/communities.py @@ -8,7 +8,14 @@ from typing import TYPE_CHECKING from scrapebadger._internal.pagination import PaginatedResponse, paginate -from scrapebadger.twitter.models import Community, CommunityMember, CommunityTweetType, Tweet +from scrapebadger.twitter.models import ( + Community, + CommunityMember, + CommunitySearchTweetType, + CommunityTweet, + CommunityTweetType, + Tweet, +) if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -290,6 +297,86 @@ async def search_tweets( data = [Tweet.model_validate(item) for item in response.get("data", []) or []] return PaginatedResponse(data=data, next_cursor=response.get("next_cursor")) + async def search_tweets_across_communities( + self, + query: str, + *, + tweet_type: CommunitySearchTweetType = CommunitySearchTweetType.TOP, + count: int = 20, + cursor: str | None = None, + ) -> PaginatedResponse[CommunityTweet]: + """Search tweets posted in communities, across every community. + + These are the Top and Latest tabs of X's community search page. Each + tweet names the community it was posted in (``community_id``, + ``community_name``), so a keyword leads to the communities that talk + about it. ``search`` finds communities by name; ``search_tweets`` + searches inside one community. + + Args: + query: Search query string. + tweet_type: Tab to read (TOP or LATEST). + count: Number of tweets to ask for (1-100). X decides the page + size, usually 10 to 25 tweets. + cursor: Pagination cursor: the ``next_cursor`` of the previous + response of the same query, unchanged. + + Returns: + Paginated response containing tweets with their community. + + Example: + ```python + from scrapebadger.twitter import CommunitySearchTweetType + + page = await client.twitter.communities.search_tweets_across_communities( + "web scraping", + tweet_type=CommunitySearchTweetType.LATEST, + ) + for tweet in page.data: + print(tweet.community_id, tweet.community_name, tweet.text) + ``` + """ + response = await self._client.get( + "/v1/twitter/communities/search_tweets", + params={ + "query": query, + "tweet_type": tweet_type.value, + "count": count, + "cursor": cursor, + }, + ) + data = [CommunityTweet.model_validate(item) for item in response.get("data", []) or []] + return PaginatedResponse(data=data, next_cursor=response.get("next_cursor")) + + async def search_tweets_across_communities_all( + self, + query: str, + *, + tweet_type: CommunitySearchTweetType = CommunitySearchTweetType.TOP, + max_pages: int | None = None, + max_items: int | None = None, + ) -> AsyncIterator[CommunityTweet]: + """Iterate through tweets found across communities with automatic pagination. + + Args: + query: Search query string. + tweet_type: Tab to read (TOP or LATEST). + max_pages: Maximum number of pages to fetch. + max_items: Maximum number of tweets to yield. + + Yields: + Tweets with the community each was posted in. + """ + async for tweet in paginate( + self._client, + "/v1/twitter/communities/search_tweets", + {"query": query, "tweet_type": tweet_type.value}, + CommunityTweet.model_validate, + max_pages=max_pages, + max_items=max_items, + ): + yield tweet + async def get_timeline( self, *, diff --git a/src/scrapebadger/twitter/models.py b/src/scrapebadger/twitter/models.py index ee18eef..32b2da4 100644 --- a/src/scrapebadger/twitter/models.py +++ b/src/scrapebadger/twitter/models.py @@ -76,6 +76,18 @@ class CommunityTweetType(StrEnum): MEDIA = "Media" +class CommunitySearchTweetType(StrEnum): + """Tab of the search of tweets across communities. + + Attributes: + TOP: Tweets ranked by X. + LATEST: Most recent tweets first. + """ + + TOP = "Top" + LATEST = "Latest" + + # ============================================================================= # Base Configuration # ============================================================================= @@ -410,6 +422,23 @@ def created_at_datetime(self) -> datetime | None: return None +class CommunityTweet(Tweet): + """A tweet found by a search across communities, with its community. + + Everything a :class:`Tweet` has, plus the community the tweet was posted + in. Pass ``community_id`` to ``communities.get_detail`` or + ``communities.get_tweets``. + + Attributes: + community_id: ID of the community the tweet was posted in. ``None`` for + the rare result X returns without a community. + community_name: Name of that community. + """ + + community_id: str | None = None + community_name: str | None = None + + class User(_BaseModel): """A Twitter user profile. diff --git a/tests/test_twitter_communities_search_tweets.py b/tests/test_twitter_communities_search_tweets.py new file mode 100644 index 0000000..86d6d60 --- /dev/null +++ b/tests/test_twitter_communities_search_tweets.py @@ -0,0 +1,117 @@ +"""SCR-756: tweets across communities (``GET /v1/twitter/communities/search_tweets``). + +The Top and Latest tabs of X's community search page: a search of tweets across +every community, where each tweet names the community it was posted in. The API +sends ``community_id`` and ``community_name`` next to the usual tweet fields; +the plain ``Tweet`` model would drop them. +""" + +from __future__ import annotations + +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from scrapebadger._internal.client import BaseClient +from scrapebadger._internal.config import ClientConfig +from scrapebadger.twitter import CommunitySearchTweetType, CommunityTweet, CommunityTweetType, Tweet +from scrapebadger.twitter.communities import CommunitiesClient + +PATH = "/v1/twitter/communities/search_tweets" + + +def _tweet(tweet_id: str, community_id: str | None, community_name: str | None) -> dict[str, Any]: + return { + "id": tweet_id, + "text": f"tweet {tweet_id}", + "username": "someone", + "view_count": "12", + "community_id": community_id, + "community_name": community_name, + } + + +@pytest.fixture +def communities() -> CommunitiesClient: + return CommunitiesClient(BaseClient(ClientConfig(api_key="test_key", max_retries=1))) + + +async def test_each_tweet_carries_its_community(communities: CommunitiesClient) -> None: + page: dict[str, Any] = { + "data": [_tweet("1", "100", "Python"), _tweet("2", None, None)], + "next_cursor": "NEXT", + } + communities._client.get = AsyncMock(return_value=page) # type: ignore[method-assign] + + result = await communities.search_tweets_across_communities("python") + + assert all(isinstance(t, CommunityTweet) and isinstance(t, Tweet) for t in result.data) + assert [(t.id, t.community_id, t.community_name) for t in result.data] == [ + ("1", "100", "Python"), + ("2", None, None), + ] + assert result.data[0].text == "tweet 1" + assert result.next_cursor == "NEXT" + + +async def test_request_defaults_to_the_top_tab(communities: CommunitiesClient) -> None: + communities._client.get = AsyncMock(return_value={"data": []}) # type: ignore[method-assign] + + await communities.search_tweets_across_communities("web 3") + + path, kwargs = communities._client.get.call_args[0][0], communities._client.get.call_args[1] + assert path == PATH + assert kwargs["params"] == {"query": "web 3", "tweet_type": "Top", "count": 20, "cursor": None} + + +async def test_latest_tab_count_and_cursor_are_sent(communities: CommunitiesClient) -> None: + communities._client.get = AsyncMock(return_value={"data": None}) # type: ignore[method-assign] + + result = await communities.search_tweets_across_communities( + "web 3", tweet_type=CommunitySearchTweetType.LATEST, count=40, cursor="CUR" + ) + + assert communities._client.get.call_args[1]["params"] == { + "query": "web 3", + "tweet_type": "Latest", + "count": 40, + "cursor": "CUR", + } + assert result.data == [] + assert result.next_cursor is None + + +async def test_all_pages_with_the_tab_and_stops_at_max_items( + communities: CommunitiesClient, +) -> None: + pages = [ + {"data": [_tweet("1", "100", "Python"), _tweet("2", "100", "Python")], "next_cursor": "P2"}, + {"data": [_tweet("3", "200", "PyData"), _tweet("4", "200", "PyData")], "next_cursor": None}, + ] + communities._client.get = AsyncMock(side_effect=pages) # type: ignore[method-assign] + + got = [ + (t.id, t.community_id) + async for t in communities.search_tweets_across_communities_all( + "python", tweet_type=CommunitySearchTweetType.LATEST, max_items=3 + ) + ] + + assert got == [("1", "100"), ("2", "100"), ("3", "200")] + calls = communities._client.get.call_args_list + assert [c[0][0] for c in calls] == [PATH, PATH] + assert calls[0][1]["params"]["tweet_type"] == "Latest" + assert calls[1][1]["params"]["cursor"] == "P2" + + +def test_the_search_tab_has_no_media_option() -> None: + assert [t.value for t in CommunitySearchTweetType] == ["Top", "Latest"] + # the per-community filter keeps its three values, and is importable as documented + assert [t.value for t in CommunityTweetType] == ["Top", "Latest", "Media"] + + +def test_a_plain_tweet_drops_the_community_and_the_new_model_keeps_it() -> None: + raw = _tweet("1", "100", "Python") + assert not hasattr(Tweet.model_validate(raw), "community_id") + assert CommunityTweet.model_validate(raw).community_name == "Python" diff --git a/uv.lock b/uv.lock index 485e93d..946da05 100644 --- a/uv.lock +++ b/uv.lock @@ -930,7 +930,7 @@ wheels = [ [[package]] name = "scrapebadger" -version = "0.84.0" +version = "0.85.0" source = { editable = "." } dependencies = [ { name = "httpx" },