Beispiel #1
0
    def DebugEndpoint(self, verb=None, endpoint=None, data=None):
        """ Request a url and return raw data. For testing purposes only.

        Args:
            url:
                The web location we want to retrieve.
            verb:
                Either POST or GET.
            data:
                A dict of (str, unicode) key/value pairs.

        Returns:
            data
        """
        url = "{0}{1}".format(self.base_url, endpoint)
        print(url)

        if verb == 'POST':
            if 'media_ids' in data:
                url = self._BuildUrl(
                    url,
                    extra_params={
                        'media_ids': data['media_ids']
                    }
                )
                print('POSTing url:', url)
            if 'media' in data:
                try:
                    print('POSTing url:', url)
                    raw_data = requests.post(
                        url,
                        files=data,
                        auth=self._Api__auth,
                        timeout=self._timeout
                    )
                except requests.RequestException as e:
                    raise TwitterError(str(e))
            else:
                try:
                    print('POSTing url:', url)
                    raw_data = requests.post(
                        url,
                        data=data,
                        auth=self._Api__auth,
                        timeout=self._timeout
                    )
                except requests.RequestException as e:
                    raise TwitterError(str(e))
        if verb == 'GET':
            url = self._BuildUrl(url, extra_params=data)
            print('GETting url:', url)
            try:
                raw_data = requests.get(
                    url,
                    auth=self._Api__auth,
                    timeout=self._timeout)

            except requests.RequestException as e:
                raise TwitterError(str(e))
        return raw_data._content
Beispiel #2
0
def parse_media_file(passed_media, media_category=None):
    """ Parses a media file and attempts to return a file-like object and
    information about the media file.

    Args:
        passed_media: media file which to parse.

    Returns:
        file-like object, the filename of the media file, the file size, and
        the type of media.
    """
    img_formats = [
        'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'
    ]
    video_formats = ['video/mp4', 'video/quicktime']

    # If passed_media is a string, check if it points to a URL, otherwise,
    # it should point to local file. Create a reference to a file obj for
    #  each case such that data_file ends up with a read() method.
    if not hasattr(passed_media, 'read'):
        if passed_media.startswith('http'):
            data_file = http_to_file(passed_media)
            filename = os.path.basename(urlparse(passed_media).path)
        else:
            data_file = open(os.path.realpath(passed_media), 'rb')
            filename = os.path.basename(passed_media)

    # Otherwise, if a file object was passed in the first place,
    # create the standard reference to media_file (i.e., rename it to fp).
    else:
        if passed_media.mode not in ['rb', 'rb+', 'w+b']:
            raise TwitterError('File mode must be "rb" or "rb+"')
        filename = os.path.basename(passed_media.name)
        data_file = passed_media

    data_file.seek(0, 2)
    file_size = data_file.tell()

    try:
        data_file.seek(0)
    except Exception as e:
        pass

    media_type = mimetypes.guess_type(os.path.basename(filename))[0]
    if media_type is not None:
        if media_type in img_formats and file_size > 5 * 1048576:
            if media_category is not 'tweet_gif':
                raise TwitterError(
                    {'message': 'Images must be less than 5MB.'})
        elif media_type in video_formats and file_size > 15 * 1048576:
            raise TwitterError({'message': 'Videos must be less than 15MB.'})
        elif media_type not in img_formats and media_type not in video_formats:
            raise TwitterError(
                {'message': 'Media type could not be determined.'})

    return data_file, filename, file_size, media_type
Beispiel #3
0
def enf_type(field, _type, val):
    """Enforce type checking on variable.

    Check to see if a given val for a field (i.e., the name
    of the field) is of the proper _type. If it is not,
    raise a TwitterError with a brief explanation.

    Args:
        field:
            Name of the field you are checking.
        _type:
            Type that the value should be returned as.
        val:
            Value to convert to _type.

    Returns:
        val converted to type _type.

    """
    try:
        return _type(val)
    except ValueError:
        raise TwitterError({
            'message':
            '"{0}" must be type {1}'.format(field, _type.__name__)
        })
Beispiel #4
0
 def add_to_list(self, screen_name, list_name):
     for _ in range(2):
         try:
             self.polling_api().CreateListsMember(
                 screen_name=screen_name,
                 slug=list_name.lower(),
                 owner_screen_name=self.environment.polling_account)
             return None
         except TwitterError as e:
             if e.message[0]['code'] == 34:
                 self.polling_api().CreateList(list_name)
                 logger.info(f'Created list {list_name}.')
                 # self.load_api()
                 sleep(5)
             if e.message[0]['code'] == 104:
                 logger.error(
                     f'Rate limit reached for adding user {screen_name} to list {list_name}.'
                 )
                 return e.message[0]['message']
             if e.message[0]['code'] == 106:
                 logger.error(
                     f'Not allowed to add user {screen_name} to list {list_name}.'
                 )
                 return e.message[0]['message']
             if e.message[0]['code'] == 108:
                 logger.warning(
                     f'Could not find user {screen_name} to add to list {list_name}.'
                 )
                 return e.message[0]['message']
             else:
                 raise
     raise TwitterError()
