Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
13 changes: 12 additions & 1 deletion docs/twitter.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) |
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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" }
Expand Down
2 changes: 1 addition & 1 deletion src/scrapebadger/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1356,7 +1356,7 @@ async def main():
ZestimateHistoryPoint as ZillowZestimateHistoryPoint,
)

__version__ = "0.84.0"
__version__ = "0.85.0"

__all__ = [
# TikTok core models
Expand Down
2 changes: 1 addition & 1 deletion src/scrapebadger/_internal/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"


Expand Down
6 changes: 6 additions & 0 deletions src/scrapebadger/twitter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
CommunityBanner,
CommunityMember,
CommunityRule,
CommunitySearchTweetType,
CommunityTweet,
CommunityTweetType,
Hashtag,
List,
Location,
Expand Down Expand Up @@ -81,6 +84,9 @@
"CommunityBanner",
"CommunityMember",
"CommunityRule",
"CommunitySearchTweetType",
"CommunityTweet",
"CommunityTweetType",
# Stream WebSocket event models
"ConnectedEvent",
"DeliveryLog",
Expand Down
89 changes: 88 additions & 1 deletion src/scrapebadger/twitter/communities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
*,
Expand Down
29 changes: 29 additions & 0 deletions src/scrapebadger/twitter/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
# =============================================================================
Expand Down Expand Up @@ -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.

Expand Down
117 changes: 117 additions & 0 deletions tests/test_twitter_communities_search_tweets.py
Original file line number Diff line number Diff line change
@@ -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"
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading