desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Test all of the twitter.User properties'
| def testProperties(self):
| user = twitter.User()
user.id = 673483
self.assertEqual(673483, user.id)
user.name = 'DeWitt'
self.assertEqual('DeWitt', user.name)
user.screen_name = 'dewitt'
self.assertEqual('dewitt', user.screen_name)
user.description = 'Indeterminate things'
self.assertEqual('Indeterminate ... |
'Test the twitter.User AsJsonString method'
| def testAsJsonString(self):
| self.assertEqual(UserTest.SAMPLE_JSON, self._GetSampleUser().AsJsonString())
|
'Test the twitter.User AsDict method'
| def testAsDict(self):
| user = self._GetSampleUser()
data = user.AsDict()
self.assertEqual(673483, data['id'])
self.assertEqual('DeWitt', data['name'])
self.assertEqual('dewitt', data['screen_name'])
self.assertEqual('Indeterminate things', data['description'])
self.assertEqual('San Francisco, CA', data['l... |
'Test the twitter.User __eq__ method'
| def testEq(self):
| user = twitter.User()
user.id = 673483
user.name = 'DeWitt'
user.screen_name = 'dewitt'
user.description = 'Indeterminate things'
user.location = 'San Francisco, CA'
user.profile_image_url = 'https://twitter.com/system/user/profile_image/673483/normal/me.jpg'
user.url = 'http://... |
'Test the twitter.User __hash__ method'
| def testHash(self):
| user = self._GetSampleUser()
self.assertEqual(hash(user), hash(user.id))
|
'Test the twitter.User NewFromJsonDict method'
| def testNewFromJsonDict(self):
| data = json.loads(UserTest.SAMPLE_JSON)
user = twitter.User.NewFromJsonDict(data)
self.assertEqual(self._GetSampleUser(), user)
|
'Test the twitter.Status constructor'
| def testInit(self):
| twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007', id=4391023, text=u'A l\xe9gp\xe1rn\xe1s haj\xf3m tele van angoln\xe1kkal.', user=self._GetSampleUser())
|
'Test all of the twitter.Status properties'
| def testProperties(self):
| status = twitter.Status()
status.id = 1
self.assertEqual(1, status.id)
created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, (-1), (-1), (-1)))
status.created_at = 'Fri Jan 26 23:17:14 +0000 2007'
self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.created_at... |
'Test the twitter.Status AsJsonString method'
| @unittest.skipIf((sys.version_info.major >= 3), 'skipped until fix found for v3 python')
def testAsJsonString(self):
| self.assertEqual(StatusTest.SAMPLE_JSON, self._GetSampleStatus().AsJsonString())
|
'Test the twitter.Status AsDict method'
| def testAsDict(self):
| status = self._GetSampleStatus()
data = status.AsDict()
self.assertEqual(4391023, data['id'])
self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', data['created_at'])
self.assertEqual(u'A l\xe9gp\xe1rn\xe1s haj\xf3m tele van angoln\xe1kkal.', data['text'])
self.assert... |
'Test the twitter.Status __eq__ method'
| def testEq(self):
| status = twitter.Status()
status.created_at = 'Fri Jan 26 23:17:14 +0000 2007'
status.id = 4391023
status.text = u'A l\xe9gp\xe1rn\xe1s haj\xf3m tele van angoln\xe1kkal.'
status.user = self._GetSampleUser()
self.assertEqual(status, self._GetSampleStatus())
|
'Test the twitter.Status __hash__ method'
| def testHash(self):
| status = self._GetSampleStatus()
self.assertEqual(hash(status), hash(status.id))
|
'Test the twitter.Status NewFromJsonDict method'
| def testNewFromJsonDict(self):
| data = json.loads(StatusTest.SAMPLE_JSON)
status = twitter.Status.NewFromJsonDict(data)
self.assertEqual(self._GetSampleStatus(), status)
|
'This is tedious, but the point is to add a responses endpoint for
each call that GetFriends() is going to make against the API and
have it return the appropriate json data.'
| @responses.activate
def testGetFriends(self):
| cursor = (-1)
for i in range(0, 5):
with open(u'testdata/get_friends_{0}.json'.format(i)) as f:
resp_data = f.read()
endpoint = u'https://api.twitter.com/1.1/friends/list.json?count=200&tweet_mode=compat&include_user_entities=True&screen_name=codebear&skip_status=False&cursor={0}'.fo... |
'Test twitter.Category object'
| def test_category(self):
| cat = twitter.Category.NewFromJsonDict(self.CATEGORY_SAMPLE_JSON)
try:
cat.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(cat.AsJsonString())
self.assertTrue(cat.AsDict())
|
'Test twitter.DirectMessage object'
| def test_direct_message(self):
| dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)
dm_short = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SHORT_SAMPLE_JSON)
try:
dm.__repr__()
dm_short.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(dm.AsJsonString())
... |
'Test that each Direct Message object contains a fully hydrated
twitter.models.User object for both ``dm.sender`` & ``dm.recipient``.'
| def test_direct_message_sender_is_user_model(self):
| dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)
self.assertTrue(isinstance(dm.sender, twitter.models.User))
self.assertEqual(dm.sender.id, 372018022)
self.assertEqual(dm.id, 678629245946433539)
|
'Test that each Direct Message object contains a fully hydrated
twitter.models.User object for both ``dm.sender`` & ``dm.recipient``.'
| def test_direct_message_recipient_is_user_model(self):
| dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)
self.assertTrue(isinstance(dm.recipient, twitter.models.User))
self.assertEqual(dm.recipient.id, 4012966701)
self.assertEqual(dm.id, 678629245946433539)
|
'Test twitter.Hashtag object'
| def test_hashtag(self):
| ht = twitter.Hashtag.NewFromJsonDict(self.HASHTAG_SAMPLE_JSON)
try:
ht.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(ht.AsJsonString())
self.assertTrue(ht.AsDict())
|
'Test twitter.List object'
| def test_list(self):
| lt = twitter.List.NewFromJsonDict(self.LIST_SAMPLE_JSON)
try:
lt.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(lt.AsJsonString())
self.assertTrue(lt.AsDict())
|
'Test twitter.Media object'
| def test_media(self):
| media = twitter.Media.NewFromJsonDict(self.MEDIA_SAMPLE_JSON)
try:
media.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(media.AsJsonString())
self.assertTrue(media.AsDict())
|
'Test twitter.Status object'
| def test_status(self):
| status = twitter.Status.NewFromJsonDict(self.STATUS_SAMPLE_JSON)
try:
status.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(status.AsJsonString())
self.assertTrue(status.AsDict())
self.assertTrue(status.media[0].AsJsonString())
self.assertTrue(status.media[0].... |
'Test that quoted tweets are properly handled.'
| def test_status_quoted_tweet(self):
| status = twitter.Status.NewFromJsonDict(self.STATUS_QUOTED_TWEET_SAMPLE_JSON)
assert (status.quoted_status_id == 849412806835351552)
assert (status.quoted_status.id == 849412806835351552)
assert (status.quoted_status.text == 'hard to believe @mastodonmusic created its own open so... |
'Test that quoted tweet properly handles attached media.'
| def test_status_quoted_tweet_with_media(self):
| status = twitter.Status.NewFromJsonDict(self.STATUS_QUOTED_TWEET_WITH_MEDIA)
assert (status.quoted_status.media is not None)
|
'Test twitter.Status object which does not contain a \'user\' entity.'
| def test_status_no_user(self):
| status = twitter.Status.NewFromJsonDict(self.STATUS_NO_USER_SAMPLE_JSON)
try:
status.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(status.AsJsonString())
self.assertTrue(status.AsDict())
|
'Test twitter.Trend object'
| def test_trend(self):
| trend = twitter.Trend.NewFromJsonDict(self.TREND_SAMPLE_JSON)
try:
trend.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(trend.AsJsonString())
self.assertTrue(trend.AsDict())
self.assertEqual(trend.tweet_volume, 104403)
self.assertEqual(trend.volume, trend.twee... |
'Test the twitter.User NewFromJsonDict method'
| def test_user(self):
| user = twitter.User.NewFromJsonDict(self.USER_SAMPLE_JSON)
self.assertEqual(user.id, 718443)
try:
user.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(user.AsJsonString())
self.assertTrue(user.AsDict())
self.assertTrue(isinstance(user.status, twitter.Status))
... |
'Test twitter.UserStatus object'
| def test_user_status(self):
| user_status = twitter.UserStatus.NewFromJsonDict(self.USER_STATUS_SAMPLE_JSON)
try:
user_status.__repr__()
except Exception as e:
self.fail(e)
self.assertTrue(user_status.AsJsonString())
self.assertTrue(user_status.AsDict())
|
'Test the twitter.Media constructor'
| def testInit(self):
| media = twitter.Media(id=244204973989187584, display_url='pic.twitter.com/7a2z7S8tKL', expanded_url='http://twitter.com/NASAJPL/status/672830989895254016/photo/1', url='https://t.co/7a2z7S8tKL', media_url_https='https://pbs.twimg.com/media/CVZgOC3UEAELUcL.jpg', media_url='http://pbs.twimg.com/media/CVZgOC3UEAELUcL.... |
'Test all of the twitter.Media properties'
| def testProperties(self):
| media = twitter.Media()
media.id = 244204973989187584
media.display_url = 'pic.twitter.com/7a2z7S8tKL'
media.expanded_url = 'http://twitter.com/NASAJPL/status/672830989895254016/photo/1'
media.url = 'https://t.co/7a2z7S8tKL'
media.media_url_https = 'https://pbs.twimg.com/media/CVZgOC3UEAELUcL.jp... |
'Test the twitter.User AsJsonString method'
| def testAsJsonString(self):
| self.assertEqual(MediaTest.SAMPLE_JSON, self._GetSampleMedia().AsJsonString())
|
'Test the twitter.Media AsDict method'
| def testAsDict(self):
| media = self._GetSampleMedia()
data = media.AsDict()
self.assertEqual('pic.twitter.com/lX5LVZO', data['display_url'])
self.assertEqual('http://twitter.com/fakekurrik/status/244204973972410368/photo/1', data['expanded_url'])
self.assertEqual('http://t.co/lX5LVZO', data['url'])
self.assertEqual('h... |
'Test the twitter.Media __eq__ method'
| def testEq(self):
| media = twitter.Media()
media.id = 244204973989187584
media.display_url = 'pic.twitter.com/lX5LVZO'
media.expanded_url = 'http://twitter.com/fakekurrik/status/244204973972410368/photo/1'
media.url = 'http://t.co/lX5LVZO'
media.media_url_https = 'https://pbs.twimg.com/media/A2OXIUcCUAAXj9k.png'
... |
'Test the twitter.Media __hash__ method'
| def testHash(self):
| media = self._GetSampleMedia()
self.assertEqual(hash(media), hash(media.id))
|
'Test the twitter.Media NewFromJsonDict method'
| def testNewFromJsonDict(self):
| data = json.loads(MediaTest.RAW_JSON)
media = twitter.Media.NewFromJsonDict(data)
self.assertEqual(self._GetSampleMedia(), media)
|
'Test the twitter.Trend constructor'
| def testInit(self):
| twitter.Trend(name='Kesuke Miyagi', query='Kesuke Miyagi', timestamp='Fri Jan 26 23:17:14 +0000 2007')
|
'Test all of the twitter.Trend properties'
| def testProperties(self):
| trend = twitter.Trend()
trend.name = 'Kesuke Miyagi'
self.assertEqual('Kesuke Miyagi', trend.name)
trend.query = 'Kesuke Miyagi'
self.assertEqual('Kesuke Miyagi', trend.query)
trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007'
self.assertEqual('Fri Jan 26 ... |
'Test the twitter.Trend NewFromJsonDict method'
| def testNewFromJsonDict(self):
| data = json.loads(TrendTest.SAMPLE_JSON)
trend = twitter.Trend.NewFromJsonDict(data, timestamp='Fri Jan 26 23:17:14 +0000 2007')
self.assertEqual(self._GetSampleTrend(), trend)
|
'Test the twitter.Trend __eq__ method'
| def testEq(self):
| trend = twitter.Trend()
trend.name = 'Kesuke Miyagi'
trend.query = 'Kesuke Miyagi'
trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007'
self.assertEqual(trend, self._GetSampleTrend())
|
'Test the twitter.Trent __hash__ method'
| def testHash(self):
| trend = self._GetSampleTrend()
with self.assertRaises(TypeError) as context:
hash(trend)
self.assertIn('unhashable type: {} (no id attribute)'.format(type(trend)), str(context.exception))
|
'Test the twitter._FileCache constructor'
| def testInit(self):
| cache = twitter._FileCache()
self.assert_((cache is not None), 'cache is None')
|
'Test the twitter._FileCache.Set method'
| def testSet(self):
| cache = twitter._FileCache()
cache.Set('foo', 'Hello World!')
cache.Remove('foo')
|
'Test the twitter._FileCache.Remove method'
| def testRemove(self):
| cache = twitter._FileCache()
cache.Set('foo', 'Hello World!')
cache.Remove('foo')
data = cache.Get('foo')
self.assertEqual(data, None, 'data is not None')
|
'Test the twitter._FileCache.Get method'
| def testGet(self):
| cache = twitter._FileCache()
cache.Set('foo', 'Hello World!')
data = cache.Get('foo')
self.assertEqual('Hello World!', data)
cache.Remove('foo')
|
'Test the twitter._FileCache.GetCachedTime method'
| def testGetCachedTime(self):
| now = time.time()
cache = twitter._FileCache()
cache.Set('foo', 'Hello World!')
cached_time = cache.GetCachedTime('foo')
delta = (cached_time - now)
self.assert_((delta <= 1), 'Cached time differs from clock time by more than 1 second.')
cache.Remove('foo')
|
'Test that twitter responses containing an error message are wrapped.'
| def testTwitterError(self):
| self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json', curry(self._OpenTestData, 'public_timeline_error.json'))
try:
self._api.GetUserTimeline()
except twitter.TwitterError as error:
self.assertEqual('test error', error.message)
else:
self.fail('TwitterErr... |
'Test the twitter.Api GetUserTimeline method'
| def testGetUserTimeline(self):
| time.sleep(8)
print 'Testing GetUserTimeline'
self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=kesuke', curry(self._OpenTestData, 'user_timeline-kesuke.json'))
statuses = self._api.GetUserTimeline(screen_name='kesuke', count=1)
self.assertEqual(8951210... |
'Test the twitter.Api GetStatus method'
| def testGetStatus(self):
| time.sleep(8)
print 'Testing GetStatus'
self._AddHandler('https://api.twitter.com/1.1/statuses/show.json?include_my_retweet=1&id=89512102', curry(self._OpenTestData, 'show-89512102.json'))
status = self._api.GetStatus(89512102)
self.assertEqual(89512102, status.id)
self.assertEqual(718443, st... |
'Test the twitter.Api DestroyStatus method'
| def testDestroyStatus(self):
| time.sleep(8)
print 'Testing DestroyStatus'
self._AddHandler('https://api.twitter.com/1.1/statuses/destroy/103208352.json', curry(self._OpenTestData, 'status-destroy.json'))
status = self._api.DestroyStatus(103208352)
self.assertEqual(103208352, status.id)
|
'Test the twitter.Api PostUpdate method'
| def testPostUpdate(self):
| time.sleep(8)
print 'Testing PostUpdate'
self._AddHandler('https://api.twitter.com/1.1/statuses/update.json', curry(self._OpenTestData, 'update.json'))
status = self._api.PostUpdate(u'\u041c\u043e\u0451 \u0441\u0443\u0434\u043d\u043e \u043d\u0430 \u0432\u043e\u0437\u0434\u0443\u0448\u043d\u0... |
'Test the twitter.Api PostRetweet method'
| def testPostRetweet(self):
| time.sleep(8)
print 'Testing PostRetweet'
self._AddHandler('https://api.twitter.com/1.1/statuses/retweet/89512102.json', curry(self._OpenTestData, 'retweet.json'))
status = self._api.PostRetweet(89512102)
self.assertEqual(89512102, status.id)
|
'Test the twitter.Api PostUpdate method, when used in conjunction with latitude and longitude'
| def testPostUpdateLatLon(self):
| time.sleep(8)
print 'Testing PostUpdateLatLon'
self._AddHandler('https://api.twitter.com/1.1/statuses/update.json', curry(self._OpenTestData, 'update_latlong.json'))
status = self._api.PostUpdate(u'\u041c\u043e\u0451 \u0441\u0443\u0434\u043d\u043e \u043d\u0430 \u0432\u043e\u0437\u0434\u0443\... |
'Test the twitter.Api GetReplies method'
| def testGetReplies(self):
| time.sleep(8)
print 'Testing GetReplies'
self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json', curry(self._OpenTestData, 'replies.json'))
statuses = self._api.GetReplies()
self.assertEqual(36657062, statuses[0].id)
|
'Test the twitter.API GetRetweetsOfMe method'
| def testGetRetweetsOfMe(self):
| time.sleep(8)
print 'Testing GetRetweetsOfMe'
self._AddHandler('https://api.twitter.com/1.1/statuses/retweets_of_me.json', curry(self._OpenTestData, 'retweets_of_me.json'))
retweets = self._api.GetRetweetsOfMe()
self.assertEqual(253650670274637824, retweets[0].id)
|
'Test the twitter.Api GetFriends method'
| def testGetFriends(self):
| time.sleep(8)
print 'Testing GetFriends'
self._AddHandler('https://api.twitter.com/1.1/friends/list.json?cursor=123', curry(self._OpenTestData, 'friends.json'))
users = self._api.GetFriends(cursor=123)
buzz = [u.status for u in users if (u.screen_name == 'buzz')]
self.assertEqual(89543882, bu... |
'Test the twitter.Api GetFollowers method'
| def testGetFollowers(self):
| time.sleep(8)
print 'Testing GetFollowers'
self._AddHandler('https://api.twitter.com/1.1/followers/list.json?cursor=-1', curry(self._OpenTestData, 'followers.json'))
users = self._api.GetFollowers()
alexkingorg = [u.status for u in users if (u.screen_name == 'alexkingorg')]
self.assertEqual(8... |
'Test the twitter.Api GetDirectMessages method'
| def testGetDirectMessages(self):
| time.sleep(8)
print 'Testing GetDirectMessages'
self._AddHandler('https://api.twitter.com/1.1/direct_messages.json', curry(self._OpenTestData, 'direct_messages.json'))
statuses = self._api.GetDirectMessages()
self.assertEqual(u'A l\xe9gp\xe1rn\xe1s haj\xf3m tele van angoln\xe1kkal.... |
'Test the twitter.Api PostDirectMessage method'
| def testPostDirectMessage(self):
| time.sleep(8)
print 'Testing PostDirectMessage'
self._AddHandler('https://api.twitter.com/1.1/direct_messages/new.json', curry(self._OpenTestData, 'direct_messages-new.json'))
status = self._api.PostDirectMessage('test', u'\u041c\u043e\u0451 \u0441\u0443\u0434\u043d\u043e \u043d\u0430 \u0432... |
'Test the twitter.Api DestroyDirectMessage method'
| def testDestroyDirectMessage(self):
| time.sleep(8)
print 'Testing DestroyDirectMessage'
self._AddHandler('https://api.twitter.com/1.1/direct_messages/destroy.json', curry(self._OpenTestData, 'direct_message-destroy.json'))
status = self._api.DestroyDirectMessage(3496342)
self.assertEqual(673483, status.sender_id)
|
'Test the twitter.Api CreateFriendship method'
| def testCreateFriendship(self):
| time.sleep(8)
print 'Testing CreateFriendship'
self._AddHandler('https://api.twitter.com/1.1/friendships/create.json', curry(self._OpenTestData, 'friendship-create.json'))
user = self._api.CreateFriendship('dewitt')
self.assertEqual(673483, user.id)
|
'Test the twitter.Api DestroyFriendship method'
| def testDestroyFriendship(self):
| time.sleep(8)
print 'Testing Destroy Friendship'
self._AddHandler('https://api.twitter.com/1.1/friendships/destroy.json', curry(self._OpenTestData, 'friendship-destroy.json'))
user = self._api.DestroyFriendship('dewitt')
self.assertEqual(673483, user.id)
|
'Test the twitter.Api GetUser method'
| def testGetUser(self):
| time.sleep(8)
print 'Testing GetUser'
self._AddHandler('https://api.twitter.com/1.1/users/show.json?user_id=dewitt', curry(self._OpenTestData, 'show-dewitt.json'))
user = self._api.GetUser('dewitt')
self.assertEqual('dewitt', user.screen_name)
self.assertEqual(89586072, user.status.id)
|
'Attempt to find the username in a cross-platform fashion.'
| def _GetUsername(self):
| try:
return (os.getenv('USER') or os.getenv('LOGNAME') or os.getenv('USERNAME') or os.getlogin() or 'nobody')
except (AttributeError, IOError, OSError):
return 'nobody'
|
'Returns a string representation of TwitterModel. By default
this is the same as AsJsonString().'
| def __str__(self):
| return self.AsJsonString()
|
'Returns the TwitterModel as a JSON string based on key/value
pairs returned from the AsDict() method.'
| def AsJsonString(self):
| return json.dumps(self.AsDict(), sort_keys=True)
|
'Create a dictionary representation of the object. Please see inline
comments on construction when dictionaries contain TwitterModels.'
| def AsDict(self):
| data = {}
for (key, value) in self.param_defaults.items():
if isinstance(getattr(self, key, None), (list, tuple, set)):
data[key] = list()
for subobj in getattr(self, key, None):
if getattr(subobj, u'AsDict', None):
data[key].append(subobj.AsDi... |
'Create a new instance based on a JSON dict. Any kwargs should be
supplied by the inherited, calling class.
Args:
data: A JSON dict, as converted from the JSON in the twitter API.'
| @classmethod
def NewFromJsonDict(cls, data, **kwargs):
| json_data = data.copy()
if kwargs:
for (key, val) in kwargs.items():
json_data[key] = val
c = cls(**json_data)
c._json = data
return c
|
'Get the time this status message was posted, in seconds since
the epoch (1 Jan 1970).
Returns:
int: The time this status message was posted, in seconds since
the epoch.'
| @property
def created_at_in_seconds(self):
| return timegm(parsedate(self.created_at))
|
'A string representation of this twitter.Status instance.
The return value is the ID of status, username and datetime.
Returns:
string: A string representation of this twitter.Status instance with
the ID of status, username and datetime.'
| def __repr__(self):
| if (self.tweet_mode == u'extended'):
text = self.full_text
else:
text = self.text
if self.user:
return u'Status(ID={0}, ScreenName={1}, Created={2}, Text={3!r})'.format(self.id, self.user.screen_name, self.created_at, text)
else:
return u'Status(ID={0}, Create... |
'Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Status instance'
| @classmethod
def NewFromJsonDict(cls, data, **kwargs):
| current_user_retweet = None
hashtags = None
media = None
quoted_status = None
retweeted_status = None
urls = None
user = None
user_mentions = None
if (u'user' in data):
user = User.NewFromJsonDict(data[u'user'])
if (u'retweeted_status' in data):
retweeted_status =... |
'Returns the first argument used to construct this error.'
| @property
def message(self):
| return self.args[0]
|
'Instantiates the RateLimitObject. Takes a json dict as
kwargs and maps to the object\'s dictionary. So for something like:
{"resources": {
"help": {
/help/privacy": {
"limit": 15,
"remaining": 15,
"reset": 1452254278
the RateLimit object will have an attribute \'resources\' from which you
can perform a lookup like:
ap... | def __init__(self, **kwargs):
| self.__dict__['resources'] = {}
self.__dict__.update(kwargs)
|
'Take a fully qualified URL and attempts to return the rate limit
resource family corresponding to it. For example:
>>> RateLimit.url_to_resource(\'https://api.twitter.com/1.1/statuses/lookup.json?id=317\')
>>> \'/statuses/lookup\'
Args:
url (str): URL to convert to a resource family.
Returns:
string: Resource family c... | @staticmethod
def url_to_resource(url):
| resource = urlparse(url).path.replace('/1.1', '').replace('.json', '')
for non_std_endpoint in NON_STANDARD_ENDPOINTS:
if re.match(non_std_endpoint.regex, resource):
return non_std_endpoint.resource
return resource
|
'If a resource family is unknown, add it to the object\'s
dictionary. This is to deal with new endpoints being added to
the API, but not necessarily to the information returned by
``/account/rate_limit_status.json`` endpoint.
For example, if Twitter were to add an endpoint
``/puppies/lookup.json``, the RateLimit object... | def set_limit(self, url, limit, remaining, reset):
| endpoint = self.url_to_resource(url)
resource_family = endpoint.split('/')[1]
new_endpoint = {endpoint: {'limit': enf_type('limit', int, limit), 'remaining': enf_type('remaining', int, remaining), 'reset': enf_type('reset', int, reset)}}
if (not self.resources.get(resource_family, None)):
self.r... |
'Gets a EndpointRateLimit object for the given url.
Args:
url (str, optional):
URL of the endpoint for which to return the rate limit
status.
Returns:
namedtuple: EndpointRateLimit object containing rate limit
information.'
| def get_limit(self, url):
| endpoint = self.url_to_resource(url)
resource_family = endpoint.split('/')[1]
try:
family_rates = self.resources.get(resource_family).get(endpoint)
except AttributeError:
return EndpointRateLimit(limit=15, remaining=15, reset=0)
if (not family_rates):
self.set_unknown_limit(u... |
'Instantiate a new twitter.Api object.
Args:
consumer_key (str):
Your Twitter user\'s consumer_key.
consumer_secret (str):
Your Twitter user\'s consumer_secret.
access_token_key (str):
The oAuth access token key value you retrieved
from running get_access_token.py.
access_token_secret (str):
The oAuth access token\'s s... | def __init__(self, consumer_key=None, consumer_secret=None, access_token_key=None, access_token_secret=None, application_only_auth=False, input_encoding=None, request_headers=None, cache=DEFAULT_CACHE, base_url=None, stream_url=None, upload_url=None, chunk_size=(1024 * 1024), use_gzip_compression=False, debugHTTP=False... | if os.environ:
if ('APPENGINE_RUNTIME' in os.environ.keys()):
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
cache = None
self.SetCache(cache)
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._input_encoding ... |
'Generate a Bearer Token from consumer_key and consumer_secret'
| def GetAppOnlyAuthToken(self, consumer_key, consumer_secret):
| from urllib import quote_plus
import base64
key = quote_plus(consumer_key)
secret = quote_plus(consumer_secret)
bearer_token = base64.b64encode('{}:{}'.format(key, secret))
post_headers = {'Authorization': ('Basic ' + bearer_token), 'Content-Type': 'application/x-www-form-urlencoded;charset=U... |
'Set the consumer_key and consumer_secret for this instance
Args:
consumer_key:
The consumer_key of the twitter account.
consumer_secret:
The consumer_secret for the twitter account.
access_token_key:
The oAuth access token key value you retrieved
from running get_access_token.py.
access_token_secret:
The oAuth access ... | def SetCredentials(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None, application_only_auth=False):
| self._consumer_key = consumer_key
self._consumer_secret = consumer_secret
self._access_token_key = access_token_key
self._access_token_secret = access_token_secret
if application_only_auth:
self._bearer_token = self.GetAppOnlyAuthToken(consumer_key, consumer_secret)
self.__auth = OAu... |
'Get basic help configuration details from Twitter.
Args:
None
Returns:
dict: Sets self._config and returns dict of help config values.'
| def GetHelpConfiguration(self):
| if (self._config is None):
url = ('%s/help/configuration.json' % self.base_url)
resp = self._RequestUrl(url, 'GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
self._config = data
return self._config
|
'Returns number of characters reserved per URL included in a tweet.
Args:
https (bool, optional):
If True, return number of characters reserved for https urls
or, if False, return number of character reserved for http urls.
Returns:
(int): Number of characters reserved per URL.'
| def GetShortUrlLength(self, https=False):
| config = self.GetHelpConfiguration()
if https:
return config['short_url_length_https']
else:
return config['short_url_length']
|
'Clear any credentials for this instance'
| def ClearCredentials(self):
| self._consumer_key = None
self._consumer_secret = None
self._access_token_key = None
self._access_token_secret = None
self._bearer_token = None
self.__auth = None
|
'Return twitter search results for a given term. You must specify one
of term, geocode, or raw_query.
Args:
term (str, optional):
Term to search by. Optional if you include geocode.
raw_query (str, optional):
A raw query as a string. This should be everything after the "?" in
the URL (i.e., the query parameters). You a... | def GetSearch(self, term=None, raw_query=None, geocode=None, since_id=None, max_id=None, until=None, since=None, count=15, lang=None, locale=None, result_type='mixed', include_entities=None):
| url = ('%s/search/tweets.json' % self.base_url)
parameters = {}
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
if max_id:
parameters['max_id'] = enf_type('max_id', int, max_id)
if until:
parameters['until'] = enf_type('until', str, until)
if sin... |
'Return twitter user search results for a given term.
Args:
term:
Term to search by.
page:
Page of results to return. Default is 1
[Optional]
count:
Number of results to return. Default is 20
[Optional]
include_entities:
If True, each tweet will include a node called "entities,".
This node offers a variety of metadata... | def GetUsersSearch(self, term=None, page=1, count=20, include_entities=None):
| parameters = {}
if (term is not None):
parameters['q'] = term
if (page != 1):
parameters['page'] = page
if include_entities:
parameters['include_entities'] = 1
try:
parameters['count'] = int(count)
except ValueError:
raise TwitterError({'message': 'count ... |
'Get the current top trending topics (global)
Args:
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 10 entries. Each entry contains a trend.'
| def GetTrendsCurrent(self, exclude=None):
| return self.GetTrendsWoeid(woeid=1, exclude=exclude)
|
'Return the top 10 trending topics for a specific WOEID, if trending
information is available for it.
Args:
woeid:
the Yahoo! Where On Earth ID for a location.
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 10 entries. Each en... | def GetTrendsWoeid(self, woeid, exclude=None):
| url = ('%s/trends/place.json' % self.base_url)
parameters = {'id': woeid}
if exclude:
parameters['exclude'] = exclude
resp = self._RequestUrl(url, verb='GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
trends = []
timestamp = data[0]['as_of']
... |
'Return the list of suggested user categories, this can be used in
GetUserSuggestion function
Returns:
A list of categories'
| def GetUserSuggestionCategories(self):
| url = ('%s/users/suggestions.json' % self.base_url)
resp = self._RequestUrl(url, verb='GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
categories = []
for category in data:
categories.append(Category.NewFromJsonDict(category))
return categories
|
'Returns a list of users in a category
Args:
category:
The Category object to limit the search by
Returns:
A list of users in that category'
| def GetUserSuggestion(self, category):
| url = ('%s/users/suggestions/%s.json' % (self.base_url, category.slug))
resp = self._RequestUrl(url, verb='GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
users = []
for user in data['users']:
users.append(User.NewFromJsonDict(user))
return users
|
'Fetch a collection of the most recent Tweets and retweets posted
by the authenticating user and the users they follow.
The home timeline is central to how most users interact with Twitter.
Args:
count:
Specifies the number of statuses to retrieve. May not be
greater than 200. Defaults to 20. [Optional]
since_id:
Retur... | def GetHomeTimeline(self, count=None, since_id=None, max_id=None, trim_user=False, exclude_replies=False, contributor_details=False, include_entities=True):
| url = ('%s/statuses/home_timeline.json' % self.base_url)
parameters = {}
if (count is not None):
try:
if (int(count) > 200):
raise TwitterError({'message': "'count' may not be greater than 200"})
except ValueError:
raise TwitterError(... |
'Fetch the sequence of public Status messages for a single user.
The twitter.Api instance must be authenticated if the user is private.
Args:
user_id (int, optional):
Specifies the ID of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name.
screen_na... | def GetUserTimeline(self, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, include_rts=True, trim_user=False, exclude_replies=False):
| url = ('%s/statuses/user_timeline.json' % self.base_url)
parameters = {}
if user_id:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
parameters['screen_name'] = screen_name
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
... |
'Returns a single status message, specified by the status_id parameter.
Args:
status_id:
The numeric ID of the status you are trying to retrieve.
trim_user:
When set to True, each tweet returned in a timeline will include
a user object including only the status authors numerical ID.
Omit this parameter to receive the c... | def GetStatus(self, status_id, trim_user=False, include_my_retweet=True, include_entities=True, include_ext_alt_text=True):
| url = ('%s/statuses/show.json' % self.base_url)
parameters = {'id': enf_type('status_id', int, status_id), 'trim_user': enf_type('trim_user', bool, trim_user), 'include_my_retweet': enf_type('include_my_retweet', bool, include_my_retweet), 'include_entities': enf_type('include_entities', bool, include_entities)... |
'Returns information allowing the creation of an embedded representation of a
Tweet on third party sites.
Specify tweet by the id or url parameter.
Args:
status_id:
The numeric ID of the status you are trying to embed.
url:
The url of the status you are trying to embed.
maxwidth:
The maximum width in pixels that the em... | def GetStatusOembed(self, status_id=None, url=None, maxwidth=None, hide_media=False, hide_thread=False, omit_script=False, align=None, related=None, lang=None):
| request_url = ('%s/statuses/oembed.json' % self.base_url)
parameters = {}
if (status_id is not None):
try:
parameters['id'] = int(status_id)
except ValueError:
raise TwitterError({'message': "'status_id' must be an integer."})
elif (url is not None):
... |
'Destroys the status specified by the required ID parameter.
The authenticating user must be the author of the specified
status.
Args:
status_id (int):
The numerical ID of the status you\'re trying to destroy.
trim_user (bool, optional):
When set to True, each tweet returned in a timeline will include
a user object inc... | def DestroyStatus(self, status_id, trim_user=False):
| url = ('%s/statuses/destroy/%s.json' % (self.base_url, status_id))
post_data = {'id': enf_type('status_id', int, status_id), 'trim_user': enf_type('trim_user', bool, trim_user)}
resp = self._RequestUrl(url, 'POST', data=post_data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
retur... |
'Post a twitter status message from the authenticated user.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
Args:
status (str):
The message text to be posted. Must be less than or equal to 140
characters.
media (int, str, fp, optional):
A URL, a local file, or a file-like object (something with a
read() metho... | def PostUpdate(self, status, media=None, media_additional_owners=None, media_category=None, in_reply_to_status_id=None, auto_populate_reply_metadata=False, exclude_reply_user_ids=None, latitude=None, longitude=None, place_id=None, display_coordinates=False, trim_user=False, verify_status_length=True, attachment_url=Non... | url = ('%s/statuses/update.json' % self.base_url)
if (isinstance(status, str) or (self._input_encoding is None)):
u_status = status
else:
u_status = str(status, self._input_encoding)
if (verify_status_length and (calc_expected_status_length(u_status) > 140)):
raise TwitterError('... |
'Upload a media file to Twitter in one request. Used for small file
uploads that do not require chunked uploads.
Args:
media:
File-like object to upload.
additional_owners: additional Twitter users that are allowed to use
The uploaded media. Should be a list of integers. Maximum
number of additional owners is capped at... | def UploadMediaSimple(self, media, additional_owners=None, media_category=None):
| url = ('%s/media/upload.json' % self.upload_url)
parameters = {}
(media_fp, _, _, _) = parse_media_file(media)
parameters['media'] = media_fp.read()
if (additional_owners and (len(additional_owners) > 100)):
raise TwitterError({'message': 'Maximum of 100 additional owners may ... |
'Provide addtional data for uploaded media.
Args:
media_id:
ID of a previously uploaded media item.
alt_text:
Image Alternate Text.'
| def PostMediaMetadata(self, media_id, alt_text=None):
| url = ('%s/media/metadata/create.json' % self.upload_url)
parameters = {}
parameters['media_id'] = media_id
if alt_text:
parameters['alt_text'] = {'text': alt_text}
resp = self._RequestUrl(url, 'POST', json=parameters)
return resp
|
'Start a chunked upload to Twitter.
Args:
media:
File-like object to upload.
additional_owners: additional Twitter users that are allowed to use
The uploaded media. Should be a list of integers. Maximum
number of additional owners is capped at 100 by Twitter.
media_category:
Category with which to identify media upload... | def _UploadMediaChunkedInit(self, media, additional_owners=None, media_category=None):
| url = ('%s/media/upload.json' % self.upload_url)
(media_fp, filename, file_size, media_type) = parse_media_file(media)
if (not all([media_fp, filename, file_size, media_type])):
raise TwitterError({'message': 'Could not process media file'})
parameters = {}
if (additional_owners ... |
'Appends (i.e., actually uploads) media file to Twitter.
Args:
media_id (int):
ID of the media file received from Init method.
media_fp (file):
File-like object representing media file (must have .read() method)
filename (str):
Filename of the media file being uploaded.
Returns:
True if successful. Raises otherwise.'
| def _UploadMediaChunkedAppend(self, media_id, media_fp, filename):
| url = ('%s/media/upload.json' % self.upload_url)
boundary = '--{0}'.format(uuid4().hex).encode('utf-8')
media_id_bytes = str(media_id).encode('utf-8')
headers = {'Content-Type': 'multipart/form-data; boundary={0}'.format(boundary.decode('utf8')[2:])}
segment_id = 0
while True:
try:
... |
'Finalize chunked upload to Twitter.
Args:
media_id (int):
ID of the media file for which to finalize the upload.
Returns:
json: JSON string of data from Twitter.'
| def _UploadMediaChunkedFinalize(self, media_id):
| url = ('%s/media/upload.json' % self.upload_url)
parameters = {'command': 'FINALIZE', 'media_id': media_id}
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data
|
'Upload a media file to Twitter in multiple requests.
Args:
media:
File-like object to upload.
additional_owners: additional Twitter users that are allowed to use
The uploaded media. Should be a list of integers. Maximum
number of additional owners is capped at 100 by Twitter.
media_category:
Category with which to ide... | def UploadMediaChunked(self, media, additional_owners=None, media_category=None):
| (media_id, media_fp, filename) = self._UploadMediaChunkedInit(media=media, additional_owners=additional_owners, media_category=media_category)
append = self._UploadMediaChunkedAppend(media_id=media_id, media_fp=media_fp, filename=filename)
if (not append):
TwitterError('Media could not be ... |
'Post a twitter status message from the user with a picture attached.
Args:
status:
the text of your update
media:
This can be the location of media(PNG, JPG, GIF) on the local file
system or at an HTTP URL, it can also be a file-like object
possibly_sensitive:
set true if content is "advanced." [Optional]
in_reply_to_... | def PostMedia(self, status, media, possibly_sensitive=None, in_reply_to_status_id=None, latitude=None, longitude=None, place_id=None, display_coordinates=False):
| warnings.warn("This endpoint has been deprecated by Twitter. Please use PostUpdate() instead. Details of Twitter's deprecation can be found at: dev.twitter.com/rest/reference/post/statuses/update_with_media", PythonTwitterDeprecationWarning330)
url = ('%s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.