Beispiel #5
0
    def PostRetweet(self, id):
        '''This code come from issue #130 on python-twitter tracker'''

        if not self._oauth_consumer:
            raise TwitterError(
                "The twitter.Api instance must be authenticated.")
        try:
            if int(id) <= 0:
                raise TwitterError("'id' must be a positive number")
        except ValueError:
            raise TwitterError("'id' must be an integer")
        url = 'http://api.twitter.com/1/statuses/retweet/%s.json' % id
        json_data = self._FetchUrl(url, post_data={'dummy': None})
        data = json.loads(json_data)
        self._CheckForTwitterError(data)
        return Status.NewFromJsonDict(data)
def test_csv_record_creator_acc_not_found_fall_back_empty_screen_name():
  record_creator = CsvRecordCreator()
  record_creator.api.GetUserTimeline = Mock(side_effect=TwitterError('Account not found.'))
  
  with pytest.raises(InputArgumentsError) as e:
    record_creator.tweet_api_request(4567, '', 200)

  assert e.value.code == 32
  assert e.value.message == 'Account not found. Screen name is blank.'
  assert record_creator.api.GetUserTimeline.call_count == 1
 def test_follow_congresspeople(self, logging_mock):
     profiles = pd.DataFrame(
         [['DepEduardoCunha', 'DepEduardoCunha2'], ['DepRodrigomaia', None],
          [None, None]],
         columns=['twitter_profile', 'secondary_twitter_profile'])
     self.subject.profiles = profiles
     calls = [
         mock.call.CreateFriendship(screen_name='DepEduardoCunha'),
         mock.call.CreateFriendship(screen_name='DepEduardoCunha2'),
         mock.call.CreateFriendship(screen_name='DepRodrigomaia'),
     ]
     self.subject.follow_congresspeople()
     self.api.assert_has_calls(calls, any_order=True)
     self.assertEqual(3, self.api.CreateFriendship.call_count)
     self.api.CreateFriendship.side_effect = TwitterError('Not found')
     self.subject.follow_congresspeople()
     logging_mock.warning.assert_called()
     self.assertEqual(3, logging_mock.warning.call_count)
Beispiel #8
0
    def __init__(self,
                 consumer_key=None,
                 consumer_secret=None,
                 access_token_key=None,
                 access_token_secret=None,
                 input_encoding=None,
                 request_headers=None,
                 cache=DEFAULT_CACHE,
                 shortner=None,
                 base_url=None,
                 use_gzip_compression=False,
                 debugHTTP=False,
                 proxy={}):

        self.SetCache(cache)
        self._urllib = urllib2
        self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
        self._input_encoding = input_encoding
        self._use_gzip = use_gzip_compression
        self._debugHTTP = debugHTTP
        self._oauth_consumer = None
        self._proxy = proxy

        self._InitializeRequestHeaders(request_headers)
        self._InitializeUserAgent()
        self._InitializeDefaultParameters()

        if base_url is None:
            self.base_url = 'https://api.twitter.com/1'
        else:
            self.base_url = base_url

        if consumer_key is not None and (access_token_key is None
                                         or access_token_secret is None):
            print >> sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.'
            print >> sys.stderr, 'If your using this library from a command line utility, please'
            print >> sys.stderr, 'run the the included get_access_token.py tool to generate one.'

            raise TwitterError(
                'Twitter requires oAuth Access Token for all API access')

        self.SetCredentials(consumer_key, consumer_secret, access_token_key,
                            access_token_secret)
Beispiel #9
0
 def reply(self):
     statuses = self.twitter_client.GetSearch(
         term="to:%s" % self.name,
         since_id=self.last_replied_tweet_id,
         count=1)
     if len(statuses) > 0:
         status = statuses[0]
         trimmed_reply = "@%s %s" % (status.user.screen_name,
                                     self.random_quote())[:140]
         try:
             updated_status = self.twitter_client.PostUpdate(
                 trimmed_reply, in_reply_to_status_id=status.id)
         except TwitterError as e:
             if 'over 140 char' in str(e):
                 raise TwitterError(str(e), trimmed_reply)
             else:
                 raise e
         self.update_last_replied_tweet_id(status.id)
         return updated_status.text
     else:
         return False
def test_csv_record_creator_acc_not_found_fall_back():
  record_creator = CsvRecordCreator()
  record_creator.api.GetUserTimeline = Mock(side_effect=[TwitterError('Account not found.'), 123])
  result = record_creator.tweet_api_request(4567, 'tweet', 200)
  assert result == 123