E527 Add configurable API URL support for Capsolver captcha solver by izzzzzi · Pull Request #324 · d60/twikit · GitHub
[go: up one dir, main page]

Skip to content

Conversation

@izzzzzi
Copy link
@izzzzzi izzzzzi commented Mar 9, 2025

Add support for custom API endpoints in Capsolver

This commit enhances the Capsolver class by adding support for custom API endpoints. Users can now specify an alternative API URL when initializing the Capsolver instance, allowing for greater flexibility when working with different Capsolver API providers or self-hosted solutions.

Key changes:

  • Added a new api_url parameter to the Capsolver constructor with a default value of 'https://api.capsolver.com'
  • Updated the documentation to reflect the new parameter
  • Modified the create_task and get_task_result methods to use the custom API URL
  • Added trailing slash handling to ensure proper URL formatting

Example usage:

# Standard API
solver = Capsolver(api_key='your_api_key')

# Custom API endpoint
solver = Capsolver(
    api_key='your_api_key',
    api_url='https://custom-api.capsolver.com'
)

Summary by Sourcery

New Features:

  • Add the ability to configure the Capsolver API URL.

Summary by CodeRabbit

  • New Features
    • Enabled users to specify a custom CAPTCHA service endpoint instead of relying solely on the default address.
    • Improved consistency in endpoint formatting for a more reliable integration experience.

@sourcery-ai
Copy link
sourcery-ai bot commented Mar 9, 2025

Reviewer's Guide by Sourcery

This pull request introduces the ability to configure the base URL for the Capsolver API. A new api_url parameter has been added to the Capsolver class constructor, allowing users to specify a custom API endpoint. The create_task and get_task_result methods have been updated to use the configured api_url. Trailing slash handling was added to ensure proper URL formatting.

Sequence diagram for get_task_result with custom API URL

sequenceDiagram
    participant User
    participant Capsolver
    participant Custom API

    User->>Capsolver: get_task_result(task_id)
    Capsolver->>Custom API: POST /getTaskResult with task_id
    Custom API-->>Capsolver: Response (solution or status)
    Capsolver-->>User: Response (solution or status)
Loading

File-Level Changes

Change Details Files
Added the ability to configure the base URL for the Capsolver API.
  • Added an api_url parameter to the Capsolver class constructor.
  • Set the default value of api_url to 'https://api.capsolver.com'.
  • Updated the create_task method to use the configured api_url.
  • Updated the get_task_result method to use the configured api_url.
  • Added trailing slash removal from the api_url to ensure proper URL formatting.
twikit/_captcha/capsolver.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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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

@coderabbitai
Copy link
Contributor
coderabbitai bot commented Mar 9, 2025

Walkthrough

The update in twikit/_captcha/capsolver.py introduces a new parameter, api_url, in the Capsolver class. The parameter is added to the constructor signature and the class documentation, with a default value of 'https://api.capsolver.com'. Trailing slashes in the provided URL are removed upon initialization. Both the create_task and get_task_result methods now build their endpoint URLs dynamically using the api_url value instead of relying on hardcoded URLs.

Changes

File Changes
twikit/_captcha/capsolver.py - Added new api_url parameter to Capsolver constructor (default: 'https://api.capsolver.com')
- Updated class docstring to include API URL info
- Modified create_task and get_task_result methods to utilize api_url instead of hardcoded endpoints
- Implemented trailing slash removal in initialization

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as Capsolver
    participant A as API Server

    U->>C: Initialize Capsolver(api_url)
    U->>C: Call create_task(parameters)
    C->>A: POST {api_url}/create_task
    A-->>C: Respond with task_id
    U->>C: Call get_task_result(task_id)
    C->>A: GET {api_url}/get_task_result with task_id
    A-->>C: Respond with task result
    C-->>U: Return task result
Loading

Poem

Hopping through the code so light,
I’ve tweaked the URLs just right.
With a dash of slash removed,
My API calls are smoothly approved.
A rabbit’s hop in every byte, so bright!
🐇💻

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Overall Comments:

  • Consider adding input validation for the api_url parameter to ensure it's a valid URL.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 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.

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

🧹 Nitpick comments (2)
twikit/_captcha/capsolver.py (2)

44-51: Consider adding URL validation

