Handle exceptions and errors when working with the Twitter API
Twikit provides a comprehensive set of exception classes for handling errors that occur when interacting with Twitter’s API. Understanding these errors helps you build robust applications.
Raised when you don’t have permission to access a resource:
from twikit.errors import Forbiddentry: # Try to access a private account's tweets tweets = await client.get_user_tweets(private_user_id, 'Tweets')except Forbidden as e: print(f'Access forbidden: {e}') print('You may not have permission to view this content')
from twikit.errors import NotFoundtry: tweet = await client.get_tweet_by_id('invalid_id')except NotFound as e: print(f'Resource not found: {e}') print('The tweet may have been deleted')
from twikit.errors import RequestTimeouttry: tweets = await client.search_tweet('query', 'Latest')except RequestTimeout as e: print(f'Request timed out: {e}') print('The server took too long to respond')
from twikit.errors import TooManyRequestsimport timeimport asynciotry: for i in range(100): # Too many requests! await client.search_tweet(f'query_{i}', 'Latest')except TooManyRequests as e: print(f'Rate limit exceeded: {e}') # Get the reset time if e.rate_limit_reset: wait_seconds = e.rate_limit_reset - int(time.time()) print(f'Rate limit resets in {wait_seconds} seconds') print(f'Reset at timestamp: {e.rate_limit_reset}') # Wait for the rate limit to reset await asyncio.sleep(wait_seconds) else: # Wait 15 minutes if no reset time provided await asyncio.sleep(900)
Common causes:
Making too many requests in a 15-minute window
Not implementing rate limit handling
Running multiple scripts simultaneously
The TooManyRequests exception has a special rate_limit_reset attribute containing a Unix timestamp of when the limit resets. Use this to calculate the exact wait time.
from twikit.errors import AccountSuspendedtry: await client.login( auth_info_1='username', password='password' )except AccountSuspended as e: print(f'Account suspended: {e}') print('Your account has been suspended by Twitter') print('Visit https://help.twitter.com/en/managing-your-account/suspended-twitter-accounts')
What to do:
Review Twitter’s rules and policies
Appeal the suspension through Twitter’s help center
Raised when an account is locked (often due to CAPTCHA challenges):
from twikit.errors import AccountLockedfrom twikit._captcha import Capsolvertry: await client.create_tweet('Hello, world!')except AccountLocked as e: print(f'Account locked: {e}') print('Visit https://twitter.com/account/access to unlock') # Or use automatic unlock with Capsolver if client.captcha_solver: print('Attempting automatic unlock...') await client.unlock()
What to do:
Visit the account access page to verify your identity
from twikit.errors import UserNotFoundtry: user = await client.get_user_by_screen_name('nonexistent_user_12345')except UserNotFound as e: print(f'User not found: {e}') print('The username may be incorrect or the account was deleted')
from twikit.errors import UserUnavailabletry: user = await client.get_user_by_id('12345')except UserUnavailable as e: print(f'User unavailable: {e}') print('The user account is temporarily unavailable')
from twikit.errors import TweetNotAvailabletry: tweet = await client.get_tweet_by_id('12345')except TweetNotAvailable as e: print(f'Tweet not available: {e}')
Raised when there’s a problem with uploaded media:
from twikit.errors import InvalidMediatry: media_id = await client.upload_media('image.jpg', wait_for_completion=True) await client.create_tweet('Check this out!', media_ids=[media_id])except InvalidMedia as e: print(f'Invalid media: {e}') print('The media file may be corrupted or in an unsupported format')
from twikit.errors import NotFound, Forbidden, TooManyRequeststry: user = await client.get_user_by_screen_name('someuser') tweets = await user.get_tweets('Tweets')except NotFound: print('User not found')except Forbidden: print('Cannot access this user (private or blocked)')except TooManyRequests as e: print(f'Rate limited. Reset at: {e.rate_limit_reset}')