Python tweepy.error.TweepError() Examples

The following are 30 code examples of tweepy.error.TweepError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tweepy.error , or try the search function .
Example #1
Source File: auth.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def get_authorization_url(self, signin_with_twitter=False):
        """Get the authorization URL to redirect the user"""
        try:
            # get the request token
            self.request_token = self._get_request_token()

            # build auth request and return as url
            if signin_with_twitter:
                url = self._get_oauth_url('authenticate')
            else:
                url = self._get_oauth_url('authorize')
            request = oauth.OAuthRequest.from_token_and_callback(
                token=self.request_token, http_url=url
            )

            return request.to_url()
        except Exception, e:
            raise TweepError(e) 
Example #2
Source File: parsers.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def parse(self, method, payload):
        try:
            if method.payload_type is None:
                return
            model = getattr(self.model_factory, method.payload_type)
        except AttributeError:
            raise TweepError('No model for this payload type: '
                             '%s' % method.payload_type)

        json = JSONParser.parse(self, method, payload)
        if isinstance(json, tuple):
            json, cursors = json
        else:
            cursors = None

        if method.payload_list:
            result = model.parse_list(method.api, json)
        else:
            result = model.parse(method.api, json)

        if cursors:
            return result, cursors
        else:
            return result 
Example #3
Source File: auth.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def get_xauth_access_token(self, username, password):
        """
        Get an access token from an username and password combination.
        In order to get this working you need to create an app at
        http://twitter.com/apps, after that send a mail to api@twitter.com
        and request activation of xAuth for it.
        """
        try:
            url = self._get_oauth_url('access_token')
            oauth = OAuth1(self.consumer_key,
                           client_secret=self.consumer_secret)
            r = requests.post(url=url,
                              auth=oauth,
                              headers={'x_auth_mode': 'client_auth',
                                       'x_auth_username': username,
                                       'x_auth_password': password})

            credentials = parse_qs(r.content)
            return credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0]
        except Exception as e:
            raise TweepError(e) 
Example #4
Source File: auth.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def get_access_token(self, verifier=None):
        """
        After user has authorized the request token, get access token
        with user supplied verifier.
        """
        try:
            url = self._get_oauth_url('access_token')
            self.oauth = OAuth1Session(self.consumer_key,
                                       client_secret=self.consumer_secret,
                                       resource_owner_key=self.request_token['oauth_token'],
                                       resource_owner_secret=self.request_token['oauth_token_secret'],
                                       verifier=verifier, callback_uri=self.callback)
            resp = self.oauth.fetch_access_token(url)
            self.access_token = resp['oauth_token']
            self.access_token_secret = resp['oauth_token_secret']
            return self.access_token, self.access_token_secret
        except Exception as e:
            raise TweepError(e) 
Example #5
Source File: parsers.py    From pheme-twitter-conversation-collection with Apache License 2.0 6 votes vote down vote up
def parse(self, method, payload):
        try:
            if method.payload_type is None: return
            model = getattr(self.model_factory, method.payload_type)
        except AttributeError:
            raise TweepError('No model for this payload type: %s' % method.payload_type)

        json = JSONParser.parse(self, method, payload)
        if isinstance(json, tuple):
            json, cursors = json
        else:
            cursors = None

        if method.payload_list:
            result = model.parse_list(method.api, json)
        else:
            result = model.parse(method.api, json)

        if cursors:
            return result, cursors
        else:
            return result 
Example #6
Source File: auth.py    From pheme-twitter-conversation-collection with Apache License 2.0 6 votes vote down vote up
def get_xauth_access_token(self, username, password):
        """
        Get an access token from an username and password combination.
        In order to get this working you need to create an app at
        http://twitter.com/apps, after that send a mail to api@twitter.com
        and request activation of xAuth for it.
        """
        try:
            url = self._get_oauth_url('access_token', secure=True) # must use HTTPS
            request = oauth.OAuthRequest.from_consumer_and_token(
                oauth_consumer=self._consumer,
                http_method='POST', http_url=url,
                parameters = {
                    'x_auth_mode': 'client_auth',
                    'x_auth_username': username,
                    'x_auth_password': password
                }
            )
            request.sign_request(self._sigmethod, self._consumer, None)

            resp = urlopen(Request(url, data=request.to_postdata()))
            self.access_token = oauth.OAuthToken.from_string(resp.read())
            return self.access_token
        except Exception, e:
            raise TweepError(e) 
Example #7
Source File: auth.py    From pheme-twitter-conversation-collection with Apache License 2.0 6 votes vote down vote up
def get_access_token(self, verifier=None):
        """
        After user has authorized the request token, get access token
        with user supplied verifier.
        """
        try:
            url = self._get_oauth_url('access_token')

            # build request
            request = oauth.OAuthRequest.from_consumer_and_token(
                self._consumer,
                token=self.request_token, http_url=url,
                verifier=str(verifier)
            )
            request.sign_request(self._sigmethod, self._consumer, self.request_token)

            # send request
            resp = urlopen(Request(url, headers=request.to_header()))
            self.access_token = oauth.OAuthToken.from_string(resp.read())
            return self.access_token
        except Exception, e:
            raise TweepError(e) 
Example #8
Source File: auth.py    From pheme-twitter-conversation-collection with Apache License 2.0 6 votes vote down vote up
def get_authorization_url(self, signin_with_twitter=False):
        """Get the authorization URL to redirect the user"""
        try:
            # get the request token
            self.request_token = self._get_request_token()

            # build auth request and return as url
            if signin_with_twitter:
                url = self._get_oauth_url('authenticate')
            else:
                url = self._get_oauth_url('authorize')
            request = oauth.OAuthRequest.from_token_and_callback(
                token=self.request_token, http_url=url
            )

            return request.to_url()
        except Exception, e:
            raise TweepError(e) 
Example #9
Source File: commands.py    From telegram-twitter-forwarder-bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
def cmd_verify(bot, update, args, chat):
    if not chat.twitter_request_token:
        bot.reply(update, "Use /auth command first")
        return
    if len(args) < 1:
        bot.reply(update, "No verifier code specified")
        return
    verifier_code = args[0]
    auth = OAuthHandler(bot.tw.auth.consumer_key, bot.tw.auth.consumer_secret)
    auth.request_token = json.loads(chat.twitter_request_token)
    try:
        auth.get_access_token(verifier_code)
    except TweepError:
        bot.reply(update, "Invalid verifier code. Use /auth again")
        return
    chat.twitter_token = auth.access_token
    chat.twitter_secret = auth.access_token_secret
    chat.save()
    bot.reply(update, "Access token setup complete")
    api = tweepy.API(auth)
    settings = api.get_settings()
    tz_name = settings.get("time_zone", {}).get("tzinfo_name")
    cmd_set_timezone(bot, update, [tz_name]) 
Example #10
Source File: api.py    From twitter_bot_utils with GNU General Public License v3.0 6 votes vote down vote up
def media_upload(self, filename, *args, **kwargs):
        """ :reference: https://dev.twitter.com/rest/reference/post/media/upload
            :reference https://dev.twitter.com/rest/reference/post/media/upload-chunked
            :allowed_param:
        """
        f = kwargs.pop('file', None)

        mime, _ = mimetypes.guess_type(filename)
        size = getfilesize(filename, f)

        if mime in IMAGE_MIMETYPES and size < self.max_size_standard:
            return self.image_upload(filename, file=f, *args, **kwargs)

        elif mime in CHUNKED_MIMETYPES:
            return self.upload_chunked(filename, file=f, *args, **kwargs)

        else:
            raise TweepError("Can't upload media with mime type %s" % mime) 
Example #11
Source File: parsers.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def parse(self, method, payload):
        try:
            if method.payload_type is None: return
            model = getattr(self.model_factory, method.payload_type)
        except AttributeError:
            raise TweepError('No model for this payload type: %s' % method.payload_type)

        json = JSONParser.parse(self, method, payload)
        if isinstance(json, tuple):
            json, cursors = json
        else:
            cursors = None

        if method.payload_list:
            result = model.parse_list(method.api, json)
        else:
            result = model.parse(method.api, json)

        if cursors:
            return result, cursors
        else:
            return result 
Example #12
Source File: auth.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def get_access_token(self, verifier=None):
        """
        After user has authorized the request token, get access token
        with user supplied verifier.
        """
        try:
            url = self._get_oauth_url('access_token')

            # build request
            request = oauth.OAuthRequest.from_consumer_and_token(
                self._consumer,
                token=self.request_token, http_url=url,
                verifier=str(verifier)
            )
            request.sign_request(self._sigmethod, self._consumer, self.request_token)

            # send request
            resp = urlopen(Request(url, headers=request.to_header()))
            self.access_token = oauth.OAuthToken.from_string(resp.read())
            return self.access_token
        except Exception, e:
            raise TweepError(e) 
Example #13
Source File: auth.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def get_xauth_access_token(self, username, password):
        """
        Get an access token from an username and password combination.
        In order to get this working you need to create an app at
        http://twitter.com/apps, after that send a mail to api@twitter.com
        and request activation of xAuth for it.
        """
        try:
            url = self._get_oauth_url('access_token', secure=True) # must use HTTPS
            request = oauth.OAuthRequest.from_consumer_and_token(
                oauth_consumer=self._consumer,
                http_method='POST', http_url=url,
                parameters = {
                    'x_auth_mode': 'client_auth',
                    'x_auth_username': username,
                    'x_auth_password': password
                }
            )
            request.sign_request(self._sigmethod, self._consumer, None)

            resp = urlopen(Request(url, data=request.to_postdata()))
            self.access_token = oauth.OAuthToken.from_string(resp.read())
            return self.access_token
        except Exception, e:
            raise TweepError(e) 
Example #14
Source File: api.py    From pheme-twitter-conversation-collection with Apache License 2.0 5 votes vote down vote up
def verify_credentials(self, **kargs):
        try:
            return bind_api(
                path = '/account/verify_credentials.json',
                payload_type = 'user',
                require_auth = True,
                allowed_param = ['include_entities', 'skip_status'],
            )(self, **kargs)
        except TweepError, e:
            if e.response and e.response.status == 401:
                return False
            raise 
Example #15
Source File: api.py    From pheme-twitter-conversation-collection with Apache License 2.0 5 votes vote down vote up
def _pack_image(filename, max_size, form_field="image"):
        """Pack image from file into multipart-formdata post body"""
        # image must be less than 700kb in size
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise TweepError('File is too big, must be less than 700kb.')
        except os.error:
            raise TweepError('Unable to access file')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        # build the mulitpart-formdata body
        fp = open(filename, 'rb')
        BOUNDARY = 'Tw3ePy'
        body = []
        body.append('--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (form_field, filename))
        body.append('Content-Type: %s' % file_type)
        body.append('')
        body.append(fp.read())
        body.append('--' + BOUNDARY + '--')
        body.append('')
        fp.close()
        body = '\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': str(len(body))
        }

        return headers, body 
Example #16
Source File: auth.py    From locality-sensitive-hashing with MIT License 5 votes vote down vote up
def get_username(self):
        if self.username is None:
            api = API(self)
            user = api.verify_credentials()
            if user:
                self.username = user.screen_name
            else:
                raise TweepError("Unable to get username, invalid oauth token!")
        return self.username 
Example #17
Source File: service.py    From polybot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self):
        print(
            "You'll need a consumer token and secret from your twitter app configuration here."
        )
        api_key = input("Consumer token: ")
        api_secret = input("Consumer secret: ")
        auth = tweepy.OAuthHandler(api_key, api_secret)
        try:
            redirect_url = auth.get_authorization_url()
        except tweepy.TweepError:
            print("Unable to fetch a request token! Check your consumer credentials")
            return False
        print(
            "OK, now visit this URL and get the verifier from there: %s" % redirect_url
        )
        verifier = input("Verifier: ")
        try:
            auth.get_access_token(verifier)
        except tweepy.TweepError:
            print(
                "Unable to fetch the access token! Verifier may not have been correct."
            )
            return False

        print("Checking everything works...")
        self.tweepy = tweepy.API(auth)
        print("Successfully authenticated as %s" % self.tweepy.me().screen_name)

        self.config.add_section("twitter")
        self.config.set("twitter", "api_key", api_key)
        self.config.set("twitter", "api_secret", api_secret)
        self.config.set("twitter", "access_key", auth.access_token)
        self.config.set("twitter", "access_secret", auth.access_token_secret)

        return True 
Example #18
Source File: service.py    From polybot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_post(
        self,
        status,
        imagefile=None,
        mime_type=None,
        lat=None,
        lon=None,
        in_reply_to_id=None,
    ):
        try:
            if imagefile:
                if mime_type:
                    ext = mimetypes.guess_extension(mime_type)
                    f = BytesIO(imagefile)
                    imagefile = "dummy" + ext
                else:
                    f = None
                return self.tweepy.update_with_media(
                    imagefile,
                    status=status,
                    lat=lat,
                    long=lon,
                    file=f,
                    in_reply_to_status_id=in_reply_to_id,
                )
            else:
                return self.tweepy.update_status(
                    status, in_reply_to_status_id=in_reply_to_id, lat=lat, long=lon
                )
        except TweepError as e:
            raise PostError(e) 
Example #19
Source File: tweepy_error_handling.py    From smappPy with GNU General Public License v2.0 5 votes vote down vote up
def call_with_error_handling(function, *args, **kwargs):
    """
    Calls given functions with given arguments, wrapping function call in
    try-except block catching most twitter errors and responses.
    Returns tuple: (function return value, return code). Return code is 0
    when function executes successfully. Custom Error Codes:
        1   - Unknown/Unparseable Twitter error
        2   - HTTPLib incomplete read error
        3   - SSL Read timeout error
        4   - ValeError (eg: "No JSON object could be decoded")
    """
    try:
       ret = function(*args, **kwargs)
    except TweepError as e:
        error_dict = parse_tweepy_error(e)
        logger.warning("Error {0}: {1}".format(error_dict["code"], error_dict["message"]))
        return (None, error_dict["code"])
    except IncompleteRead as i:
        logger.warn("HTTPLib incomplete read error: {0}".format(i))
        return (None, 2)
    except SSLError as s:
        logger.warn("SSL read timeout error: {0}".format(s))
        return (None, 3)
    except ValueError as v:
        logger.warn("Value error (most likely JSON problem): {0}".format(v))
        return (None, 4)

    return (ret, 0) 
Example #20
Source File: twitter.py    From twitter-most-followed with MIT License 5 votes vote down vote up
def get_api():
	auth = RateLimitHandler(CONSUMER_KEY, CONSUMER_SECRET)
	for key, secret in ACCESS_TOKENS:
		try:
			auth.add_access_token(key, secret)
		except TweepError, e:
			print key, e 
Example #21
Source File: auth.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _get_request_token(self, access_type=None):
        try:
            url = self._get_oauth_url('request_token')
            if access_type:
                url += '?x_auth_access_type=%s' % access_type
            return self.oauth.fetch_request_token(url)
        except Exception as e:
            raise TweepError(e) 
Example #22
Source File: auth.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def get_authorization_url(self,
                              signin_with_twitter=False,
                              access_type=None):
        """Get the authorization URL to redirect the user"""
        try:
            if signin_with_twitter:
                url = self._get_oauth_url('authenticate')
                if access_type:
                    logging.warning(WARNING_MESSAGE)
            else:
                url = self._get_oauth_url('authorize')
            self.request_token = self._get_request_token(access_type=access_type)
            return self.oauth.authorization_url(url)
        except Exception as e:
            raise TweepError(e) 
Example #23
Source File: auth.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def __init__(self, consumer_key, consumer_secret):
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self._bearer_token = ''

        resp = requests.post(self._get_oauth_url('token'),
                             auth=(self.consumer_key,
                                   self.consumer_secret),
                             data={'grant_type': 'client_credentials'})
        data = resp.json()
        if data.get('token_type') != 'bearer':
            raise TweepError('Expected token_type to equal "bearer", '
                             'but got %s instead' % data.get('token_type'))

        self._bearer_token = data['access_token'] 
Example #24
Source File: cursor.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def __init__(self, method, *args, **kargs):
        if hasattr(method, 'pagination_mode'):
            if method.pagination_mode == 'cursor':
                self.iterator = CursorIterator(method, args, kargs)
            elif method.pagination_mode == 'id':
                self.iterator = IdIterator(method, args, kargs)
            elif method.pagination_mode == 'page':
                self.iterator = PageIterator(method, args, kargs)
            else:
                raise TweepError('Invalid pagination mode.')
        else:
            raise TweepError('This method does not perform pagination') 
Example #25
Source File: cursor.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def prev(self):
        if self.prev_cursor == 0:
            raise TweepError('Can not page back more, at first page')
        data, self.next_cursor, self.prev_cursor = self.method(cursor=self.prev_cursor,
                                                               *self.args,
                                                               **self.kargs)
        self.num_tweets -= 1
        return data 
Example #26
Source File: cursor.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def prev(self):
        if self.current_page == 1:
            raise TweepError('Can not page back more, at first page')
        self.current_page -= 1
        return self.method(page=self.current_page, *self.args, **self.kargs) 
Example #27
Source File: cursor.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def prev(self):
        if self.current_page is None:
            raise TweepError('Can not go back more, at first page')
        if self.page_index == 0:
            # At the beginning of the current page, move to next...
            self.current_page = self.page_iterator.prev()
            self.page_index = len(self.current_page)
            if self.page_index == 0:
                raise TweepError('No more items')
        self.page_index -= 1
        self.num_tweets -= 1
        return self.current_page[self.page_index] 
Example #28
Source File: parsers.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def parse(self, method, payload):
        try:
            json = self.json_lib.loads(payload)
        except Exception as e:
            raise TweepError('Failed to parse JSON payload: %s' % e)

        needs_cursors = 'cursor' in method.session.params
        if needs_cursors and isinstance(json, dict) \
                and 'previous_cursor' in json \
                and 'next_cursor' in json:
            cursors = json['previous_cursor'], json['next_cursor']
            return json, cursors
        else:
            return json 
Example #29
Source File: auth.py    From locality-sensitive-hashing with MIT License 5 votes vote down vote up
def _get_request_token(self):
        try:
            url = self._get_oauth_url('request_token')
            request = oauth.OAuthRequest.from_consumer_and_token(
                self._consumer, http_url=url, callback=self.callback
            )
            request.sign_request(self._sigmethod, self._consumer, None)
            resp = urlopen(Request(url, headers=request.to_header()))
            return oauth.OAuthToken.from_string(resp.read())
        except Exception, e:
            raise TweepError(e) 
Example #30
Source File: cursor.py    From pheme-twitter-conversation-collection with Apache License 2.0 5 votes vote down vote up
def prev(self):
        if (self.current_page == 1):
            raise TweepError('Can not page back more, at first page')
        self.current_page -= 1
        return self.method(page=self.current_page, *self.args, **self.kargs)