Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the bookmarks count to tweet #286

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Add the bookmarks count to tweet #286

wants to merge 2 commits into from

Conversation

ankh2054
Copy link

@ankh2054 ankh2054 commented Jan 11, 2025

As per twitter API docs - https://developer.x.com/en/docs/x-api/tweets/lookup/api-reference/get-tweets-id

Summary by Sourcery

New Features:

  • Added bookmark_count field to the Tweet object, allowing access to the number of times a tweet has been bookmarked.

Summary by CodeRabbit

  • New Features

    • Added bookmark count tracking for tweets across multiple components.
    • Enhanced tweet metrics to include number of bookmarks.
  • Bug Fixes

    • Corrected __ne__ method implementation for consistent comparison behavior.
  • Documentation

    • Updated class and method documentation to reflect new bookmark count attribute.
  • Chores

    • Removed several example scripts related to tweet management and direct messaging.
    • Updated .gitignore to exclude unnecessary files and directories.
    • Improved package management in setup.py for better package discovery.

Copy link

sourcery-ai bot commented Jan 11, 2025

Reviewer's Guide by Sourcery

This pull request adds the bookmark_count attribute to the Tweet object, allowing access to the number of bookmarks a tweet has received. This feature utilizes the Twitter API's public metrics to retrieve the bookmark count.

Class diagram showing Tweet class modifications

classDiagram
    class Tweet {
        +str text
        +int favorite_count
        +list media
        +int|None bookmark_count
        +__init__(client, data, user)
        +__eq__(__value)
        +__ne__(__value)
    }
    note for Tweet "Added bookmark_count attribute
fetched from public_metrics or legacy data"
Loading

Class diagram showing TweetEngagementEvent modifications

classDiagram
    class TweetEngagementEvent {
        +int|None like_count
        +int|None retweet_count
        +str|None view_count
        +str|None view_count_state
        +int|None quote_count
        +int|None reply_count
        +int|None bookmark_count
    }
    note for TweetEngagementEvent "Added bookmark_count field"
Loading

File-Level Changes

Change Details Files
Added the bookmark_count field to the Tweet class.
  • Included the bookmark_count attribute in the Tweet class definition.
  • Initialized the bookmark_count attribute in the Tweet constructor using data from the public_metrics field if available, falling back to legacy data if necessary.
  • Added bookmark_count to the TweetEngagementEvent namedtuple in streaming.py.
  • Updated the example code to print the bookmark_count of a tweet if available.
twikit/guest/tweet.py
twikit/tweet.py
twikit/streaming.py
examples/example.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.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a 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. You can also use
    this command to specify where the summary should be inserted.

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 Jan 11, 2025

Walkthrough

The pull request removes several example scripts and introduces a new bookmark_count attribute across multiple files in the Twikit library to track the number of bookmarks for tweets. This enhancement adds support for retrieving and displaying the bookmark count from tweet data, utilizing both public_metrics and legacy data structures. The changes are consistent across the tweet-related classes and streaming events, ensuring comprehensive coverage of the new metric.

Changes

File Change Summary
examples/example.py File content removed; previously contained an async script for Twitter API interactions.
twikit/guest/tweet.py Added bookmark_count attribute to Tweet class with initialization logic.
twikit/streaming.py Updated TweetEngagementEvent to include bookmark_count.
twikit/tweet.py Added bookmark_count attribute to main Tweet class.
.gitignore Added entries to ignore specific directories and files.
example_project/test_twikit.py Introduced an async testing script for the twikit library.
examples/delete_all_tweets.py File removed; previously contained a script for deleting all tweets.
examples/dm_auto_reply.py File removed; previously contained a script for automated DM replies.
examples/download_tweet_media.py File removed; previously contained a script for downloading tweet media.
examples/guest.py File removed; previously contained a script for guest client interactions.
examples/listen_for_new_tweets.py File removed; previously contained a script for monitoring new tweets.
setup.py Added find_packages() function and updated package data inclusion method.
twikit/client/__init__.py Introduced new imports and updated the public interface with __all__.

Possibly related issues

  • d60/twikit#285: Directly addresses the request to add the ability to view public bookmarks and the number of times a tweet has been bookmarked.

Poem

🐰 A Rabbit's Ode to Bookmarks 🔖
Tweets now whisper their hidden fame,
Bookmarks counted, no longer tame.
Numbers dancing, metrics bright,
A digital tale of reader's delight!
Hop along, data's new refrain! 📊

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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 @ankh2054 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding tests to verify bookmark count parsing from both public_metrics and legacy data structures
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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.

twikit/guest/tweet.py Outdated Show resolved Hide resolved
@ankh2054 ankh2054 changed the title Add the number of bookmarks of the tweet. Add the bookmarks count to tweet Jan 11, 2025
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: 3

🧹 Nitpick comments (2)
example_project/test_twikit.py (1)

4-16: Add docstring to explain script purpose and usage.

The script would benefit from a docstring explaining its purpose, required environment variables, and usage instructions.

 async def main():
