twikit version: 2.3.3
Python: 3.11
Description
User.__init__ and Client.request crash with KeyError when the Twitter/X API returns JSON responses with missing fields that twikit assumes are always present.
Bug 1: user.py — KeyError in User.__init__
Multiple fields in User.__init__ are accessed via direct dict lookup (legacy['key']). Twitter's API does not always include all legacy user fields in its responses, causing KeyError for fields like entities.description.urls, withheld_in_countries, and potentially any of the ~30 fields parsed in the constructor.
Traceback:
File "twikit/client/client.py", line 1402, in get_user_by_screen_name
return User(self, user_data)
File "twikit/user.py", line 102, in __init__
self.description_urls: list = legacy['entities']['description']['urls']
KeyError: 'urls'
After the first crash is hit, subsequent fields also fail:
File "twikit/user.py", line 124, in __init__
self.withheld_in_countries: list[str] = legacy['withheld_in_countries']
KeyError: 'withheld_in_countries'
Bug 2: client/client.py — KeyError in error handling
Client.request accesses response_data['errors'][0]['code'] directly, but Twitter sometimes returns error objects without a code field.
This causes a KeyError during error handling itself, masking the original error.
Expected behavior
twikit should handle missing fields gracefully using .get() with sensible defaults instead of crashing.
Environment
- Observed during normal polling of user timelines via
get_user_tweets() and get_user_by_screen_name()
- Reproducible intermittently — Twitter API responses vary in which fields they include
twikit version: 2.3.3
Python: 3.11
Description
User.__init__andClient.requestcrash withKeyErrorwhen the Twitter/X API returns JSON responses with missing fields that twikit assumes are always present.Bug 1:
user.py— KeyError inUser.__init__Multiple fields in
User.__init__are accessed via direct dict lookup (legacy['key']). Twitter's API does not always include all legacy user fields in its responses, causingKeyErrorfor fields likeentities.description.urls,withheld_in_countries, and potentially any of the ~30 fields parsed in the constructor.Traceback:
After the first crash is hit, subsequent fields also fail:
Bug 2:
client/client.py— KeyError in error handlingClient.requestaccessesresponse_data['errors'][0]['code']directly, but Twitter sometimes returns error objects without acodefield.This causes a
KeyErrorduring error handling itself, masking the original error.Expected behavior
twikit should handle missing fields gracefully using
.get()with sensible defaults instead of crashing.Environment
get_user_tweets()andget_user_by_screen_name()