Skip to content

KeyError in User.__init__ and Client.request when Twitter API omits expected fields #417

@PawiX25

Description

@PawiX25

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions