-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsearch_recent.py
More file actions
43 lines (34 loc) · 1.35 KB
/
search_recent.py
File metadata and controls
43 lines (34 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Recent Search - X API v2
========================
Endpoint: GET https://api.x.com/2/tweets/search/recent
Docs: https://developer.x.com/en/docs/twitter-api/tweets/search/api-reference/get-tweets-search-recent
Authentication: Bearer Token (App-only)
Required env vars: BEARER_TOKEN
Note: Returns posts from the last 7 days.
This example demonstrates automatic pagination using the iterate() method
to fetch all pages of results.
"""
import os
import json
from xdk import Client
bearer_token = os.environ.get("BEARER_TOKEN")
client = Client(bearer_token=bearer_token)
query = '(from:XDevelopers -is:retweet) OR #XDevelopers'
def main():
# Search with automatic pagination
all_posts = []
for page in client.posts.search_recent(
query=query,
max_results=100, # Per page
tweet_fields=["author_id", "created_at"]
):
# Access data attribute (model uses extra='allow' so data should be available)
# Use getattr with fallback in case data field is missing from response
page_data = getattr(page, 'data', []) or []
all_posts.extend(page_data)
print(f"Fetched {len(page_data)} Posts (total: {len(all_posts)})")
print(f"\nTotal Posts: {len(all_posts)}")
print(json.dumps({"data": all_posts[:5]}, indent=4, sort_keys=True)) # Print first 5 as example
if __name__ == "__main__":
main()