+    """
+    Example script demonstrating tweet bookmark count retrieval.
+    
+    Environment variables:
+        TWIKIT_COOKIES_PATH: Path to the cookies.json file
+        TWEET_ID: ID of the tweet to fetch
+    """
     client = Client()
setup.py (1)

Line range hint 15-21: Consider using minimum version requirements.

Instead of pinning exact versions, consider specifying minimum versions to allow for compatible updates and security patches.

     install_requires=[
-        'httpx[socks]',
-        'filetype',
-        'beautifulsoup4',
-        'pyotp',
-        'lxml'
+        'httpx[socks]>=0.24.0',
+        'filetype>=1.2.0',
+        'beautifulsoup4>=4.11.0',
+        'pyotp>=2.8.0',
+        'lxml>=4.9.0'
     ],
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dfd1e7c and 96b9928.

📒 Files selected for processing (13)
  • .gitignore (1 hunks)
  • example_project/test_twikit.py (1 hunks)
  • examples/delete_all_tweets.py (0 hunks)
  • examples/dm_auto_reply.py (0 hunks)
  • examples/download_tweet_media.py (0 hunks)
  • examples/example.py (0 hunks)
  • examples/guest.py (0 hunks)
  • examples/listen_for_new_tweets.py (0 hunks)
  • setup.py (3 hunks)
  • twikit/client/__init__.py (1 hunks)
  • twikit/guest/tweet.py (2 hunks)
  • twikit/streaming.py (2 hunks)
  • twikit/tweet.py (2 hunks)
💤 Files with no reviewable changes (6)
  • examples/guest.py
  • examples/download_tweet_media.py
  • examples/example.py
  • examples/delete_all_tweets.py
  • examples/dm_auto_reply.py
  • examples/listen_for_new_tweets.py
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🚧 Files skipped from review as they are similar to previous changes (3)
  • twikit/tweet.py
  • twikit/streaming.py
  • twikit/guest/tweet.py
🔇 Additional comments (2)
twikit/client/__init__.py (1)

1-4: LGTM! Well-structured module initialization.

The imports and __all__ declaration follow Python best practices for module organization and explicit public interface definition.

setup.py (1)

13-13: LGTM! Good use of find_packages().

Using find_packages() is the recommended approach for automatic package discovery.

client = Client()

# Load your saved cookies if you have them
client.load_cookies('path/to/cookies.json')
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use environment variables or command-line arguments for the cookies path.

Hardcoded paths reduce flexibility and portability. Consider using environment variables or command-line arguments.

-    client.load_cookies('path/to/cookies.json')
+    cookies_path = os.getenv('TWIKIT_COOKIES_PATH', 'cookies.json')
+    client.load_cookies(cookies_path)

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +14 to +15
tweet = await client.get_tweet_by_id('1519480761749016577')
print(f"Tweet bookmark count: {tweet.bookmark_count}")
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and make tweet ID configurable.

The script needs proper error handling for API calls and should make the tweet ID configurable.

-    tweet = await client.get_tweet_by_id('1519480761749016577')
-    print(f"Tweet bookmark count: {tweet.bookmark_count}")
+    tweet_id = os.getenv('TWEET_ID', '1519480761749016577')
+    try:
+        tweet = await client.get_tweet_by_id(tweet_id)
+        print(f"Tweet bookmark count: {tweet.bookmark_count}")
+    except Exception as e:
+        print(f"Error fetching tweet: {e}")

Committable suggestion skipped: line range outside the PR's diff.

@@ -24,5 +25,5 @@
long_description_content_type='text/markdown',
license='MIT',
url='https://github.com/d60/twikit',
package_data={'twikit': ['py.typed']}
include_package_data=True
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Remove include_package_data=True as it's not needed

The codebase doesn't contain any non-Python package data files that need to be included in the distribution. The existing non-Python files are development-related (documentation, requirements, linter config) and don't need to be packaged. You can safely remove this setting from setup.py.

🔗 Analysis chain

Verify MANIFEST.in file exists.

The include_package_data=True setting requires a MANIFEST.in file to specify which non-Python files should be included in the distribution.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if MANIFEST.in exists and contains necessary include statements
if [ -f "MANIFEST.in" ]; then
    echo "MANIFEST.in contents:"
    cat MANIFEST.in
else
    echo "Warning: MANIFEST.in file not found"
fi

Length of output: 105


Script:

#!/bin/bash
# Search for non-Python files that might need to be included in distribution
fd --type f \
   --exclude '*.py' \
   --exclude '*.pyc' \
   --exclude '__pycache__' \
   --exclude '.git' \
   --exclude '.github' \
   --exclude 'tests' \
   --exclude '*.md' \
   --exclude 'LICENSE' \
   --exclude '.gitignore' \
   --exclude 'setup.py' \
   --exclude 'setup.cfg' \
   --exclude 'pyproject.toml' \
   --exclude '*.ini'

Length of output: 365

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.

1 participant