or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-interface.mdauthentication.mdclient-v2.mddata-models.mdindex.mdlegacy-api.mdstreaming.mdutilities.md

index.mddocs/

0

# Tweepy

1

2

A comprehensive Python library for accessing the X API (Twitter), providing both synchronous and asynchronous interfaces to Twitter's API v1.1 (legacy) and API v2. Tweepy enables developers to build applications that interact with X/Twitter's social media platform, offering complete coverage of API endpoints for posting tweets, managing user accounts, searching content, streaming real-time data, and handling media uploads.

3

4

## Package Information

5

6

- **Package Name**: tweepy

7

- **Language**: Python

8

- **Installation**: `pip install tweepy`

9

- **Optional Dependencies**: `pip install tweepy[async]` for async support

10

11

## Core Imports

12

13

```python

14

import tweepy

15

```

16

17

Common imports for different functionality:

18

19

```python

20

# Twitter API v2 Client

21

from tweepy import Client

22

23

# Authentication handlers

24

from tweepy import OAuth1UserHandler, OAuth2BearerHandler, OAuth2UserHandler

25

26

# Streaming

27

from tweepy import StreamingClient, StreamRule

28

29

# Data models

30

from tweepy import Tweet, User, Media, Space, List

31

32

# Legacy API v1.1

33

from tweepy import API

34

35

# Pagination utilities

36

from tweepy import Cursor, Paginator

37

```

38

39

## Basic Usage

40

41

### Twitter API v2 Client Example

42

43

```python

44

import tweepy

45

46

# Initialize client with Bearer token (App-only auth)

47

client = tweepy.Client(bearer_token="your_bearer_token")

48

49

# Search for recent tweets

50

tweets = client.search_recent_tweets(query="python programming", max_results=10)

51

52

# Print tweet text and author info

53

for tweet in tweets.data:

54

print(f"@{tweet.author_id}: {tweet.text}")

55

56

# Get user information

57

user = client.get_user(username="twitter")

58

print(f"User: {user.data.name} (@{user.data.username})")

59

print(f"Followers: {user.data.public_metrics['followers_count']}")

60

```

61

62

### User Authentication Example

63

64

```python

65

import tweepy

66

67

# OAuth 1.0a User Context authentication

68

auth = tweepy.OAuth1UserHandler(

69

consumer_key="your_consumer_key",

70

consumer_secret="your_consumer_secret",

71

access_token="your_access_token",

72

access_token_secret="your_access_token_secret"

73

)

74

75

# Create client with user authentication

76

client = tweepy.Client(

77

consumer_key="your_consumer_key",

78

consumer_secret="your_consumer_secret",

79

access_token="your_access_token",

80

access_token_secret="your_access_token_secret"

81

)

82

83

# Post a tweet (requires user auth)

84

response = client.create_tweet(text="Hello Twitter from Tweepy!")

85

print(f"Tweet posted: {response.data['id']}")

86

```

87

88

### Streaming Example

89

90

```python

91

import tweepy

92

93

class TweetPrinter(tweepy.StreamingClient):

94

def on_tweet(self, tweet):

95

print(f"New tweet: {tweet.text}")

96

97

# Initialize streaming client

98

stream = TweetPrinter(bearer_token="your_bearer_token")

99

100

# Add filter rules

101

rule = tweepy.StreamRule("python -is:retweet lang:en")

102

stream.add_rules(rule)

103

104

# Start streaming (blocking call)

105

stream.filter()

106

```

107

108

## Architecture

109

110

Tweepy provides multiple interfaces for different use cases:

111

112

- **Client (API v2)**: Modern interface with comprehensive v2 endpoint coverage, optimized for new applications

113

- **API (v1.1)**: Legacy interface for backward compatibility and v1.1-only features

114

- **StreamingClient**: Real-time tweet streaming with rule-based filtering

115

- **Authentication**: Multiple OAuth flows (1.0a, 2.0 Bearer Token, 2.0 Authorization Code)

116

- **Data Models**: Rich objects (Tweet, User, Media, etc.) with full field access

117

- **Pagination**: Automatic handling of paginated responses

118

- **Async Support**: Full async/await interface for non-blocking operations

119

120

## Capabilities

121

122

### Twitter API v2 Client

123

124

Comprehensive interface to Twitter API v2 endpoints including tweet management, user operations, timelines, search, lists, spaces, direct messages, and media upload. Supports both app-only and user authentication contexts.

125

126

```python { .api }

127

class Client:

128

def __init__(self, bearer_token=None, consumer_key=None, consumer_secret=None,

129

access_token=None, access_token_secret=None, *,

130

return_type=Response, wait_on_rate_limit=False): ...

131

132

# Tweet operations

133

def create_tweet(self, text=None, **kwargs): ...

134

def delete_tweet(self, id, **kwargs): ...

135

def get_tweet(self, id, **kwargs): ...

136

def search_recent_tweets(self, query, **kwargs): ...

137

138

# User operations

139

def get_me(self, **kwargs): ...

140

def get_user(self, *, id=None, username=None, **kwargs): ...

141

def follow_user(self, target_user_id, **kwargs): ...

142

143

# Streaming and more...

144

```

145

146

[Twitter API v2 Client](./client-v2.md)

147

148

### Authentication

149

150

Multiple OAuth authentication handlers supporting different application types and use cases, from simple app-only access to full user authorization flows.

151

152

```python { .api }

153

class OAuth1UserHandler:

154

def __init__(self, consumer_key, consumer_secret, access_token=None,

155

access_token_secret=None, callback=None): ...

156

def get_authorization_url(self, signin_with_twitter=False, access_type=None): ...

157

def get_access_token(self, verifier=None): ...

158

159

class OAuth2BearerHandler:

160

def __init__(self, bearer_token): ...

161

162

class OAuth2UserHandler:

163

def __init__(self, *, client_id, redirect_uri, scope, client_secret=None): ...

164

def get_authorization_url(self): ...

165

def fetch_token(self, authorization_response): ...

166

```

167

168

[Authentication](./authentication.md)

169

170

### Real-time Streaming

171

172

Rule-based streaming client for receiving real-time tweets matching specified criteria, with customizable event handlers and automatic reconnection.

173

174

```python { .api }

175

class StreamingClient:

176

def __init__(self, bearer_token, *, chunk_size=512, daemon=False,

177

max_retries=float('inf'), **kwargs): ...

178

def filter(self, *, threaded=False, **kwargs): ...

179

def sample(self, *, threaded=False, **kwargs): ...

180

def add_rules(self, add, **kwargs): ...

181

def delete_rules(self, ids, **kwargs): ...

182

def get_rules(self, **kwargs): ...

183

184

# Event handlers (override these)

185

def on_tweet(self, tweet): ...

186

def on_data(self, raw_data): ...

187

```

188

189

[Streaming](./streaming.md)

190

191

### Data Models

192

193

Rich data model classes representing Twitter objects with full field access and type safety, including tweets, users, media, spaces, lists, and more.

194

195

```python { .api }

196

class Tweet:

197

# Core attributes

198

id: str

199

text: str

200

author_id: str

201

created_at: datetime

202

public_metrics: dict

203

# ... all other v2 tweet fields

204

205

class User:

206

id: str

207

name: str

208

username: str

209

created_at: datetime

210

public_metrics: dict

211

# ... all other v2 user fields

212

213

class Media:

214

media_key: str

215

type: str

216

url: str

217

# ... all other media fields

218

```

219

220

[Data Models](./data-models.md)

221

222

### Legacy API (v1.1)

223

224

Complete interface to Twitter API v1.1 endpoints for backward compatibility and access to v1.1-specific functionality not yet available in v2.

225

226

```python { .api }

227

class API:

228

def __init__(self, auth=None, *, cache=None, host='api.twitter.com',

229

parser=None, **kwargs): ...

230

231

# Timeline methods

232

def home_timeline(self, **kwargs): ...

233

def user_timeline(self, **kwargs): ...

234

235

# Tweet methods

236

def update_status(self, status, **kwargs): ...

237

def get_status(self, id, **kwargs): ...

238

239

# User methods

240

def get_user(self, **kwargs): ...

241

def search_users(self, q, **kwargs): ...

242

243

# Many more v1.1 methods...

244

```

245

246

[Legacy API](./legacy-api.md)

247

248

### Utilities and Pagination

249

250

Utility classes for pagination, caching, error handling, and other common functionality to simplify API usage and improve application performance.

251

252

