X Tutup
Skip to content

Commit 2506bc4

Browse files
committed
add basic support for tweet changes
1 parent 87e1976 commit 2506bc4

File tree

3 files changed

+68
-38
lines changed

3 files changed

+68
-38
lines changed

tests/test_rate_limit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def testLimitsViaHeadersWithSleep(self):
218218
method=responses.GET, url=url, body='{}', match_querystring=True)
219219

220220
# Get initial rate limit data to populate api.rate_limit object
221-
url = "https://api.twitter.com/1.1/search/tweets.json?tweet_mode=compatibility&q=test&count=15&result_type=mixed"
221+
url = "https://api.twitter.com/1.1/search/tweets.json?tweet_mode=compat&q=test&count=15&result_type=mixed"
222222
responses.add(
223223
method=responses.GET,
224224
url=url,

twitter/api.py

Lines changed: 56 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
#
44
#
5-
# Copyright 2007 The Python-Twitter Developers
5+
# Copyright 2007-2016 The Python-Twitter Developers
66
#
77
# Licensed under the Apache License, Version 2.0 (the "License");
88
# you may not use this file except in compliance with the License.
@@ -156,39 +156,55 @@ def __init__(self,
156156
use_gzip_compression=False,
157157
debugHTTP=False,
158158
timeout=None,
159-
sleep_on_rate_limit=False):
159+
sleep_on_rate_limit=False,
160+
tweet_mode='compat'):
160161
"""Instantiate a new twitter.Api object.
161162
162163
Args:
163-
consumer_key:
164+
consumer_key (str):
164165
Your Twitter user's consumer_key.
165-
consumer_secret:
166+
consumer_secret (str):
166167
Your Twitter user's consumer_secret.
167-
access_token_key:
168+
access_token_key (str):
168169
The oAuth access token key value you retrieved
169170
from running get_access_token.py.
170-
access_token_secret:
171+
access_token_secret (str):
171172
The oAuth access token's secret, also retrieved
172173
from the get_access_token.py run.
173-
input_encoding:
174-
The encoding used to encode input strings. [Optional]
175-
request_header:
176-
A dictionary of additional HTTP request headers. [Optional]
177-
cache:
174+
input_encoding (str, optional):
175+
The encoding used to encode input strings.
176+
request_header (dict, optional):
177+
A dictionary of additional HTTP request headers.
178+
cache (object, optional):
178179
The cache instance to use. Defaults to DEFAULT_CACHE.
179-
Use None to disable caching. [Optional]
180-
base_url:
180+
Use None to disable caching.
181+
base_url (str, optional):
181182
The base URL to use to contact the Twitter API.
182-
Defaults to https://api.twitter.com. [Optional]
183-
use_gzip_compression:
183+
Defaults to https://api.twitter.com.
184+
stream_url (str, optional):
185+
The base URL to use for streaming endpoints.
186+
Defaults to 'https://stream.twitter.com/1.1'.
187+
upload_url (str, optional):
188+
The base URL to use for uploads. Defaults to 'https://upload.twitter.com/1.1'.
189+
chunk_size (int, optional):
190+
Chunk size to use for chunked (multi-part) uploads of images/videos/gifs.
191+
Defaults to 1MB. Anything under 16KB and you run the risk of erroring out
192+
on 15MB files.
193+
use_gzip_compression (bool, optional):
184194
Set to True to tell enable gzip compression for any call
185-
made to Twitter. Defaults to False. [Optional]
186-
debugHTTP:
195+
made to Twitter. Defaults to False.
196+
debugHTTP (bool, optional):
187197
Set to True to enable debug output from urllib2 when performing
188-
any HTTP requests. Defaults to False. [Optional]
189-
timeout:
198+
any HTTP requests. Defaults to False.
199+
timeout (int, optional):
190200
Set timeout (in seconds) of the http/https requests. If None the
191-
requests lib default will be used. Defaults to None. [Optional]
201+
requests lib default will be used. Defaults to None.
202+
sleep_on_rate_limit (bool, optional):
203+
Whether to sleep an appropriate amount of time if a rate limit is hit for
204+
an endpoint.
205+
tweet_mode (str, optional):
206+
Whether to use the new (as of Sept. 2016) extended tweet mode. See docs for
207+
details. Choices are ['compatibility', 'extended'].
192208
"""
193209

