Skip to content

Conversation

T3los
Copy link

@T3los T3los commented Aug 12, 2025

Possible fix for a bug where client.get_tweet_by_id() throws a KeyError when the tweet has replies.

Summary by Sourcery

Bug Fixes:

  • Adjust reply_next_cursor lookup to use content.value instead of content.itemContent.value to avoid KeyError for tweets with replies

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue where additional replies in long tweet threads sometimes failed to load.
    • Corrected pagination handling to ensure subsequent pages of replies load consistently.
    • Improves reliability when expanding and navigating through reply chains.
    • No changes to the public API or user-facing settings.

Copy link

sourcery-ai bot commented Aug 12, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactor cursor extraction in get_tweet_by_id to use content.value instead of content.itemContent.value, preventing KeyError when handling tweets with replies.

Class diagram for updated get_tweet_by_id method in Client

classDiagram
    class Client {
        +async get_tweet_by_id(tweet_id)
        -_get_more_replies(tweet_id, reply_next_cursor)
    }
    Client --> "calls" _get_more_replies
    %% Highlight change in reply_next_cursor extraction
    class get_tweet_by_id {
        -reply_next_cursor = entries[-1]['content']['itemContent']['value']
        +reply_next_cursor = entries[-1]['content']['value']
    }
Loading

File-Level Changes

Change Details Files
Simplified reply cursor parsing to avoid missing key errors
  • Removed dependency on content.itemContent
  • Switched to directly reading content.value for cursor
twikit/client/client.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Walkthrough

Updated get_tweet_by_id to extract the next-replies cursor from entries[-1]['content']['value'] instead of entries[-1]['content']['itemContent']['value']. The pagination flow and call to _get_more_replies remain unchanged. No public interfaces were modified.

Changes

Cohort / File(s) Summary of Changes
Replies pagination cursor fix
twikit/client/client.py
Adjusted cursor extraction in get_tweet_by_id to read from content.value rather than content.itemContent.value; pagination and control flow unchanged; no signature changes.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TwitterAPI as Twitter API
  Client->>TwitterAPI: fetch tweet by ID
  TwitterAPI-->>Client: response with entries
  Client->>Client: parse entries[-1].content.value as cursor
  alt more replies available
    Client->>TwitterAPI: _get_more_replies(cursor)
    TwitterAPI-->>Client: additional replies
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Poem

I twitch my nose at threads that sprawl,
Hop to the cursor, heed the call.
From content.value, paths align,
Replies now queue in tidy line.
Thump-thump—pagination’s right,
A rabbit’s fix by moonlit night. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @T3los - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (2)
twikit/client/client.py (2)

1525-1531: Likely same KeyError in _get_more_replies: mirror the cursor extraction fallback.

When paginating more replies, the code still assumes entries[-1]['content']['itemContent']['value']. If the payload matches the shape you just fixed (content.value), this will throw the same KeyError on subsequent pages.

Recommend making it consistent and defensive:

-        if entries[-1]['entryId'].startswith('cursor'):
-            next_cursor = entries[-1]['content']['itemContent']['value']
-            _fetch_next_result = partial(self._get_more_replies, tweet_id, next_cursor)
+        if entries[-1]['entryId'].startswith('cursor'):
+            content = entries[-1].get('content', {})
+            next_cursor = content.get('value') or content.get('itemContent', {}).get('value')
+            _fetch_next_result = (
+                partial(self._get_more_replies, tweet_id, next_cursor)
+                if next_cursor is not None else None
+            )

1633-1641: Refactor cursor extraction across all client methods

The search script confirms that brittle entry['…']['content']['value'] and entry['…']['itemContent']['value'] reads occur in dozens of places (both in twikit/client/client.py and twikit/guest/client.py). We should centralize the fallback logic into a helper and replace every direct indexing with a safe extractor.

Key locations (non-exhaustive):

  • twikit/client/client.py – lines 1526, 1616, 755–761, 772–779, 830–834, 931–937, 1633–1637, 1723–1726, 1919–1922, 2004–2006, 2064–2066, 2284–2288, 2678–2680, 3524–3526, 3596–3598, 3627–3629, 3737–3739, 3951–3954, 3959–3962, 4022–4025, 4201–4204
  • twikit/guest/client.py – lines 401–404

Suggested approach:

  1. Add a private utility in client.py (or a shared module), e.g.:
    def _extract_cursor(entry):
        content = entry.get('content', {})
        # Twitter sometimes nests value under itemContent
        return content.get('value') or content.get('itemContent', {}).get('value')
  2. Replace every …['content']['value'] or …['item']['itemContent']['value'] with:
    cursor = _extract_cursor(entry_or_item)
  3. Remove all direct indexing to avoid future KeyErrors.

This consolidation will both eliminate repeated diffs and ensure uniform, defensive cursor handling.

🧹 Nitpick comments (1)
twikit/client/client.py (1)

1568-1574: Docstring example should use await.

The method is async; the example should reflect that to prevent confusion.

-        >>> tweet = client.get_tweet_by_id(target_tweet_id)
+        >>> tweet = await client.get_tweet_by_id(target_tweet_id)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b18105 and b5b56e0.

📒 Files selected for processing (1)
  • twikit/client/client.py (1 hunks)

@T3los T3los changed the title Update client.py Prevent KeyError when accessing content.value for next cursor Aug 12, 2025
@xiaoland
Copy link

xiaoland commented Aug 20, 2025

@T3los Thank you for your work!

There's a same pattern at

next_cursor = entries[-1]['content']['itemContent']['value']

May you also fix this? I have tested the change locally and it works well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants