How to use the twython.exceptions.TwythonAuthError function in twython

To help you get started, we’ve selected a few twython examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rufoa / deleted-tweets / watch.py View on Github external
else:
			keep = False

		if keep:
			access_token = access_token_old
			access_token_secret = access_token_secret_old
		else:
			print "\nGo to this URL and log in:\n" + auth['auth_url'] + "\n"
			rest = Twython(consumer_key, consumer_secret, auth['oauth_token'], auth['oauth_token_secret'])
			pin = raw_input('Enter PIN code: ')

			try:
				tokens = rest.get_authorized_tokens(pin)
				access_token = tokens['oauth_token']
				access_token_secret = tokens['oauth_token_secret']
			except TwythonAuthError:
				print "Invalid or expired PIN"
				exit(1)

		rest = Twython(consumer_key, consumer_secret, access_token, access_token_secret)

		follow = raw_input('List of twitter accounts to follow: ')
		follow_list = []
		for account in re.split('[\s,]+', follow):
			if account.isdigit():
				user = rest.show_user(user_id=account)
			else:
				if account[0] == '@':
					account = account[1:]
				user = rest.show_user(screen_name=account)
			if 'id_str' in user:
				print "@" + user['screen_name'] + " (user ID " + user['id_str'] + ") found"
github ryanmcgrath / twython / twython / api.py View on Github external
input box of the OAuth login screen with the
                            given value

        :rtype: dict
        """
        if self.oauth_version != 1:
            raise TwythonError('This method can only be called when your \
                               OAuth version is 1.0.')

        request_args = {}
        if callback_url:
            request_args['oauth_callback'] = callback_url
        response = self.client.get(self.request_token_url, params=request_args)

        if response.status_code == 401:
            raise TwythonAuthError(response.content,
                                   error_code=response.status_code)
        elif response.status_code != 200:
            raise TwythonError(response.content,
                               error_code=response.status_code)

        request_tokens = dict(parse_qsl(response.content.decode('utf-8')))
        if not request_tokens:
            raise TwythonError('Unable to decode request tokens.')

        oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed') \
            == 'true'

        auth_url_params = {
            'oauth_token': request_tokens['oauth_token'],
        }
github Humpheh / twied / src / twied / labelprop / inference.py View on Github external
# return none if the user is private or field empty
        if dbusr is not None:
            return dbusr if 'private' not in dbusr else None

        mentions = defaultdict(int)
        geotags = []
        user = None

        max_id = None
        for i in range(self.timelines):
            try:
                # get the next part of the twitter timeline
                self.log("Downloading new Twitter profile: %s %i/%i" % (user_id, i+1, self.timelines))
                usr_tweets = self.twitter.get_user_timeline(user_id=user_id, count=200, include_rts=False, max_id=max_id)
            except TwythonAuthError:
                # if auth error, user is private, store as private entry
                self.db.insert_one({
                    'user': {'id': int(user_id)},
                    'private': True
                })
                return None
            except TwythonError as e:
                # error in getting the information (API limited?)
                logging.error(str(e))
                return None

            # search the returned tweets for geotags and mentions
            for twt in usr_tweets:
                user = twt['user']
                for m in twt['entities']['user_mentions']:
                    mentions[m['id_str']] += 1
github manuelcortez / TWBlue / src / sessionmanager / sessionManager.py View on Github external
def do_ok(self):
  log.debug("Starting sessions...")
  for i in self.sessions:
   if (i in sessions.sessions) == True: continue
   s = session.Session(i)
   s.get_configuration()
   if i not in config.app["sessions"]["ignored_sessions"]:
    try:
     s.login()
    except TwythonAuthError:
     self.show_auth_error(s.settings["twitter"]["user_name"])
     continue
   sessions.sessions[i] = s
   self.new_sessions[i] = s
#  self.view.destroy()
github ryanmcgrath / twython / twython / api.py View on Github external
raise TwythonError('This method can only be called when your \
                               OAuth version is 2.0.')

        data = {'grant_type': 'client_credentials'}
        basic_auth = HTTPBasicAuth(self.app_key, self.app_secret)
        try:
            response = self.client.post(self.request_token_url,
                                        data=data, auth=basic_auth)
            content = response.content.decode('utf-8')
            try:
                content = content.json()
            except AttributeError:
                content = json.loads(content)
                access_token = content['access_token']
        except (KeyError, ValueError, requests.exceptions.RequestException):
            raise TwythonAuthError('Unable to obtain OAuth 2 access token.')
        else:
            return access_token
github ryanmcgrath / twython / twython / api.py View on Github external
# greater than 304 (not modified) is an error
        if response.status_code > 304:
            error_message = self._get_error_message(response)
            self._last_call['api_error'] = error_message

            ExceptionType = TwythonError
            if response.status_code == 429:
                # Twitter API 1.1, always return 429 when
                # rate limit is exceeded
                ExceptionType = TwythonRateLimitError
            elif response.status_code == 401 or 'Bad Authentication data' \
                    in error_message:
                # Twitter API 1.1, returns a 401 Unauthorized or
                # a 400 "Bad Authentication data" for invalid/expired
                # app keys/user tokens
                ExceptionType = TwythonAuthError

            raise ExceptionType(
                error_message,
                error_code=response.status_code,
                retry_after=response.headers.get('X-Rate-Limit-Reset'))
        content = ''
        try:
            if response.status_code == 204:
                content = response.content
            else:
                content = response.json()
        except ValueError:
            if response.content != '':
                raise TwythonError('Response was not valid JSON. \
                                   Unable to decode.')