194210
# check to see if the library is running on a Google App Engine instance
@@ -214,6 +230,7 @@ def __init__(self,
214230

215231
self.rate_limit = RateLimit()
216232
self.sleep_on_rate_limit = sleep_on_rate_limit
233+
self.tweet_mode = tweet_mode
217234

218235
if base_url is None:
219236
self.base_url = 'https://api.twitter.com/1.1'
@@ -890,6 +907,8 @@ def PostUpdate(self,
890907
media_additional_owners=None,
891908
media_category=None,
892909
in_reply_to_status_id=None,
910+
auto_populate_reply_metadata=False,
911+
exclude_reply_user_ids=None,
893912
latitude=None,
894913
longitude=None,
895914
place_id=None,
@@ -959,7 +978,17 @@ def PostUpdate(self,
959978
if verify_status_length and calc_expected_status_length(u_status) > 140:
960979
raise TwitterError("Text must be less than or equal to 140 characters.")
961980

962-
parameters = {'status': u_status}
981+
if auto_populate_reply_metadata and not in_reply_to_status_id:
982+
raise TwitterError("If auto_populate_reply_metadata is True, you must set in_reply_to_status_id")
983+
984+
parameters = {
985+
'status': u_status,
986+
'in_reply_to_status_id': in_reply_to_status_id,
987+
'auto_populate_reply_metadata': auto_populate_reply_metadata,
988+
'place_id': place_id,
989+
'display_coordinates': display_coordinates,
990+
'trim_user': trim_user,
991+
}
963992

964993
if media:
965994
media_ids = []
@@ -993,25 +1022,16 @@ def PostUpdate(self,
9931022
else:
9941023
_, _, file_size, _ = parse_media_file(media)
9951024
if file_size > self.chunk_size:
996-
media_ids.append(self.UploadMediaChunked(media,
997-
media_additional_owners))
1025+
media_ids.append(
1026+
self.UploadMediaChunked(media, media_additional_owners))
9981027
else:
9991028
media_ids.append(
1000-
self.UploadMediaSimple(media,
1001-
media_additional_owners))
1029+
self.UploadMediaSimple(media, media_additional_owners))
10021030
parameters['media_ids'] = ','.join([str(mid) for mid in media_ids])
10031031

1004-
if in_reply_to_status_id:
1005-
parameters['in_reply_to_status_id'] = in_reply_to_status_id
10061032
if latitude is not None and longitude is not None:
10071033
parameters['lat'] = str(latitude)
10081034
parameters['long'] = str(longitude)
1009-
if place_id is not None:
1010-
parameters['place_id'] = str(place_id)
1011-
if display_coordinates:
1012-
parameters['display_coordinates'] = 'true'
1013-
if trim_user:
1014-
parameters['trim_user'] = 'true'
10151035

10161036
resp = self._RequestUrl(url, 'POST', data=parameters)
10171037
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
@@ -4833,8 +4853,7 @@ def _RequestUrl(self, url, verb, data=None, json=None):
48334853
A JSON object.
48344854
"""
48354855
if not self.__auth:
4836-
raise TwitterError(
4837-
"The twitter.Api instance must be authenticated.")
4856+
raise TwitterError("The twitter.Api instance must be authenticated.")
48384857

48394858
if url and self.sleep_on_rate_limit:
48404859
limit = self.CheckRateLimit(url)
@@ -4860,6 +4879,8 @@ def _RequestUrl(self, url, verb, data=None, json=None):
48604879
resp = 0 # POST request, but without data or json
48614880

48624881
elif verb == 'GET':
4882+
if data:
4883+
data['tweet_mode'] = self.tweet_mode
48634884
url = self._BuildUrl(url, extra_params=data)
48644885
resp = requests.get(url, auth=self.__auth, timeout=self._timeout)
48654886

twitter/models.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,14 @@ def NewFromJsonDict(cls, data, **kwargs):
7878
7979
"""
8080

81+
json_data = data.copy()
8182
if kwargs:
8283
for key, val in kwargs.items():
83-
data[key] = val
84+
json_data[key] = val
8485

85-
return cls(**data)
86+
c = cls(**json_data)
87+
c._json = data
88+
return c
8689

8790

8891
class Media(TwitterModel):
@@ -379,6 +382,7 @@ def __init__(self, **kwargs):
379382
'current_user_retweet': None,
380383
'favorite_count': None,
381384
'favorited': None,
385+
'full_text': None,
382386
'geo': None,
383387
'hashtags': None,
384388
'id': None,
@@ -409,6 +413,11 @@ def __init__(self, **kwargs):
409413
for (param, default) in self.param_defaults.items():
410414
setattr(self, param, kwargs.get(param, default))
411415

416+
if kwargs.get('full_text', None):
417+
self.tweet_mode = 'extended'
418+
else:
419+
self.tweet_mode = 'compatibility'
420+
412421
@property
413422
def created_at_in_seconds(self):
414423
""" Get the time this status message was posted, in seconds since

0 commit comments

Comments
 (0)
X Tutup