The current implementation accepts any string as the API URL without validation. Consider adding basic URL format validation to ensure proper URL structure.

    def __init__(
        self,
        api_key: str,
        max_attempts: int = 3,
        get_result_interval: float = 1.0,
        use_blob_data: bool = False,
        api_url: str = 'https://api.capsolver.com'
    ) -> None:
        self.api_key = api_key
        self.get_result_interval = get_result_interval
        self.max_attempts = max_attempts
        self.use_blob_data = use_blob_data
+       # Basic validation to ensure the URL starts with http:// or https://
+       if not api_url.startswith(('http://', 'https://')):
+           raise ValueError("API URL must start with 'http://' or 'https://'")
        self.api_url = api_url.rstrip('/')  

58-63: Consider adding error handling for API requests

The code should handle HTTP exceptions that might occur when making requests to custom API endpoints.

    def create_task(self, task_data: dict) -> dict:
        data = {
            'clientKey': self.api_key,
            'task': task_data
        }
-       response = httpx.post(
-           f'{self.api_url}/createTask',
-           json=data,
-           headers={'content-type': 'application/json'}
-       ).json()
+       try:
+           response = httpx.post(
+               f'{self.api_url}/createTask',
+               json=data,
+               headers={'content-type': 'application/json'},
+               timeout=30  # Add a reasonable timeout
+           )
+           response.raise_for_status()  # Raise exception for HTTP errors
+           return response.json()
+       except httpx.HTTPError as e:
+           raise RuntimeError(f"API request failed: {str(e)}")
-       return response

Similar changes should be applied to the get_task_result method as well.

Also applies to: 70-75

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3818195 and 7557ad3.

📒 Files selected for processing (1)
  • twikit/_captcha/capsolver.py (2 hunks)
🔇 Additional comments (6)
twikit/_captcha/capsolver.py (6)

35-36: Documentation looks good!

The new parameter is well documented with a clear description of its purpose and default value.


44-45: Parameter addition implemented correctly

The new api_url parameter has been added to the method signature with an appropriate default value, maintaining backward compatibility.


51-51: Good handling of trailing slashes

The code properly strips any trailing slashes from the URL to ensure consistent formatting when constructing endpoint URLs later.


59-59: URL construction is correct

Using f-string to combine the base API URL with the endpoint path is efficient.


71-71: URL construction is correct

Consistent approach to URL construction as in the create_task method.


45-45:

❓ Verification inconclusive

Update tests for the new parameter

Ensure that unit tests are updated to cover the new configurable API URL functionality.


🏁 Script executed:

#!/bin/bash

# Check if there are any test files that might need to be updated
fd -e py "test.*capsolver" -x cat {} \; 2>/dev/null || echo "No test files found for Capsolver"

# Check if there are any test files in the project
fd -e py "test" -x grep -l "Capsolver" {} \; 2>/dev/null || echo "No test files with Capsolver references found"

Length of output: 90


ACTION: Update unit tests for the new configurable API URL

Our automated search did not turn up any test files referencing Capsolver or its API URL configuration. Please verify manually whether:

  • There are any tests covering the behavior of the new configurable API URL in twikit/_captcha/capsolver.py (line 45)
  • The test suite needs new test cases or updates to ensure that changes to the API URL are properly validated

If tests exist under a different naming convention or in unexpected locations, please update or add tests accordingly.

@TimurKutsenko
Copy link

@izzzzzi Напиши в телеграм плиз: @unstable6

@dwqekc
Copy link
dwqekc commented Apr 20, 2025

@izzzzzi Приветствую, добавляя api_url - вы желаете дать пользователям возможность втыкать свои апи? Если так,то на каждом(почти) каптча сервисе роуты,аргументы разные.Если вы желаете для создания локальных апи - capsolver не предоставляет таких возможностей

@izzzzzi
Copy link
Author
izzzzzi commented Apr 24, 2025

@dwqekc я использую 3-4 сервиса для решения капчи и у всех апи идентичное

@dwqekc
Copy link
dwqekc commented Apr 24, 2025

@dwqekc я использую 3-4 сервиса для решения капчи и у всех апи идентичное

для поддержания объектирования либо делай абстракции либо реализации под все нужны тебе сервисы

< 8000 !-- '"` -->

@dwqekc
Copy link
dwqekc commented Apr 24, 2025

ну или блин просто форк свой поддерживай)),тут мержи не быстро принимают)))))

@dwqekc
Copy link
dwqekc commented Apr 24, 2025

но кстати, абстракции - тут мастхев можно в будущем di сделать короче более правильный чем щас обычно пихают))

Верхние уровни не будут знать о низших из за конечной реализации абстракции

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.

3 participants

0