```python { .api }

253

class Paginator:

254

def __init__(self, method, *args, **kwargs): ...

255

def flatten(self, limit=None): ...

256

def get_next(self): ...

257

def get_previous(self): ...

258

259

class Cursor:

260

def __init__(self, method, *args, **kwargs): ...

261

def items(self, limit=None): ...

262

def pages(self, limit=None): ...

263

264

# Caching classes

265

class MemoryCache: ...

266

class FileCache: ...

267

```

268

269

[Utilities](./utilities.md)

270

271

### Asynchronous Interface

272

273

Complete async/await interface providing non-blocking access to all Twitter API functionality with identical method signatures to the synchronous interface.

274

275

```python { .api }

276

class AsyncClient:

277

# Identical methods to Client but async

278

async def create_tweet(self, text=None, **kwargs): ...

279

async def get_tweet(self, id, **kwargs): ...

280

async def search_recent_tweets(self, query, **kwargs): ...

281

282

class AsyncStreamingClient:

283

# Identical methods to StreamingClient but async

284

async def filter(self, **kwargs): ...

285

async def sample(self, **kwargs): ...

286

```

287

288

[Async Interface](./async-interface.md)

289

290

## Types

291

292

### Response Types

293

294

```python { .api }

295

from collections import namedtuple

296

297

Response = namedtuple("Response", ("data", "includes", "errors", "meta"))

298

StreamResponse = namedtuple("StreamResponse", ("data",))

299

```

300

301

### Exception Types

302

303

```python { .api }

304

class TweepyException(Exception):

305

"""Base Tweepy exception"""

306

307

class HTTPException(TweepyException):

308

"""HTTP request failure exception"""

309

310

class BadRequest(HTTPException):

311

"""400 Bad Request error"""

312

313

class Unauthorized(HTTPException):

314

"""401 Unauthorized error"""

315

316

class Forbidden(HTTPException):

317

"""403 Forbidden error"""

318

319

class NotFound(HTTPException):

320

"""404 Not Found error"""

321

322

class TooManyRequests(HTTPException):

323

"""429 Rate limit exceeded error"""

324

325

class TwitterServerError(HTTPException):

326

"""5xx server errors"""

327

```

328

329

### Field Constants

330

331

```python { .api }

332

# Tweet field constants

333

TWEET_FIELDS = (

334

"id", "text", "attachments", "author_id", "context_annotations",

335

"conversation_id", "created_at", "edit_controls", "entities", "geo",

336

"in_reply_to_user_id", "lang", "non_public_metrics", "organic_metrics",

337

"possibly_sensitive", "promoted_metrics", "public_metrics",

338

"referenced_tweets", "reply_settings", "source", "withheld"

339

)

340

341

PUBLIC_TWEET_FIELDS = (

342

"id", "text", "attachments", "author_id", "context_annotations",

343

"conversation_id", "created_at", "edit_controls", "entities", "geo",

344

"in_reply_to_user_id", "lang", "possibly_sensitive", "public_metrics",

345

"referenced_tweets", "reply_settings", "source", "withheld"

346

)

347

348

# User field constants

349

USER_FIELDS = (

350

"id", "name", "username", "created_at", "description", "entities",

351

"location", "pinned_tweet_id", "profile_image_url", "protected",

352

"public_metrics", "url", "verified", "verified_type", "withheld"

353

)

354

355

# Media field constants

356

MEDIA_FIELDS = (

357

"media_key", "type", "url", "duration_ms", "height", "non_public_metrics",

358

"organic_metrics", "preview_image_url", "promoted_metrics",

359

"public_metrics", "width", "alt_text", "variants"

360

)

361

362

# Additional field constants for Lists, Spaces, Places, Polls, etc.

363

LIST_FIELDS = ("id", "name", "created_at", "description", "follower_count", "member_count", "private", "owner_id")

364

SPACE_FIELDS = ("id", "state", "created_at", "ended_at", "host_ids", "lang", "is_ticketed", "invited_user_ids", "participant_count", "subscriber_count", "scheduled_start", "speaker_ids", "started_at", "title", "topic_ids", "updated_at", "creator_id")

365

PLACE_FIELDS = ("id", "full_name", "name", "country", "country_code", "geo", "place_type")

366

POLL_FIELDS = ("id", "options", "duration_minutes", "end_datetime", "voting_status")

367

DIRECT_MESSAGE_EVENT_FIELDS = ("id", "text", "event_type", "created_at", "sender_id", "dm_conversation_id", "referenced_tweet", "media_keys", "attachments")

368

```