Source code for twikit.errors

from __future__ import annotations


[docs] class TwitterException(Exception): """ Base class for Twitter API related exceptions. """ def __init__(self, *args: object, headers: dict | None = None) -> None: super().__init__(*args) if headers is None: self.headers = None else: self.headers = dict(headers)
[docs] class BadRequest(TwitterException): """ Exception raised for 400 Bad Request errors. """
[docs] class Unauthorized(TwitterException): """ Exception raised for 401 Unauthorized errors. """
[docs] class Forbidden(TwitterException): """ Exception raised for 403 Forbidden errors. """
[docs] class NotFound(TwitterException): """ Exception raised for 404 Not Found errors. """
[docs] class RequestTimeout(TwitterException): """ Exception raised for 408 Request Timeout errors. """
[docs] class TooManyRequests(TwitterException): """ Exception raised for 429 Too Many Requests errors. """ def __init__(self, *args, headers: dict | None = None) -> None: super().__init__(*args, headers=headers) if headers is not None and 'x-rate-limit-reset' in headers: self.rate_limit_reset = int(headers.get('x-rate-limit-reset')) else: self.rate_limit_reset = None
[docs] class ServerError(TwitterException): """ Exception raised for 5xx Server Error responses. """
[docs] class CouldNotTweet(TwitterException): """ Exception raised when a tweet could not be sent. """
[docs] class DuplicateTweet(CouldNotTweet): """ Exception raised when a tweet is a duplicate of another. """
[docs] class TweetNotAvailable(TwitterException): """ Exceptions raised when a tweet is not available. """
[docs] class InvalidMedia(TwitterException): """ Exception raised when there is a problem with the media ID sent with the tweet. """
[docs] class UserNotFound(TwitterException): """ Exception raised when a user does not exsit. """
[docs] class UserUnavailable(TwitterException): """ Exception raised when a user is unavailable. """
ERROR_CODE_TO_EXCEPTION: dict[int, TwitterException] = { 187: DuplicateTweet, 324: InvalidMedia }
[docs] def raise_exceptions_from_response(errors: list[dict]): for error in errors: code = error.get('code') if code not in ERROR_CODE_TO_EXCEPTION: code = error.get('extensions', {}).get('code') exception = ERROR_CODE_TO_EXCEPTION.get(code) if exception is not None: raise exception(error['message'])