`_
-
-Want to help?
--------------
-
-Twython is useful, but ultimately only as useful as the people using it (say that ten times fast!). If you'd like to help, write example code, contribute patches, document things on the wiki, tweet about it. Your help is always appreciated!
diff --git a/docs/_themes/basicstrap/customsidebar.html b/docs/_themes/basicstrap/customsidebar.html
index ac8c5837..dbeab995 100644
--- a/docs/_themes/basicstrap/customsidebar.html
+++ b/docs/_themes/basicstrap/customsidebar.html
@@ -1,18 +1,5 @@
-{{ _('Donate') }}
-
-
-Find Twython useful? Consider supporting the author on Gittip:
-
-
-
-
-
-
{{ _('Links') }}
\ No newline at end of file
+
diff --git a/docs/conf.py b/docs/conf.py
index 23044e32..3ffa5b59 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -50,9 +50,9 @@
# built documents.
#
# The short X.Y version.
-version = '3.4.0'
+version = '3.8.0'
# The full version, including alpha/beta/rc tags.
-release = '3.4.0'
+release = '3.8.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/docs/index.rst b/docs/index.rst
index 1aa13e0c..05d2838b 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -16,7 +16,7 @@ Features
- Twitter lists
- Timelines
- Direct Messages
- - and anything found in `the Twitter API docs `_.
+ - and anything found in `the Twitter API docs `_.
- Image Uploading:
- Update user status with an image
- Change user avatar
diff --git a/docs/usage/advanced_usage.rst b/docs/usage/advanced_usage.rst
index fac35c21..df3bc485 100644
--- a/docs/usage/advanced_usage.rst
+++ b/docs/usage/advanced_usage.rst
@@ -29,11 +29,11 @@ This uploads an image as a media object and associates it with a status update.
photo = open('/path/to/file/image.jpg', 'rb')
response = twitter.upload_media(media=photo)
twitter.update_status(status='Checkout this cool image!', media_ids=[response['media_id']])
-
+
Documentation:
-* https://dev.twitter.com/rest/reference/post/statuses/update
-* https://dev.twitter.com/rest/reference/post/media/upload
+* https://developer.twitter.com/en/docs/api-reference-index
+* https://developer.twitter.com/en/docs/media/upload-media/overview
Updating Status with Video
--------------------------
@@ -48,8 +48,8 @@ This uploads a video as a media object and associates it with a status update.
Documentation:
-* https://dev.twitter.com/rest/reference/post/statuses/update
-* https://dev.twitter.com/rest/reference/post/media/upload
+* https://developer.twitter.com/en/docs/api-reference-index
+* https://developer.twitter.com/en/docs/media/upload-media/overview
Posting a Status with an Editing Image
--------------------------------------
@@ -59,10 +59,10 @@ with a status update.
.. code-block:: python
- # Assume you are working with a JPEG
+ # Assuming that you are working with a JPEG
from PIL import Image
- from StringIO import StringIO
+ from io import BytesIO
photo = Image.open('/path/to/file/image.jpg')
@@ -71,14 +71,13 @@ with a status update.
height = int((float(photo.size[1]) * float(wpercent)))
photo = photo.resize((basewidth, height), Image.ANTIALIAS)
- image_io = StringIO.StringIO()
+ image_io = BytesIO()
photo.save(image_io, format='JPEG')
# If you do not seek(0), the image will be at the end of the file and
# unable to be read
image_io.seek(0)
-
response = twitter.upload_media(media=image_io)
twitter.update_status(status='Checkout this cool image!', media_ids=[response['media_id']])
@@ -98,7 +97,7 @@ That being said, Twython offers a generator for search results and can be access
results = twitter.cursor(twitter.search, q='python')
for result in results:
- print result
+ print(result)
Manipulate the Request (headers, proxies, etc.)
-----------------------------------------------
diff --git a/docs/usage/basic_usage.rst b/docs/usage/basic_usage.rst
index 84ffb087..8fee8078 100644
--- a/docs/usage/basic_usage.rst
+++ b/docs/usage/basic_usage.rst
@@ -28,7 +28,7 @@ Create a Twython instance with your application keys and the users OAuth tokens
User Information
^^^^^^^^^^^^^^^^
-Documentation: https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials
+Documentation: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
.. code-block:: python
@@ -37,7 +37,7 @@ Documentation: https://dev.twitter.com/docs/api/1.1/get/account/verify_credentia
Authenticated Users Home Timeline
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
+Documentation: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
.. code-block:: python
@@ -48,7 +48,7 @@ Updating Status
This method makes use of dynamic arguments, :ref:`read more about them `
-Documentation: https://dev.twitter.com/docs/api/1.1/post/statuses/update
+Documentation: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
.. code-block:: python
@@ -72,7 +72,7 @@ Searching
.. note:: Searching can be done whether you're authenticated via OAuth 1 or OAuth 2
-Documentation: https://dev.twitter.com/docs/api/1.1/get/search/tweets
+Documentation: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
.. code-block:: python
@@ -80,7 +80,7 @@ Documentation: https://dev.twitter.com/docs/api/1.1/get/search/tweets
.. _dynamicargexplaination:
-.. important:: To help explain :ref:`dynamic function arguments ` a little more, you can see that the previous call used the keyword argument ``q``, that is because Twitter specifies in their `search documentation `_ that the search call accepts the parameter "q". You can pass mutiple keyword arguments. The search documentation also specifies that the call accepts the parameter "result_type"
+.. important:: To help explain :ref:`dynamic function arguments ` a little more, you can see that the previous call used the keyword argument ``q``, that is because Twitter specifies in their `search documentation `_ that the search call accepts the parameter "q". You can pass mutiple keyword arguments. The search documentation also specifies that the call accepts the parameter "result_type"
.. code-block:: python
diff --git a/docs/usage/special_functions.rst b/docs/usage/special_functions.rst
index 97e674c5..301abd35 100644
--- a/docs/usage/special_functions.rst
+++ b/docs/usage/special_functions.rst
@@ -25,7 +25,7 @@ The Old Way
results = twitter.search(q='twitter')
if results.get('statuses'):
for result in results['statuses']:
- print result['id_str']
+ print(result['id_str'])
The New Way
^^^^^^^^^^^
@@ -39,15 +39,28 @@ The New Way
results = twitter.cursor(twitter.search, q='twitter')
for result in results:
- print result['id_str']
+ print(result['id_str'])
Another example:
.. code-block:: python
- results = twitter.cursor(t.get_mentions_timeline)
+ results = twitter.cursor(twitter.get_mentions_timeline)
for result in results:
- print result['id_str']
+ print(result['id_str'])
+
+Items vs Pages
+^^^^^^^^^^^^^^
+
+By default, the cursor yields one item at a time. If instead you prefer to work with entire pages of results, specify ``return_pages=True`` as a keyword argument.
+
+.. code-block:: python
+
+ results = twitter.cursor(twitter.get_mentions_timeline, return_pages=True)
+ # page is a list
+ for page in results:
+ for result in page:
+ print(result['id_str'])
HTML for Tweet
@@ -66,7 +79,7 @@ This function takes a tweet object received from the Twitter API and returns an
include_rts=True)
for tweet in user_tweets:
tweet['text'] = Twython.html_for_tweet(tweet)
- print tweet['text']
+ print(tweet['text'])
The above code takes all the tweets from a specific users timeline, loops over them and replaces the value of ``tweet['text']`` with HTML.
diff --git a/docs/usage/starting_out.rst b/docs/usage/starting_out.rst
index 0a681acb..7bb3d94e 100644
--- a/docs/usage/starting_out.rst
+++ b/docs/usage/starting_out.rst
@@ -10,7 +10,7 @@ This section is going to help you understand creating a Twitter Application, aut
Beginning
---------
-First, you'll want to head over to https://dev.twitter.com/apps and register an application!
+First, you'll want to head over to https://apps.twitter.com/ and register an application!
After you register, grab your applications ``Consumer Key`` and ``Consumer Secret`` from the application details tab.
diff --git a/docs/usage/streaming_api.rst b/docs/usage/streaming_api.rst
index 8b21c700..97ef6eaa 100644
--- a/docs/usage/streaming_api.rst
+++ b/docs/usage/streaming_api.rst
@@ -5,7 +5,7 @@ Streaming API
This section will cover how to use Twython and interact with the Twitter Streaming API.
-Streaming Documentation: https://dev.twitter.com/docs/streaming-apis
+Streaming Documentation: https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/streaming-message-types
.. important:: The Streaming API requires that you have OAuth 1 authentication credentials. If you don't have credentials, head over to the :ref:`authentication section ` and find out how!
@@ -27,10 +27,10 @@ Now set up how you want to handle the signals.
class MyStreamer(TwythonStreamer):
def on_success(self, data):
if 'text' in data:
- print data['text'].encode('utf-8')
+ print(data['text'])
def on_error(self, status_code, data):
- print status_code
+ print(status_code)
# Want to stop trying to get data because of the error?
# Uncomment the next line!
diff --git a/examples/get_direct_messages.py b/examples/get_direct_messages.py
new file mode 100644
index 00000000..fa80865b
--- /dev/null
+++ b/examples/get_direct_messages.py
@@ -0,0 +1,5 @@
+from twython import Twython, TwythonError
+twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
+
+get_list = twitter.get_direct_messages()
+print(get_list)
diff --git a/examples/get_user_timeline.py b/examples/get_user_timeline.py
index 0a1f4df5..55ab427f 100644
--- a/examples/get_user_timeline.py
+++ b/examples/get_user_timeline.py
@@ -7,4 +7,4 @@
except TwythonError as e:
print e
-print user_timeline
+print(user_timeline)
diff --git a/get_direct_message example b/get_direct_message example
deleted file mode 100644
index 5a27a066..00000000
--- a/get_direct_message example
+++ /dev/null
@@ -1,17 +0,0 @@
-from twython import Twython, TwythonError
-twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
-
-
-get_list = twitter.get_direct_messages()
-#Returns All Twitter DM information which is a lot in a list format
-
-dm_dict = get_list[0]
-#Sets get_list to a dictionary, the number in the list is the direct message retrieved
-#That means that 0 is the most recent and n-1 is the last DM revieved.
-#You can cycle through all the numbers and it will return the text and the sender id of each
-
-print dm_dict['text']
-#Gets the text from the dictionary
-
-print dm_dict['sender']['id']
-#Gets the ID of the sender
diff --git a/setup.py b/setup.py
index 7b38b99e..a3600dec 100755
--- a/setup.py
+++ b/setup.py
@@ -8,8 +8,8 @@
except ImportError:
from distutils.core import setup
-__author__ = 'Ryan McGrath '
-__version__ = '3.4.0'
+__author__ = 'Ryan McGrath '
+__version__ = '3.9.1'
packages = [
'twython',
@@ -24,15 +24,15 @@
name='twython',
version=__version__,
install_requires=['requests>=2.1.0', 'requests_oauthlib>=0.4.0'],
+ python_requires='>=3.5',
author='Ryan McGrath',
- author_email='ryan@venodesigns.net',
- license=open('LICENSE').read(),
+ author_email='ryan@rymc.io',
+ license='MIT',
url='https://github.com/ryanmcgrath/twython/tree/master',
keywords='twitter search api tweet twython stream',
- description='Actively maintained, pure Python wrapper for the \
- Twitter API. Supports both normal and streaming Twitter APIs',
- long_description=open('README.rst').read() + '\n\n' +
- open('HISTORY.rst').read(),
+ description='Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs',
+ long_description=open('README.md', encoding='utf-8').read() + '\n\n' +open('HISTORY.md', encoding='utf-8').read(),
+ long_description_content_type='text/markdown',
include_package_data=True,
packages=packages,
classifiers=[
@@ -41,6 +41,11 @@
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
- 'Topic :: Internet'
+ 'Topic :: Internet',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3 :: Only',
+ 'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
]
)
diff --git a/tests/config.py b/tests/config.py
index 607bdd88..10ab3ea9 100644
--- a/tests/config.py
+++ b/tests/config.py
@@ -1,10 +1,8 @@
+# -*- coding: utf-8 -*-
import os
import sys
-if sys.version_info[0] == 2 and sys.version_info[1] == 6:
- import unittest2 as unittest
-else:
- import unittest
+import unittest
app_key = os.environ.get('APP_KEY')
app_secret = os.environ.get('APP_SECRET')
@@ -26,11 +24,3 @@
test_list_owner_screen_name = os.environ.get('TEST_LIST_OWNER_SCREEN_NAME',
'twitterapi')
-test_tweet_object = {u'contributors': None, u'truncated': False, u'text': u'http://t.co/FCmXyI6VHd is a #cool site, lol! @mikehelmick shd #checkitout. Love, @__twython__ https://t.co/67pwRvY6z9 http://t.co/N6InAO4B71', u'in_reply_to_status_id': None, u'id': 349683012054683648, u'favorite_count': 0, u'source': u'web', u'retweeted': False, u'coordinates': None, u'entities': {u'symbols': [], u'user_mentions': [{u'id': 29251354, u'indices': [45, 57], u'id_str': u'29251354', u'screen_name': u'mikehelmick', u'name': u'Mike Helmick'}, {u'id': 1431865928, u'indices': [81, 93], u'id_str': u'1431865928', u'screen_name': u'__twython__', u'name': u'Twython'}], u'hashtags': [{u'indices': [28, 33], u'text': u'cool'}, {u'indices': [62, 73], u'text': u'checkitout'}], u'urls': [{u'url': u'http://t.co/FCmXyI6VHd', u'indices': [0, 22], u'expanded_url': u'http://google.com', u'display_url': u'google.com'}, {u'url': u'https://t.co/67pwRvY6z9', u'indices': [94, 117], u'expanded_url': u'https://github.com', u'display_url': u'github.com'}], u'media': [{u'id': 537884378513162240, u'id_str': u'537884378513162240', u'indices': [118, 140], u'media_url': u'http://pbs.twimg.com/media/B3by_g-CQAAhrO5.jpg', u'media_url_https': u'https://pbs.twimg.com/media/B3by_g-CQAAhrO5.jpg', u'url': u'http://t.co/N6InAO4B71', u'display_url': u'pic.twitter.com/N6InAO4B71', u'expanded_url': u'http://twitter.com/pingofglitch/status/537884380060844032/photo/1', u'type': u'photo', u'sizes': {u'large': {u'w': 1024, u'h': 640, u'resize': u'fit'}, u'thumb': {u'w': 150, u'h': 150, u'resize': u'crop'}, u'medium': {u'w': 600, u'h': 375, u'resize': u'fit'}, u'small': {u'w': 340, u'h': 212, u'resize': u'fit'}}}]}, u'in_reply_to_screen_name': None, u'id_str': u'349683012054683648', u'retweet_count': 0, u'in_reply_to_user_id': None, u'favorited': False, u'user': {u'follow_request_sent': False, u'profile_use_background_image': True, u'default_profile_image': True, u'id': 1431865928, u'verified': False, u'profile_text_color': u'333333', u'profile_image_url_https': u'https://si0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png', u'profile_sidebar_fill_color': u'DDEEF6', u'entities': {u'description': {u'urls': []}}, u'followers_count': 1, u'profile_sidebar_border_color': u'C0DEED', u'id_str': u'1431865928', u'profile_background_color': u'3D3D3D', u'listed_count': 0, u'profile_background_image_url_https': u'https://si0.twimg.com/images/themes/theme1/bg.png', u'utc_offset': None, u'statuses_count': 2, u'description': u'', u'friends_count': 1, u'location': u'', u'profile_link_color': u'0084B4', u'profile_image_url': u'http://a0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png', u'following': False, u'geo_enabled': False, u'profile_background_image_url': u'http://a0.twimg.com/images/themes/theme1/bg.png', u'screen_name': u'__twython__', u'lang': u'en', u'profile_background_tile': False, u'favourites_count': 0, u'name': u'Twython', u'notifications': False, u'url': None, u'created_at': u'Thu May 16 01:11:09 +0000 2013', u'contributors_enabled': False, u'time_zone': None, u'protected': False, u'default_profile': False, u'is_translator': False}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'lang': u'en', u'created_at': u'Wed Jun 26 00:18:21 +0000 2013', u'in_reply_to_status_id_str': None, u'place': None}
-test_tweet_html = 'google.com is a #cool site, lol! @mikehelmick shd #checkitout. Love, @__twython__ github.com pic.twitter.com/N6InAO4B71'
-
-test_tweet_symbols_object = {u'text': u'Some symbols: $AAPL and $PEP and $ANOTHER and $A.', u'contributors': None, u'geo': None, u'favorited': True, u'in_reply_to_user_id_str': None, u'user': {u'location': u'', u'id_str': u'2030131', u'protected': False, u'profile_background_tile': False, u'friends_count': 18, u'profile_background_image_url_https': u'https://abs.twimg.com/images/themes/theme1/bg.png', u'entities': {u'description': {u'urls': []}}, u'lang': u'en', u'listed_count': 5, u'default_profile_image': True, u'default_profile': False, u'statuses_count': 447, u'notifications': False, u'profile_background_color': u'9AE4E8', u'profile_sidebar_fill_color': u'E0FF92', u'profile_link_color': u'0000FF', u'profile_image_url_https': u'https://abs.twimg.com/sticky/default_profile_images/default_profile_5_normal.png', u'followers_count': 8, u'geo_enabled': True, u'following': True, u'has_extended_profile': False, u'profile_use_background_image': True, u'profile_text_color': u'000000', u'screen_name': u'philgyfordtest', u'contributors_enabled': False, u'verified': False, u'name': u'Phil Gyford Test', u'profile_sidebar_border_color': u'000000', u'utc_offset': 0, u'profile_image_url': u'http://abs.twimg.com/sticky/default_profile_images/default_profile_5_normal.png', u'id': 2030131, u'favourites_count': 0, u'time_zone': u'London', u'url': None, u'is_translation_enabled': False, u'is_translator': False, u'profile_background_image_url': u'http://abs.twimg.com/images/themes/theme1/bg.png', u'description': u'', u'created_at': u'Fri Mar 23 16:56:52 +0000 2007', u'follow_request_sent': False}, u'in_reply_to_user_id': None, u'retweeted': False, u'coordinates': None, u'place': None, u'in_reply_to_status_id': None, u'lang': u'en', u'in_reply_to_status_id_str': None, u'truncated': False, u'retweet_count': 0, u'is_quote_status': False, u'id': 662694880657989632, u'id_str': u'662694880657989632', u'in_reply_to_screen_name': None, u'favorite_count': 1, u'entities': {u'hashtags': [], u'user_mentions': [], u'symbols': [{u'indices': [14, 19], u'text': u'AAPL'}, {u'indices': [24, 28], u'text': u'PEP'}, {u'indices': [46, 48], u'text': u'A'}], u'urls': []}, u'created_at': u'Fri Nov 06 18:15:46 +0000 2015', u'source': u'Tweetbot for Mac'}
-
-test_tweet_compat_object = {u'contributors': None, u'truncated': True, u'text': u"Say more about what's happening! Rolling out now: photos, videos, GIFs, polls, and Quote Tweets no longer count tow\u2026 https://t.co/SRmsuks2ru", u'is_quote_status': False, u'in_reply_to_status_id': None, u'id': 777915304261193728, u'favorite_count': 13856, u'source': u'Twitter Web Client', u'retweeted': False, u'coordinates': None, u'entities': {u'symbols': [], u'user_mentions': [], u'hashtags': [], u'urls': [{u'url': u'https://t.co/SRmsuks2ru', u'indices': [117, 140], u'expanded_url': u'https://twitter.com/i/web/status/777915304261193728', u'display_url': u'twitter.com/i/web/status/7\u2026'}]}, u'in_reply_to_screen_name': None, u'id_str': u'777915304261193728', u'retweet_count': 14767, u'in_reply_to_user_id': None, u'favorited': False, u'user': {u'follow_request_sent': False, u'has_extended_profile': False, u'profile_use_background_image': True, u'id': 783214, u'verified': True, u'profile_text_color': u'333333', u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg', u'profile_sidebar_fill_color': u'F6F6F6', u'is_translator': False, u'geo_enabled': True, u'entities': {u'url': {u'urls': [{u'url': u'http://t.co/5iRhy7wTgu', u'indices': [0, 22], u'expanded_url': u'http://blog.twitter.com/', u'display_url': u'blog.twitter.com'}]}, u'description': {u'urls': [{u'url': u'https://t.co/qq1HEzvnrA', u'indices': [84, 107], u'expanded_url': u'http://support.twitter.com', u'display_url': u'support.twitter.com'}]}}, u'followers_count': 56827498, u'protected': False, u'location': u'San Francisco, CA', u'default_profile_image': False, u'id_str': u'783214', u'lang': u'en', u'utc_offset': -25200, u'statuses_count': 3161, u'description': u'Your official source for news, updates and tips from Twitter, Inc. Need help? Visit https://t.co/qq1HEzvnrA.', u'friends_count': 145, u'profile_link_color': u'226699', u'profile_image_url': u'http://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg', u'notifications': False, u'profile_background_image_url_https': u'https://pbs.twimg.com/profile_background_images/657090062/l1uqey5sy82r9ijhke1i.png', u'profile_background_color': u'ACDED6', u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/783214/1471929200', u'profile_background_image_url': u'http://pbs.twimg.com/profile_background_images/657090062/l1uqey5sy82r9ijhke1i.png', u'name': u'Twitter', u'is_translation_enabled': False, u'profile_background_tile': True, u'favourites_count': 2332, u'screen_name': u'twitter', u'url': u'http://t.co/5iRhy7wTgu', u'created_at': u'Tue Feb 20 14:35:54 +0000 2007', u'contributors_enabled': False, u'time_zone': u'Pacific Time (US & Canada)', u'profile_sidebar_border_color': u'FFFFFF', u'default_profile': False, u'following': False, u'listed_count': 90445}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'possibly_sensitive_appealable': False, u'lang': u'en', u'created_at': u'Mon Sep 19 17:00:36 +0000 2016', u'in_reply_to_status_id_str': None, u'place': None}
-test_tweet_extended_object = {u'full_text': u"Say more about what's happening! Rolling out now: photos, videos, GIFs, polls, and Quote Tweets no longer count toward your 140 characters. https://t.co/I9pUC0NdZC", u'truncated': False, u'is_quote_status': False, u'in_reply_to_status_id': None, u'id': 777915304261193728, u'favorite_count': 13856, u'contributors': None, u'source': u'Twitter Web Client', u'retweeted': False, u'coordinates': None, u'entities': {u'symbols': [], u'user_mentions': [], u'hashtags': [], u'urls': [], u'media': [{u'expanded_url': u'https://twitter.com/twitter/status/777915304261193728/photo/1', u'sizes': {u'small': {u'h': 340, u'w': 340, u'resize': u'fit'}, u'large': {u'h': 700, u'w': 700, u'resize': u'fit'}, u'medium': {u'h': 600, u'w': 600, u'resize': u'fit'}, u'thumb': {u'h': 150, u'w': 150, u'resize': u'crop'}}, u'url': u'https://t.co/I9pUC0NdZC', u'media_url_https': u'https://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg', u'id_str': u'777914712382058496', u'indices': [140, 163], u'media_url': u'http://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg', u'type': u'photo', u'id': 777914712382058496, u'display_url': u'pic.twitter.com/I9pUC0NdZC'}]}, u'in_reply_to_screen_name': None, u'id_str': u'777915304261193728', u'display_text_range': [0, 139], u'retweet_count': 14767, u'in_reply_to_user_id': None, u'favorited': False, u'user': {u'follow_request_sent': False, u'has_extended_profile': False, u'profile_use_background_image': True, u'id': 783214, u'verified': True, u'profile_text_color': u'333333', u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg', u'profile_sidebar_fill_color': u'F6F6F6', u'is_translator': False, u'geo_enabled': True, u'entities': {u'url': {u'urls': [{u'url': u'http://t.co/5iRhy7wTgu', u'indices': [0, 22], u'expanded_url': u'http://blog.twitter.com/', u'display_url': u'blog.twitter.com'}]}, u'description': {u'urls': [{u'url': u'https://t.co/qq1HEzvnrA', u'indices': [84, 107], u'expanded_url': u'http://support.twitter.com', u'display_url': u'support.twitter.com'}]}}, u'followers_count': 56827498, u'protected': False, u'location': u'San Francisco, CA', u'default_profile_image': False, u'id_str': u'783214', u'lang': u'en', u'utc_offset': -25200, u'statuses_count': 3161, u'description': u'Your official source for news, updates and tips from Twitter, Inc. Need help? Visit https://t.co/qq1HEzvnrA.', u'friends_count': 145, u'profile_link_color': u'226699', u'profile_image_url': u'http://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg', u'notifications': False, u'profile_background_image_url_https': u'https://pbs.twimg.com/profile_background_images/657090062/l1uqey5sy82r9ijhke1i.png', u'profile_background_color': u'ACDED6', u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/783214/1471929200', u'profile_background_image_url': u'http://pbs.twimg.com/profile_background_images/657090062/l1uqey5sy82r9ijhke1i.png', u'name': u'Twitter', u'is_translation_enabled': False, u'profile_background_tile': True, u'favourites_count': 2332, u'screen_name': u'twitter', u'url': u'http://t.co/5iRhy7wTgu', u'created_at': u'Tue Feb 20 14:35:54 +0000 2007', u'contributors_enabled': False, u'time_zone': u'Pacific Time (US & Canada)', u'profile_sidebar_border_color': u'FFFFFF', u'default_profile': False, u'following': False, u'listed_count': 90445}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'possibly_sensitive_appealable': False, u'lang': u'en', u'created_at': u'Mon Sep 19 17:00:36 +0000 2016', u'in_reply_to_status_id_str': None, u'place': None, u'extended_entities': {u'media': [{u'expanded_url': u'https://twitter.com/twitter/status/777915304261193728/photo/1', u'display_url': u'pic.twitter.com/I9pUC0NdZC', u'url': u'https://t.co/I9pUC0NdZC', u'media_url_https': u'https://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg', u'video_info': {u'aspect_ratio': [1, 1], u'variants': [{u'url': u'https://pbs.twimg.com/tweet_video/Csu1TzEVMAAAEv7.mp4', u'bitrate': 0, u'content_type': u'video/mp4'}]}, u'id_str': u'777914712382058496', u'sizes': {u'small': {u'h': 340, u'w': 340, u'resize': u'fit'}, u'large': {u'h': 700, u'w': 700, u'resize': u'fit'}, u'medium': {u'h': 600, u'w': 600, u'resize': u'fit'}, u'thumb': {u'h': 150, u'w': 150, u'resize': u'crop'}}, u'indices': [140, 163], u'type': u'animated_gif', u'id': 777914712382058496, u'media_url': u'http://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg'}]}}
-test_tweet_extended_html = 'Say more about what\'s happening! Rolling out now: photos, videos, GIFs, polls, and Quote Tweets no longer count toward your 140 characters.'
diff --git a/tests/test_core.py b/tests/test_core.py
index c7cf2a20..4c215d4c 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,11 +1,7 @@
# -*- coding: utf-8 -*-
from twython import Twython, TwythonError, TwythonAuthError, TwythonRateLimitError
-from .config import (
- test_tweet_object, test_tweet_html, test_tweet_symbols_object,
- test_tweet_compat_object, test_tweet_extended_object, test_tweet_extended_html,
- unittest
-)
+from .config import unittest
import responses
import requests
@@ -302,38 +298,15 @@ def test_encode(self):
"""Test encoding UTF-8 works"""
self.api.encode('Twython is awesome!')
- def test_html_for_tweet(self):
- """Test HTML for Tweet returns what we want"""
- tweet_text = self.api.html_for_tweet(test_tweet_object)
- self.assertEqual(test_tweet_html, tweet_text)
-
- def test_html_for_tweet_expanded_url(self):
- """Test using expanded url in HTML for Tweet displays full urls"""
- tweet_text = self.api.html_for_tweet(test_tweet_object,
- use_expanded_url=True)
- # Make sure full url is in HTML
- self.assertTrue('http://google.com' in tweet_text)
-
- def test_html_for_tweet_short_url(self):
- """Test using expanded url in HTML for Tweet displays full urls"""
- tweet_text = self.api.html_for_tweet(test_tweet_object, False)
- # Make sure HTML doesn't contain the display OR expanded url
- self.assertTrue('http://google.com' not in tweet_text)
- self.assertTrue('google.com' not in tweet_text)
-
- def test_html_for_tweet_symbols(self):
- tweet_text = self.api.html_for_tweet(test_tweet_symbols_object)
- # Should only link symbols listed in entities:
- self.assertTrue('$AAPL' in tweet_text)
- self.assertTrue('$ANOTHER' not in tweet_text)
-
- def test_html_for_tweet_compatmode(self):
- tweet_text = self.api.html_for_tweet(test_tweet_compat_object)
- # link to compat web status link
- self.assertTrue(
- u'twitter.com/i/web/status/7…' in tweet_text)
-
- def test_html_for_tweet_extendedmode(self):
- tweet_text = self.api.html_for_tweet(test_tweet_extended_object)
- # full tweet rendered with suffix
- self.assertEqual(test_tweet_extended_html, tweet_text)
+ def test_cursor_requires_twython_function(self):
+ """Test that cursor() raises when called without a Twython function"""
+ def init_and_iterate_cursor(*args, **kwargs):
+ cursor = self.api.cursor(*args, **kwargs)
+ return next(cursor)
+
+ non_function = object()
+ non_twython_function = lambda x: x
+
+ self.assertRaises(TypeError, init_and_iterate_cursor, non_function)
+ self.assertRaises(TwythonError, init_and_iterate_cursor, non_twython_function)
+
diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py
index aa79998e..ecdd5537 100644
--- a/tests/test_endpoints.py
+++ b/tests/test_endpoints.py
@@ -4,7 +4,7 @@
app_key, app_secret, oauth_token, oauth_token_secret,
protected_twitter_1, protected_twitter_2, screen_name,
test_tweet_id, test_list_slug, test_list_owner_screen_name,
- access_token, test_tweet_object, test_tweet_html, unittest
+ access_token, unittest
)
import time
diff --git a/tests/test_html_for_tweet.py b/tests/test_html_for_tweet.py
new file mode 100644
index 00000000..921dfeeb
--- /dev/null
+++ b/tests/test_html_for_tweet.py
@@ -0,0 +1,130 @@
+# -*- coding: utf-8 -*-
+import json
+import os
+
+from twython import Twython, TwythonError
+
+from .config import unittest
+
+
+class TestHtmlForTweetTestCase(unittest.TestCase):
+ def setUp(self):
+ self.api = Twython('', '', '', '')
+
+ def load_tweet(self, name):
+ f = open(os.path.join(
+ os.path.dirname(__file__),
+ 'tweets',
+ '%s.json' % name
+ ))
+ tweet = json.load(f)
+ f.close()
+ return tweet
+
+ def test_basic(self):
+ """Test HTML for Tweet returns what we want"""
+ tweet_object = self.load_tweet('basic')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ self.assertEqual(tweet_text,
+ 'google.com is a #cool site, lol! @mikehelmick shd #checkitout. Love, @__twython__ github.com pic.twitter.com/N6InAO4B71')
+
+ def test_reply(self):
+ """Test HTML for Tweet links the replied-to username."""
+ tweet_object = self.load_tweet('reply')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ self.assertEqual(tweet_text,
+ u'Here’s a test tweet that goes on as much as possible and includes an image. Hi to my fans in testland!')
+
+ def test_expanded_url(self):
+ """Test using expanded url in HTML for Tweet displays full urls"""
+ tweet_object = self.load_tweet('basic')
+ tweet_text = self.api.html_for_tweet(tweet_object,
+ use_expanded_url=True)
+ # Make sure full url is in HTML
+ self.assertTrue('http://google.com' in tweet_text)
+
+ def test_short_url(self):
+ """Test using expanded url in HTML for Tweet displays full urls"""
+ tweet_object = self.load_tweet('basic')
+ tweet_text = self.api.html_for_tweet(tweet_object, False)
+ # Make sure HTML doesn't contain the display OR expanded url
+ self.assertTrue('http://google.com' not in tweet_text)
+ self.assertTrue('google.com' not in tweet_text)
+
+ def test_identical_urls(self):
+ """If the 'url's for different url entities are identical, they should link correctly."""
+ tweet_object = self.load_tweet('identical_urls')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ self.assertEqual(tweet_text,
+ u'Use Cases, Trials and Making 5G a Reality buff.ly/2sEhrgO #5G #innovation via @5GWorldSeries buff.ly/2sEhrgO')
+
+ def test_symbols(self):
+ tweet_object = self.load_tweet('symbols')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ # Should only link symbols listed in entities:
+ self.assertTrue('$AAPL' in tweet_text)
+ self.assertTrue('$ANOTHER' not in tweet_text)
+
+ def test_no_symbols(self):
+ """Should still work if tweet object has no symbols list"""
+ tweet = self.load_tweet('symbols')
+ # Save a copy:
+ symbols = tweet['entities']['symbols']
+ del tweet['entities']['symbols']
+ tweet_text = self.api.html_for_tweet(tweet)
+ self.assertTrue('symbols: $AAPL and' in tweet_text)
+ self.assertTrue('and $ANOTHER and $A.' in tweet_text)
+
+ def test_compatmode(self):
+ tweet_object = self.load_tweet('compat')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ # link to compat web status link
+ self.assertTrue(
+ u'twitter.com/i/web/status/7…' in tweet_text)
+
+ def test_extendedmode(self):
+ tweet_object = self.load_tweet('extended')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ # full tweet rendered with suffix
+ self.assertEqual(tweet_text,
+ 'Say more about what\'s happening! Rolling out now: photos, videos, GIFs, polls, and Quote Tweets no longer count toward your 140 characters.')
+
+ def test_entities_with_prefix(self):
+ """
+ If there is a username mention at the start of a tweet it's in the
+ "prefix" and so isn't part of the main tweet display text.
+ But its length is still counted in the indices of any subsequent
+ mentions, urls, hashtags, etc.
+ """
+ self.maxDiff = 2200
+ tweet_object = self.load_tweet('entities_with_prefix')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+ self.assertEqual(tweet_text,
+ u'This is a test for @visionphil that includes a link example.org and #hashtag and X for good measure AND that is longer than 140 characters. example.com')
+
+ def test_media(self):
+ tweet_object = self.load_tweet('media')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+
+ self.assertEqual(
+ u"""I made some D3.js charts showing the years covered by books in a series compared to their publishing dates gyford.com/phil/writing/2\u2026""",
+ tweet_text)
+
+ def test_quoted(self):
+ "With expand_quoted_status=True it should include a quoted tweet."
+ tweet_object = self.load_tweet('quoted')
+ tweet_text = self.api.html_for_tweet(tweet_object,
+ expand_quoted_status=True)
+ self.assertEqual(
+ u"""Here\u2019s a quoted tweet. twitter.com/philgyford/sta\u2026The quoted tweet text.Phil Gyford@philgyford
""",
+ tweet_text)
+
+ def test_retweet(self):
+ "With expand_quoted_status=True it should include a quoted tweet."
+ tweet_object = self.load_tweet('retweet')
+ tweet_text = self.api.html_for_tweet(tweet_object)
+
+ self.assertEqual(
+ u"""My aunt and uncle in a very ill humour one with another, but I made shift with much ado to keep them from scolding.""",
+ tweet_text)
+
diff --git a/tests/tweets/basic.json b/tests/tweets/basic.json
new file mode 100644
index 00000000..7243cd8c
--- /dev/null
+++ b/tests/tweets/basic.json
@@ -0,0 +1,170 @@
+{
+ "contributors":null,
+ "truncated":false,
+ "text":"http://t.co/FCmXyI6VHd is a #cool site, lol! @mikehelmick shd #checkitout. Love, @__twython__ https://t.co/67pwRvY6z9 http://t.co/N6InAO4B71",
+ "in_reply_to_status_id":null,
+ "id":349683012054683648,
+ "favorite_count":0,
+ "source":"Twitter Web Client",
+ "retweeted":false,
+ "coordinates":null,
+ "entities":{
+ "symbols":[
+
+ ],
+ "user_mentions":[
+ {
+ "id":29251354,
+ "indices":[
+ 45,
+ 57
+ ],
+ "id_str":"29251354",
+ "screen_name":"mikehelmick",
+ "name":"Mike Helmick"
+ },
+ {
+ "id":1431865928,
+ "indices":[
+ 81,
+ 93
+ ],
+ "id_str":"1431865928",
+ "screen_name":"__twython__",
+ "name":"Twython"
+ }
+ ],
+ "hashtags":[
+ {
+ "indices":[
+ 28,
+ 33
+ ],
+ "text":"cool"
+ },
+ {
+ "indices":[
+ 62,
+ 73
+ ],
+ "text":"checkitout"
+ }
+ ],
+ "urls":[
+ {
+ "url":"http://t.co/FCmXyI6VHd",
+ "indices":[
+ 0,
+ 22
+ ],
+ "expanded_url":"http://google.com",
+ "display_url":"google.com"
+ },
+ {
+ "url":"https://t.co/67pwRvY6z9",
+ "indices":[
+ 94,
+ 117
+ ],
+ "expanded_url":"https://github.com",
+ "display_url":"github.com"
+ }
+ ],
+ "media":[
+ {
+ "id":537884378513162240,
+ "id_str":"537884378513162240",
+ "indices":[
+ 118,
+ 140
+ ],
+ "media_url":"http://pbs.twimg.com/media/B3by_g-CQAAhrO5.jpg",
+ "media_url_https":"https://pbs.twimg.com/media/B3by_g-CQAAhrO5.jpg",
+ "url":"http://t.co/N6InAO4B71",
+ "display_url":"pic.twitter.com/N6InAO4B71",
+ "expanded_url":"http://twitter.com/pingofglitch/status/537884380060844032/photo/1",
+ "type":"photo",
+ "sizes":{
+ "large":{
+ "w":1024,
+ "h":640,
+ "resize":"fit"
+ },
+ "thumb":{
+ "w":150,
+ "h":150,
+ "resize":"crop"
+ },
+ "medium":{
+ "w":600,
+ "h":375,
+ "resize":"fit"
+ },
+ "small":{
+ "w":340,
+ "h":212,
+ "resize":"fit"
+ }
+ }
+ }
+ ]
+ },
+ "in_reply_to_screen_name":null,
+ "id_str":"349683012054683648",
+ "retweet_count":0,
+ "in_reply_to_user_id":null,
+ "favorited":false,
+ "user":{
+ "follow_request_sent":false,
+ "profile_use_background_image":true,
+ "default_profile_image":true,
+ "id":1431865928,
+ "verified":false,
+ "profile_text_color":"333333",
+ "profile_image_url_https":"https://si0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png",
+ "profile_sidebar_fill_color":"DDEEF6",
+ "entities":{
+ "description":{
+ "urls":[
+
+ ]
+ }
+ },
+ "followers_count":1,
+ "profile_sidebar_border_color":"C0DEED",
+ "id_str":"1431865928",
+ "profile_background_color":"3D3D3D",
+ "listed_count":0,
+ "profile_background_image_url_https":"https://si0.twimg.com/images/themes/theme1/bg.png",
+ "utc_offset":null,
+ "statuses_count":2,
+ "description":"",
+ "friends_count":1,
+ "location":"",
+ "profile_link_color":"0084B4",
+ "profile_image_url":"http://a0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png",
+ "following":false,
+ "geo_enabled":false,
+ "profile_background_image_url":"http://a0.twimg.com/images/themes/theme1/bg.png",
+ "screen_name":"__twython__",
+ "lang":"en",
+ "profile_background_tile":false,
+ "favourites_count":0,
+ "name":"Twython",
+ "notifications":false,
+ "url":null,
+ "created_at":"Thu May 16 01:11:09 +0000 2013",
+ "contributors_enabled":false,
+ "time_zone":null,
+ "protected":false,
+ "default_profile":false,
+ "is_translator":false
+ },
+ "geo":null,
+ "in_reply_to_user_id_str":null,
+ "possibly_sensitive":false,
+ "lang":"en",
+ "created_at":"Wed Jun 26 00:18:21 +0000 2013",
+ "in_reply_to_status_id_str":null,
+ "place":null
+}
diff --git a/tests/tweets/compat.json b/tests/tweets/compat.json
new file mode 100644
index 00000000..b01b358e
--- /dev/null
+++ b/tests/tweets/compat.json
@@ -0,0 +1,51 @@
+{
+ "contributors":null,
+ "truncated":true,
+ "text":"Say more about what's happening! Rolling out now: photos, videos, GIFs, polls, and Quote Tweets no longer count tow\u2026 https://t.co/SRmsuks2ru",
+ "is_quote_status":false,
+ "in_reply_to_status_id":null,
+ "id":777915304261193728,
+ "favorite_count":13856,
+ "source":"Twitter Web Client",
+ "retweeted":false,
+ "coordinates":null,
+ "entities":{
+ "symbols":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "hashtags":[
+
+ ],
+ "urls":[
+ {
+ "url":"https://t.co/SRmsuks2ru",
+ "indices":[
+ 117,
+ 140
+ ],
+ "expanded_url":"https://twitter.com/i/web/status/777915304261193728",
+ "display_url":"twitter.com/i/web/status/7\u2026"
+ }
+ ]
+ },
+ "in_reply_to_screen_name":null,
+ "id_str":"777915304261193728",
+ "retweet_count":14767,
+ "in_reply_to_user_id":null,
+ "favorited":false,
+ "user":{
+ "name":"Twitter",
+ "screen_name":"twitter"
+ },
+ "geo":null,
+ "in_reply_to_user_id_str":null,
+ "possibly_sensitive":false,
+ "possibly_sensitive_appealable":false,
+ "lang":"en",
+ "created_at":"Mon Sep 19 17:00:36 +0000 2016",
+ "in_reply_to_status_id_str":null,
+ "place":null
+}
diff --git a/tests/tweets/entities_with_prefix.json b/tests/tweets/entities_with_prefix.json
new file mode 100644
index 00000000..8ba89753
--- /dev/null
+++ b/tests/tweets/entities_with_prefix.json
@@ -0,0 +1,68 @@
+{
+ "created_at":"Sat Jan 06 18:56:35 +0000 2018",
+ "id":949716340755091458,
+ "id_str":"949716340755091458",
+ "full_text":"@philgyford This is a test for @visionphil that includes a link https://t.co/sKw4J3A8SZ and #hashtag and X for good measure AND that is longer than 140 characters. https://t.co/jnQdy7Zg7u",
+ "truncated":false,
+ "display_text_range":[ 12, 187 ],
+ "entities":{
+ "hashtags":[
+ {
+ "text":"hashtag",
+ "indices":[ 92, 100 ]
+ }
+ ],
+ "symbols":[ ],
+ "user_mentions":[
+ {
+ "screen_name":"philgyford",
+ "name":"Phil Gyford",
+ "id":12552,
+ "id_str":"12552",
+ "indices":[ 0, 11 ]
+ },
+ {
+ "screen_name":"visionphil",
+ "name":"Vision Phil",
+ "id":104456050,
+ "id_str":"104456050",
+ "indices":[ 31, 42 ]
+ }
+ ],
+ "urls":[
+ {
+ "url":"https://t.co/sKw4J3A8SZ",
+ "expanded_url":"http://example.org",
+ "display_url":"example.org",
+ "indices":[ 64, 87 ]
+ },
+ {
+ "url":"https://t.co/jnQdy7Zg7u",
+ "expanded_url":"http://example.com",
+ "display_url":"example.com",
+ "indices":[ 164, 187 ]
+ }
+ ]
+ },
+ "source":"Tweetbot for Mac",
+ "in_reply_to_status_id":948561036889722880,
+ "in_reply_to_status_id_str":"948561036889722880",
+ "in_reply_to_user_id":12552,
+ "in_reply_to_user_id_str":"12552",
+ "in_reply_to_screen_name":"philgyford",
+ "user":{
+ "id":2030131,
+ "id_str":"2030131"
+ },
+ "geo":null,
+ "coordinates":null,
+ "place":null,
+ "contributors":null,
+ "is_quote_status":false,
+ "retweet_count":0,
+ "favorite_count":0,
+ "favorited":false,
+ "retweeted":false,
+ "possibly_sensitive":false,
+ "lang":"en"
+}
diff --git a/tests/tweets/extended.json b/tests/tweets/extended.json
new file mode 100644
index 00000000..105700af
--- /dev/null
+++ b/tests/tweets/extended.json
@@ -0,0 +1,204 @@
+{
+ "full_text":"Say more about what's happening! Rolling out now: photos, videos, GIFs, polls, and Quote Tweets no longer count toward your 140 characters. https://t.co/I9pUC0NdZC",
+ "truncated":false,
+ "is_quote_status":false,
+ "in_reply_to_status_id":null,
+ "id":777915304261193728,
+ "favorite_count":13856,
+ "contributors":null,
+ "source":"Twitter Web Client",
+ "retweeted":false,
+ "coordinates":null,
+ "entities":{
+ "symbols":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "hashtags":[
+
+ ],
+ "urls":[
+
+ ],
+ "media":[
+ {
+ "expanded_url":"https://twitter.com/twitter/status/777915304261193728/photo/1",
+ "sizes":{
+ "small":{
+ "h":340,
+ "w":340,
+ "resize":"fit"
+ },
+ "large":{
+ "h":700,
+ "w":700,
+ "resize":"fit"
+ },
+ "medium":{
+ "h":600,
+ "w":600,
+ "resize":"fit"
+ },
+ "thumb":{
+ "h":150,
+ "w":150,
+ "resize":"crop"
+ }
+ },
+ "url":"https://t.co/I9pUC0NdZC",
+ "media_url_https":"https://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg",
+ "id_str":"777914712382058496",
+ "indices":[
+ 140,
+ 163
+ ],
+ "media_url":"http://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg",
+ "type":"photo",
+ "id":777914712382058496,
+ "display_url":"pic.twitter.com/I9pUC0NdZC"
+ }
+ ]
+ },
+ "in_reply_to_screen_name":null,
+ "id_str":"777915304261193728",
+ "display_text_range":[
+ 0,
+ 139
+ ],
+ "retweet_count":14767,
+ "in_reply_to_user_id":null,
+ "favorited":false,
+ "user":{
+ "follow_request_sent":false,
+ "has_extended_profile":false,
+ "profile_use_background_image":true,
+ "id":783214,
+ "verified":true,
+ "profile_text_color":"333333",
+ "profile_image_url_https":"https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg",
+ "profile_sidebar_fill_color":"F6F6F6",
+ "is_translator":false,
+ "geo_enabled":true,
+ "entities":{
+ "url":{
+ "urls":[
+ {
+ "url":"http://t.co/5iRhy7wTgu",
+ "indices":[
+ 0,
+ 22
+ ],
+ "expanded_url":"http://blog.twitter.com/",
+ "display_url":"blog.twitter.com"
+ }
+ ]
+ },
+ "description":{
+ "urls":[
+ {
+ "url":"https://t.co/qq1HEzvnrA",
+ "indices":[
+ 84,
+ 107
+ ],
+ "expanded_url":"http://support.twitter.com",
+ "display_url":"support.twitter.com"
+ }
+ ]
+ }
+ },
+ "followers_count":56827498,
+ "protected":false,
+ "location":"San Francisco, CA",
+ "default_profile_image":false,
+ "id_str":"783214",
+ "lang":"en",
+ "utc_offset":-25200,
+ "statuses_count":3161,
+ "description":"Your official source for news, updates and tips from Twitter, Inc. Need help? Visit https://t.co/qq1HEzvnrA.",
+ "friends_count":145,
+ "profile_link_color":"226699",
+ "profile_image_url":"http://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I_normal.jpg",
+ "notifications":false,
+ "profile_background_image_url_https":"https://pbs.twimg.com/profile_background_images/657090062/l1uqey5sy82r9ijhke1i.png",
+ "profile_background_color":"ACDED6",
+ "profile_banner_url":"https://pbs.twimg.com/profile_banners/783214/1471929200",
+ "profile_background_image_url":"http://pbs.twimg.com/profile_background_images/657090062/l1uqey5sy82r9ijhke1i.png",
+ "name":"Twitter",
+ "is_translation_enabled":false,
+ "profile_background_tile":true,
+ "favourites_count":2332,
+ "screen_name":"twitter",
+ "url":"http://t.co/5iRhy7wTgu",
+ "created_at":"Tue Feb 20 14:35:54 +0000 2007",
+ "contributors_enabled":false,
+ "time_zone":"Pacific Time (US & Canada)",
+ "profile_sidebar_border_color":"FFFFFF",
+ "default_profile":false,
+ "following":false,
+ "listed_count":90445
+ },
+ "geo":null,
+ "in_reply_to_user_id_str":null,
+ "possibly_sensitive":false,
+ "possibly_sensitive_appealable":false,
+ "lang":"en",
+ "created_at":"Mon Sep 19 17:00:36 +0000 2016",
+ "in_reply_to_status_id_str":null,
+ "place":null,
+ "extended_entities":{
+ "media":[
+ {
+ "expanded_url":"https://twitter.com/twitter/status/777915304261193728/photo/1",
+ "display_url":"pic.twitter.com/I9pUC0NdZC",
+ "url":"https://t.co/I9pUC0NdZC",
+ "media_url_https":"https://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg",
+ "video_info":{
+ "aspect_ratio":[
+ 1,
+ 1
+ ],
+ "variants":[
+ {
+ "url":"https://pbs.twimg.com/tweet_video/Csu1TzEVMAAAEv7.mp4",
+ "bitrate":0,
+ "content_type":"video/mp4"
+ }
+ ]
+ },
+ "id_str":"777914712382058496",
+ "sizes":{
+ "small":{
+ "h":340,
+ "w":340,
+ "resize":"fit"
+ },
+ "large":{
+ "h":700,
+ "w":700,
+ "resize":"fit"
+ },
+ "medium":{
+ "h":600,
+ "w":600,
+ "resize":"fit"
+ },
+ "thumb":{
+ "h":150,
+ "w":150,
+ "resize":"crop"
+ }
+ },
+ "indices":[
+ 140,
+ 163
+ ],
+ "type":"animated_gif",
+ "id":777914712382058496,
+ "media_url":"http://pbs.twimg.com/tweet_video_thumb/Csu1TzEVMAAAEv7.jpg"
+ }
+ ]
+ }
+}
diff --git a/tests/tweets/identical_urls.json b/tests/tweets/identical_urls.json
new file mode 100644
index 00000000..69840f9f
--- /dev/null
+++ b/tests/tweets/identical_urls.json
@@ -0,0 +1,34 @@
+{
+ "entities":{
+ "hashtags":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "symbols":[
+
+ ],
+ "urls":[
+ {
+ "display_url":"buff.ly/2sEhrgO",
+ "expanded_url":"http://buff.ly/2sEhrgO",
+ "indices":[
+ 42,
+ 65
+ ],
+ "url":"https://t.co/W0uArTMk9N"
+ },
+ {
+ "display_url":"buff.ly/2sEhrgO",
+ "expanded_url":"http://buff.ly/2sEhrgO",
+ "indices":[
+ 101,
+ 124
+ ],
+ "url":"https://t.co/W0uArTMk9N"
+ }
+ ]
+ },
+ "full_text":"Use Cases, Trials and Making 5G a Reality https://t.co/W0uArTMk9N #5G #innovation via @5GWorldSeries https://t.co/W0uArTMk9N"
+}
diff --git a/tests/tweets/media.json b/tests/tweets/media.json
new file mode 100644
index 00000000..4366794d
--- /dev/null
+++ b/tests/tweets/media.json
@@ -0,0 +1,205 @@
+{
+ "contributors":null,
+ "truncated":false,
+ "is_quote_status":false,
+ "in_reply_to_status_id":null,
+ "id":905105588279013377,
+ "favorite_count":10,
+ "full_text":"I made some D3.js charts showing the years covered by books in a series compared to their publishing dates https://t.co/2yUmmn3TOc https://t.co/OwNc6uJklg",
+ "source":"Twitter Web Client",
+ "retweeted":false,
+ "coordinates":null,
+ "entities":{
+ "symbols":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "hashtags":[
+
+ ],
+ "urls":[
+ {
+ "url":"https://t.co/2yUmmn3TOc",
+ "indices":[
+ 107,
+ 130
+ ],
+ "expanded_url":"http://www.gyford.com/phil/writing/2017/09/05/book-series-charts.php",
+ "display_url":"gyford.com/phil/writing/2\u2026"
+ }
+ ],
+ "media":[
+ {
+ "expanded_url":"https://twitter.com/philgyford/status/905105588279013377/photo/1",
+ "display_url":"pic.twitter.com/OwNc6uJklg",
+ "url":"https://t.co/OwNc6uJklg",
+ "media_url_https":"https://pbs.twimg.com/media/DI-UuNlWAAA_cvz.jpg",
+ "id_str":"905105571765944320",
+ "sizes":{
+ "small":{
+ "h":256,
+ "resize":"fit",
+ "w":680
+ },
+ "large":{
+ "h":376,
+ "resize":"fit",
+ "w":1000
+ },
+ "medium":{
+ "h":376,
+ "resize":"fit",
+ "w":1000
+ },
+ "thumb":{
+ "h":150,
+ "resize":"crop",
+ "w":150
+ }
+ },
+ "indices":[
+ 131,
+ 154
+ ],
+ "type":"photo",
+ "id":905105571765944320,
+ "media_url":"http://pbs.twimg.com/media/DI-UuNlWAAA_cvz.jpg"
+ }
+ ]
+ },
+ "in_reply_to_screen_name":null,
+ "in_reply_to_user_id":null,
+ "display_text_range":[
+ 0,
+ 130
+ ],
+ "retweet_count":1,
+ "id_str":"905105588279013377",
+ "favorited":false,
+ "user":{
+ "screen_name":"philgyford",
+ "name":"Phil Gyford"
+ },
+ "geo":null,
+ "in_reply_to_user_id_str":null,
+ "possibly_sensitive":false,
+ "possibly_sensitive_appealable":false,
+ "lang":"en",
+ "created_at":"Tue Sep 05 16:29:22 +0000 2017",
+ "in_reply_to_status_id_str":null,
+ "place":null,
+ "extended_entities":{
+ "media":[
+ {
+ "expanded_url":"https://twitter.com/philgyford/status/905105588279013377/photo/1",
+ "display_url":"pic.twitter.com/OwNc6uJklg",
+ "url":"https://t.co/OwNc6uJklg",
+ "media_url_https":"https://pbs.twimg.com/media/DI-UuNlWAAA_cvz.jpg",
+ "id_str":"905105571765944320",
+ "sizes":{
+ "small":{
+ "h":256,
+ "resize":"fit",
+ "w":680
+ },
+ "large":{
+ "h":376,
+ "resize":"fit",
+ "w":1000
+ },
+ "medium":{
+ "h":376,
+ "resize":"fit",
+ "w":1000
+ },
+ "thumb":{
+ "h":150,
+ "resize":"crop",
+ "w":150
+ }
+ },
+ "indices":[
+ 131,
+ 154
+ ],
+ "type":"photo",
+ "id":905105571765944320,
+ "media_url":"http://pbs.twimg.com/media/DI-UuNlWAAA_cvz.jpg"
+ },
+ {
+ "expanded_url":"https://twitter.com/philgyford/status/905105588279013377/photo/1",
+ "display_url":"pic.twitter.com/OwNc6uJklg",
+ "url":"https://t.co/OwNc6uJklg",
+ "media_url_https":"https://pbs.twimg.com/media/DI-UuQbXUAQ1WlR.jpg",
+ "id_str":"905105572529393668",
+ "sizes":{
+ "large":{
+ "h":399,
+ "resize":"fit",
+ "w":1000
+ },
+ "small":{
+ "h":271,
+ "resize":"fit",
+ "w":680
+ },
+ "medium":{
+ "h":399,
+ "resize":"fit",
+ "w":1000
+ },
+ "thumb":{
+ "h":150,
+ "resize":"crop",
+ "w":150
+ }
+ },
+ "indices":[
+ 131,
+ 154
+ ],
+ "type":"photo",
+ "id":905105572529393668,
+ "media_url":"http://pbs.twimg.com/media/DI-UuQbXUAQ1WlR.jpg"
+ },
+ {
+ "expanded_url":"https://twitter.com/philgyford/status/905105588279013377/photo/1",
+ "display_url":"pic.twitter.com/OwNc6uJklg",
+ "url":"https://t.co/OwNc6uJklg",
+ "media_url_https":"https://pbs.twimg.com/media/DI-UuTIXcAA-t1_.jpg",
+ "id_str":"905105573255016448",
+ "sizes":{
+ "small":{
+ "h":195,
+ "resize":"fit",
+ "w":680
+ },
+ "large":{
+ "h":287,
+ "resize":"fit",
+ "w":1000
+ },
+ "medium":{
+ "h":287,
+ "resize":"fit",
+ "w":1000
+ },
+ "thumb":{
+ "h":150,
+ "resize":"crop",
+ "w":150
+ }
+ },
+ "indices":[
+ 131,
+ 154
+ ],
+ "type":"photo",
+ "id":905105573255016448,
+ "media_url":"http://pbs.twimg.com/media/DI-UuTIXcAA-t1_.jpg"
+ }
+ ]
+ }
+}
diff --git a/tests/tweets/quoted.json b/tests/tweets/quoted.json
new file mode 100644
index 00000000..c8e372bd
--- /dev/null
+++ b/tests/tweets/quoted.json
@@ -0,0 +1,94 @@
+{
+ "contributors":null,
+ "truncated":false,
+ "text":"Here\u2019s a quoted tweet. https://t.co/3neKzof0gT",
+ "is_quote_status":true,
+ "in_reply_to_status_id":null,
+ "id":917706313785905157,
+ "favorite_count":0,
+ "source":"Twitter Web Client",
+ "quoted_status_id":917699069916729344,
+ "retweeted":false,
+ "coordinates":null,
+ "quoted_status":{
+ "contributors":null,
+ "truncated":false,
+ "text":"The quoted tweet text.",
+ "is_quote_status":false,
+ "in_reply_to_status_id":null,
+ "id":917699069916729344,
+ "favorite_count":1,
+ "source":"Twitter Web Client",
+ "retweeted":false,
+ "coordinates":null,
+ "entities":{
+ "symbols":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "hashtags":[
+
+ ],
+ "urls":[
+
+ ]
+ },
+ "in_reply_to_screen_name":null,
+ "in_reply_to_user_id":null,
+ "retweet_count":0,
+ "id_str":"917699069916729344",
+ "favorited":false,
+ "user":{
+ "screen_name":"philgyford",
+ "name":"Phil Gyford"
+ },
+ "geo":null,
+ "in_reply_to_user_id_str":null,
+ "lang":"ht",
+ "created_at":"Tue Oct 10 10:31:22 +0000 2017",
+ "in_reply_to_status_id_str":null,
+ "place":null
+ },
+ "entities":{
+ "symbols":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "hashtags":[
+
+ ],
+ "urls":[
+ {
+ "url":"https://t.co/3neKzof0gT",
+ "indices":[
+ 23,
+ 46
+ ],
+ "expanded_url":"https://twitter.com/philgyford/status/917699069916729344",
+ "display_url":"twitter.com/philgyford/sta\u2026"
+ }
+ ]
+ },
+ "in_reply_to_screen_name":null,
+ "in_reply_to_user_id":null,
+ "retweet_count":0,
+ "id_str":"917706313785905157",
+ "favorited":false,
+ "user":{
+ "screen_name":"philgyfordtest",
+ "name":"Phil Gyford Test"
+ },
+ "geo":null,
+ "in_reply_to_user_id_str":null,
+ "possibly_sensitive":false,
+ "possibly_sensitive_appealable":false,
+ "lang":"en",
+ "created_at":"Tue Oct 10 11:00:10 +0000 2017",
+ "quoted_status_id_str":"917699069916729344",
+ "in_reply_to_status_id_str":null,
+ "place":null
+}
diff --git a/tests/tweets/reply.json b/tests/tweets/reply.json
new file mode 100644
index 00000000..2a227125
--- /dev/null
+++ b/tests/tweets/reply.json
@@ -0,0 +1,62 @@
+{
+ "display_text_range":[
+ 12,
+ 114
+ ],
+ "in_reply_to_status_id_str":"742374355531923456",
+ "source":"Twitter Web Client",
+ "geo":null,
+ "full_text":"@philgyford Here\u2019s a test tweet that goes on as much as possible and includes an image. Hi to my fans in testland! https://t.co/tzhyk2QWSr",
+ "extended_entities":{
+ "media":[
+
+ ]
+ },
+ "id_str":"300",
+ "in_reply_to_status_id":742374355531923456,
+ "id":300,
+ "in_reply_to_screen_name":"philgyford",
+ "retweet_count":0,
+ "user":{
+
+ },
+ "created_at":"Mon Jun 13 15:48:06 +0000 2016",
+ "lang":"en",
+ "favorite_count":0,
+ "coordinates":null,
+ "place":null,
+ "contributors":null,
+ "in_reply_to_user_id":12552,
+ "in_reply_to_user_id_str":"12552",
+ "retweeted":false,
+ "favorited":false,
+ "truncated":false,
+ "entities":{
+ "user_mentions":[
+ {
+ "id_str":"12552",
+ "id":12552,
+ "screen_name":"philgyford",
+ "name":"Phil Gyford",
+ "indices":[
+ 0,
+ 11
+ ]
+ }
+ ],
+ "media":[
+
+ ],
+ "hashtags":[
+
+ ],
+ "symbols":[
+
+ ],
+ "urls":[
+
+ ]
+ },
+ "is_quote_status":false,
+ "possibly_sensitive":false
+}
diff --git a/tests/tweets/retweet.json b/tests/tweets/retweet.json
new file mode 100644
index 00000000..046bb648
--- /dev/null
+++ b/tests/tweets/retweet.json
@@ -0,0 +1,91 @@
+{
+ "coordinates":null,
+ "source":"web",
+ "in_reply_to_user_id_str":null,
+ "truncated":false,
+ "in_reply_to_user_id":null,
+ "favorite_count":0,
+ "user":{
+ "name":"Phil Gyford Test",
+ "screen_name":"philgyfordtest"
+ },
+ "favorited":false,
+ "retweeted_status":{
+ "coordinates":null,
+ "source":"Twitter Web Client",
+ "in_reply_to_user_id_str":null,
+ "truncated":false,
+ "in_reply_to_user_id":null,
+ "favorite_count":21,
+ "user":{
+ "name":"Samuel Pepys",
+ "screen_name":"samuelpepys"
+ },
+ "favorited":false,
+ "id":917459832885653506,
+ "contributors":null,
+ "in_reply_to_screen_name":null,
+ "geo":null,
+ "in_reply_to_status_id_str":null,
+ "id_str":"917459832885653506",
+ "entities":{
+ "hashtags":[
+
+ ],
+ "symbols":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "urls":[
+
+ ]
+ },
+ "in_reply_to_status_id":null,
+ "text":"My aunt and uncle in a very ill humour one with another, but I made shift with much ado to keep them from scolding.",
+ "retweet_count":3,
+ "place":null,
+ "lang":"en",
+ "created_at":"Mon Oct 09 18:40:44 +0000 2017",
+ "is_quote_status":false,
+ "retweeted":false
+ },
+ "id":917712989649801216,
+ "contributors":null,
+ "in_reply_to_screen_name":null,
+ "geo":null,
+ "in_reply_to_status_id_str":null,
+ "id_str":"917712989649801216",
+ "entities":{
+ "hashtags":[
+
+ ],
+ "symbols":[
+
+ ],
+ "user_mentions":[
+ {
+ "id_str":"14475268",
+ "indices":[
+ 3,
+ 15
+ ],
+ "name":"Samuel Pepys",
+ "id":14475268,
+ "screen_name":"samuelpepys"
+ }
+ ],
+ "urls":[
+
+ ]
+ },
+ "in_reply_to_status_id":null,
+ "text":"RT @samuelpepys: My aunt and uncle in a very ill humour one with another, but I made shift with much ado to keep them from scolding.",
+ "retweet_count":3,
+ "place":null,
+ "lang":"en",
+ "created_at":"Tue Oct 10 11:26:41 +0000 2017",
+ "is_quote_status":false,
+ "retweeted":false
+}
diff --git a/tests/tweets/symbols.json b/tests/tweets/symbols.json
new file mode 100644
index 00000000..7519a081
--- /dev/null
+++ b/tests/tweets/symbols.json
@@ -0,0 +1,61 @@
+{
+ "text":"Some symbols: $AAPL and $PEP and $ANOTHER and $A.",
+ "contributors":null,
+ "geo":null,
+ "favorited":true,
+ "in_reply_to_user_id_str":null,
+ "user":{
+ "screen_name":"philgyfordtest",
+ "name":"Phil Gyford Test"
+ },
+ "in_reply_to_user_id":null,
+ "retweeted":false,
+ "coordinates":null,
+ "place":null,
+ "in_reply_to_status_id":null,
+ "lang":"en",
+ "in_reply_to_status_id_str":null,
+ "truncated":false,
+ "retweet_count":0,
+ "is_quote_status":false,
+ "id":662694880657989632,
+ "id_str":"662694880657989632",
+ "in_reply_to_screen_name":null,
+ "favorite_count":1,
+ "entities":{
+ "hashtags":[
+
+ ],
+ "user_mentions":[
+
+ ],
+ "symbols":[
+ {
+ "indices":[
+ 14,
+ 19
+ ],
+ "text":"AAPL"
+ },
+ {
+ "indices":[
+ 24,
+ 28
+ ],
+ "text":"PEP"
+ },
+ {
+ "indices":[
+ 46,
+ 48
+ ],
+ "text":"A"
+ }
+ ],
+ "urls":[
+
+ ]
+ },
+ "created_at":"Fri Nov 06 18:15:46 +0000 2015",
+ "source":"Twitter Web Client"
+}
diff --git a/twython/__init__.py b/twython/__init__.py
index 1e57ceef..7d25ef32 100644
--- a/twython/__init__.py
+++ b/twython/__init__.py
@@ -19,7 +19,7 @@
"""
__author__ = 'Ryan McGrath '
-__version__ = '3.4.0'
+__version__ = '3.9.1'
from .api import Twython
from .streaming import TwythonStreamer
diff --git a/twython/advisory.py b/twython/advisory.py
index 31657ee6..9a0863a8 100644
--- a/twython/advisory.py
+++ b/twython/advisory.py
@@ -17,6 +17,6 @@
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
- so we want to specifcally bubble up ONLY Twython Deprecation Warnings
+ so we want to specifically bubble up ONLY Twython Deprecation Warnings
"""
pass
diff --git a/twython/api.py b/twython/api.py
index f806cea9..1e786ad5 100644
--- a/twython/api.py
+++ b/twython/api.py
@@ -9,6 +9,7 @@
dealing with the Twitter API
"""
+from __future__ import generator_stop
import warnings
import re
@@ -19,6 +20,7 @@
from . import __version__
from .advisory import TwythonDeprecationWarning
from .compat import json, urlencode, parse_qsl, quote_plus, str, is_py2
+from .compat import urlsplit
from .endpoints import EndpointsMixin
from .exceptions import TwythonError, TwythonAuthError, TwythonRateLimitError
from .helpers import _transparent_params
@@ -134,13 +136,17 @@ def __init__(self, app_key=None, app_secret=None, oauth_token=None,
def __repr__(self):
return '' % (self.app_key)
- def _request(self, url, method='GET', params=None, api_call=None):
+ def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False):
"""Internal request method"""
method = method.lower()
params = params or {}
func = getattr(self.client, method)
- params, files = _transparent_params(params)
+ if isinstance(params, dict) and json_encoded is False:
+ params, files = _transparent_params(params)
+ else:
+ params = params
+ files = list()
requests_args = {}
for k, v in self.client_args.items():
@@ -148,11 +154,16 @@ def _request(self, url, method='GET', params=None, api_call=None):
if k in ('timeout', 'allow_redirects', 'stream', 'verify'):
requests_args[k] = v
- if method == 'get':
+ if method == 'get' or method == 'delete':
requests_args['params'] = params
else:
+ # Check for json_encoded so we will sent params as "data" or "json"
+ if json_encoded:
+ data_key = 'json'
+ else:
+ data_key = 'data'
requests_args.update({
- 'data': params,
+ data_key: params,
'files': files,
})
try:
@@ -192,15 +203,16 @@ def _request(self, url, method='GET', params=None, api_call=None):
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:
- raise TwythonError('Response was not valid JSON. \
- Unable to decode.')
+ if response.content != '':
+ raise TwythonError('Response was not valid JSON. \
+ Unable to decode.')
return content
@@ -224,14 +236,14 @@ def _get_error_message(self, response):
return error_message
- def request(self, endpoint, method='GET', params=None, version='1.1'):
+ def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False):
"""Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
- GET or POST. (default GET)
+ GET, POST or DELETE. (default GET)
:type method: string
:param params: (optional) Dict of parameters (if any) accepted
the by Twitter API endpoint you are trying to
@@ -240,6 +252,9 @@ def request(self, endpoint, method='GET', params=None, version='1.1'):
:param version: (optional) Twitter API version to access
(default 1.1)
:type version: string
+ :param json_encoded: (optional) Flag to indicate if this method should send data encoded as json
+ (default False)
+ :type json_encoded: bool
:rtype: dict
"""
@@ -255,7 +270,7 @@ def request(self, endpoint, method='GET', params=None, version='1.1'):
url = '%s/%s.json' % (self.api_url % version, endpoint)
content = self._request(url, method=method, params=params,
- api_call=url)
+ api_call=url, json_encoded=json_encoded)
return content
@@ -263,9 +278,13 @@ def get(self, endpoint, params=None, version='1.1'):
"""Shortcut for GET requests via :class:`request`"""
return self.request(endpoint, params=params, version=version)
- def post(self, endpoint, params=None, version='1.1'):
+ def post(self, endpoint, params=None, version='1.1', json_encoded=False):
"""Shortcut for POST requests via :class:`request`"""
- return self.request(endpoint, 'POST', params=params, version=version)
+ return self.request(endpoint, 'POST', params=params, version=version, json_encoded=json_encoded)
+
+ def delete(self, endpoint, params=None, version='1.1', json_encoded=False):
+ """Shortcut for delete requests via :class:`request`"""
+ return self.request(endpoint, 'DELETE', params=params, version=version, json_encoded=json_encoded)
def get_lastfunction_header(self, header, default_return_value=None):
"""Returns a specific header from the last API call
@@ -412,7 +431,7 @@ def obtain_access_token(self):
@staticmethod
def construct_api_url(api_url, **params):
- """Construct a Twitter API url, encoded, with parameters
+ r"""Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
@@ -451,7 +470,7 @@ def search_gen(self, search_query, **params): # pragma: no cover
return self.cursor(self.search, q=search_query, **params)
def cursor(self, function, return_pages=False, **params):
- """Returns a generator for results that match a specified query.
+ r"""Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
@@ -470,6 +489,11 @@ def cursor(self, function, return_pages=False, **params):
>>> print result
"""
+ if not callable(function):
+ raise TypeError('.cursor() takes a Twython function as its first \
+ argument. Did you provide the result of a \
+ function call?')
+
if not hasattr(function, 'iter_mode'):
raise TwythonError('Unable to create generator for Twython \
method "%s"' % function.__name__)
@@ -478,7 +502,7 @@ def cursor(self, function, return_pages=False, **params):
content = function(**params)
if not content:
- raise StopIteration
+ return
if hasattr(function, 'iter_key'):
results = content.get(function.iter_key)
@@ -493,23 +517,31 @@ def cursor(self, function, return_pages=False, **params):
if function.iter_mode == 'cursor' and \
content['next_cursor_str'] == '0':
- raise StopIteration
+ return
try:
if function.iter_mode == 'id':
- if 'max_id' not in params:
- # Add 1 to the id because since_id and
- # max_id are inclusive
- if hasattr(function, 'iter_metadata'):
- since_id = content[function.iter_metadata].get('since_id_str')
+ # Set max_id in params to one less than lowest tweet id
+ if hasattr(function, 'iter_metadata'):
+ # Get supplied next max_id
+ metadata = content.get(function.iter_metadata)
+ if 'next_results' in metadata:
+ next_results = urlsplit(metadata['next_results'])
+ params = dict(parse_qsl(next_results.query))
else:
- since_id = content[0]['id_str']
- params['since_id'] = (int(since_id) - 1)
+ # No more results
+ return
+ else:
+ # Twitter gives tweets in reverse chronological order:
+ params['max_id'] = str(int(content[-1]['id_str']) - 1)
elif function.iter_mode == 'cursor':
params['cursor'] = content['next_cursor_str']
except (TypeError, ValueError): # pragma: no cover
raise TwythonError('Unable to generate next page of search \
results, `page` is not a number.')
+ except (KeyError, AttributeError): #pragma no cover
+ raise TwythonError('Unable to generate next page of search \
+ results, content has unexpected structure.')
@staticmethod
def unicode2utf8(text):
@@ -556,74 +588,105 @@ def html_for_tweet(tweet, use_display_url=True, use_expanded_url=False, expand_q
suffix_text = orig_tweet_text[display_text_end:len(orig_tweet_text)]
if 'entities' in tweet:
- entities = tweet['entities']
+ # We'll put all the bits of replacement HTML and their starts/ends
+ # in this list:
+ entities = []
# Mentions
- for entity in sorted(entities['user_mentions'],
- key=lambda mention: len(mention['screen_name']), reverse=True):
- start, end = entity['indices'][0], entity['indices'][1]
-
- mention_html = '@%(screen_name)s' % {'screen_name': entity['screen_name']}
- sub_expr = r'(?)' + orig_tweet_text[start:end] + '(?!)'
- if display_text_start <= start <= display_text_end:
- display_text = re.sub(sub_expr, mention_html, display_text)
- else:
- prefix_text = re.sub(sub_expr, mention_html, prefix_text)
+ if 'user_mentions' in tweet['entities']:
+ for entity in tweet['entities']['user_mentions']:
+ temp = {}
+ temp['start'] = entity['indices'][0]
+ temp['end'] = entity['indices'][1]
+
+ mention_html = '@%(screen_name)s' % {'screen_name': entity['screen_name']}
+
+ if display_text_start <= temp['start'] <= display_text_end:
+ temp['replacement'] = mention_html
+ temp['start'] -= display_text_start
+ temp['end'] -= display_text_start
+ entities.append(temp)
+ else:
+ # Make the '@username' at the start, before
+ # display_text, into a link:
+ sub_expr = r'(?)' + orig_tweet_text[temp['start']:temp['end']] + '(?!)'
+ prefix_text = re.sub(sub_expr, mention_html, prefix_text)
# Hashtags
- for entity in sorted(entities['hashtags'],
- key=lambda hashtag: len(hashtag['text']), reverse=True):
- start, end = entity['indices'][0], entity['indices'][1]
+ if 'hashtags' in tweet['entities']:
+ for entity in tweet['entities']['hashtags']:
+ temp = {}
+ temp['start'] = entity['indices'][0] - display_text_start
+ temp['end'] = entity['indices'][1] - display_text_start
+
+ url_html = '#%(hashtag)s' % {'hashtag': entity['text']}
- hashtag_html = '#%(hashtag)s'
- display_text = re.sub(r'(?)' + orig_tweet_text[start:end] + '(?!)',
- hashtag_html % {'hashtag': entity['text']}, display_text)
+ temp['replacement'] = url_html
+ entities.append(temp)
# Symbols
- for entity in sorted(entities['symbols'],
- key=lambda symbol: len(symbol['text']), reverse=True):
- start, end = entity['indices'][0], entity['indices'][1]
-
- symbol_html = '$%(symbol)s'
- display_text = re.sub(r'(?)' + re.escape(orig_tweet_text[start:end]) + r'\b(?!)',
- symbol_html % {'symbol': entity['text']}, display_text)
-
- # Urls
- for entity in entities['urls']:
- start, end = entity['indices'][0], entity['indices'][1]
- if use_display_url and entity.get('display_url') \
- and not use_expanded_url:
- shown_url = entity['display_url']
- elif use_expanded_url and entity.get('expanded_url'):
- shown_url = entity['expanded_url']
- else:
- shown_url = entity['url']
+ if 'symbols' in tweet['entities']:
+ for entity in tweet['entities']['symbols']:
+ temp = {}
+ temp['start'] = entity['indices'][0] - display_text_start
+ temp['end'] = entity['indices'][1] - display_text_start
- url_html = '%s' % (entity['url'], shown_url)
- if display_text_start <= start <= display_text_end:
- display_text = display_text.replace(orig_tweet_text[start:end], url_html)
- else:
- suffix_text = suffix_text.replace(orig_tweet_text[start:end], url_html)
-
- # Media
- if 'media' in entities:
- for entity in entities['media']:
- start, end = entity['indices'][0], entity['indices'][1]
- if use_display_url and entity.get('display_url') \
- and not use_expanded_url:
+ url_html = '$%(symbol)s' % {'symbol': entity['text']}
+
+ temp['replacement'] = url_html
+ entities.append(temp)
+
+ # URLs
+ if 'urls' in tweet['entities']:
+ for entity in tweet['entities']['urls']:
+ temp = {}
+ temp['start'] = entity['indices'][0] - display_text_start
+ temp['end'] = entity['indices'][1] - display_text_start
+
+ if use_display_url and entity.get('display_url') and not use_expanded_url:
shown_url = entity['display_url']
elif use_expanded_url and entity.get('expanded_url'):
shown_url = entity['expanded_url']
else:
shown_url = entity['url']
- url_html = '%s' % (entity['url'], shown_url)
- if display_text_start <= start <= display_text_end:
- # for compatibility with pre-extended tweets
- display_text = display_text.replace(orig_tweet_text[start:end], url_html)
+ url_html = '%s' % (entity['url'], shown_url)
+
+ if display_text_start <= temp['start'] <= display_text_end:
+ temp['replacement'] = url_html
+ entities.append(temp)
else:
- suffix_text = suffix_text.replace(orig_tweet_text[start:end], url_html)
+ suffix_text = suffix_text.replace(orig_tweet_text[temp['start']:temp['end']], url_html)
+
+ if 'media' in tweet['entities'] and len(tweet['entities']['media']) > 0:
+ # We just link to the overall URL for the tweet's media,
+ # rather than to each individual item.
+ # So, we get the URL from the first media item:
+ entity = tweet['entities']['media'][0]
+
+ temp = {}
+ temp['start'] = entity['indices'][0]
+ temp['end'] = entity['indices'][1]
+
+ if use_display_url and entity.get('display_url') and not use_expanded_url:
+ shown_url = entity['display_url']
+ elif use_expanded_url and entity.get('expanded_url'):
+ shown_url = entity['expanded_url']
+ else:
+ shown_url = entity['url']
+
+ url_html = '%s' % (entity['url'], shown_url)
+
+ if display_text_start <= temp['start'] <= display_text_end:
+ temp['replacement'] = url_html
+ entities.append(temp)
+ else:
+ suffix_text = suffix_text.replace(orig_tweet_text[temp['start']:temp['end']], url_html)
+
+ # Now do all the replacements, starting from the end, so that the
+ # start/end indices still work:
+ for entity in sorted(entities, key=lambda e: e['start'], reverse=True):
+ display_text = display_text[0:entity['start']] + entity['replacement'] + display_text[entity['end']:]
quote_text = ''
if expand_quoted_status and tweet.get('is_quote_status') and tweet.get('quoted_status'):
diff --git a/twython/compat.py b/twython/compat.py
index c36b3269..7c049b00 100644
--- a/twython/compat.py
+++ b/twython/compat.py
@@ -25,7 +25,7 @@
if is_py2:
from urllib import urlencode, quote_plus
- from urlparse import parse_qsl
+ from urlparse import parse_qsl, urlsplit
str = unicode
basestring = basestring
@@ -33,7 +33,7 @@
elif is_py3:
- from urllib.parse import urlencode, quote_plus, parse_qsl
+ from urllib.parse import urlencode, quote_plus, parse_qsl, urlsplit
str = str
basestring = (str, bytes)
diff --git a/twython/endpoints.py b/twython/endpoints.py
index 95e33d29..e35088d2 100644
--- a/twython/endpoints.py
+++ b/twython/endpoints.py
@@ -10,10 +10,11 @@
e.g. Twython.retweet(id=12345)
-This map is organized the order functions are documented at:
-https://dev.twitter.com/docs/api/1.1
+Official documentation for Twitter API endpoints can be found at:
+https://developer.twitter.com/en/docs/api-reference-index
"""
+import json
import os
import warnings
from io import BytesIO
@@ -33,7 +34,7 @@ def get_mentions_timeline(self, **params):
@screen_name) for the authenticating user.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/statuses/mentions_timeline
+ https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-mentions_timeline
"""
return self.get('statuses/mentions_timeline', params=params)
@@ -41,9 +42,10 @@ def get_mentions_timeline(self, **params):
def get_user_timeline(self, **params):
"""Returns a collection of the most recent Tweets posted by the user
- indicated by the screen_name or user_id parameters.
+ indicated by the ``screen_name`` or ``user_id`` parameters.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
"""
return self.get('statuses/user_timeline', params=params)
@@ -53,7 +55,8 @@ def get_home_timeline(self, **params):
"""Returns a collection of the most recent Tweets and retweets
posted by the authenticating user and the users they follow.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
"""
return self.get('statuses/home_timeline', params=params)
@@ -63,7 +66,8 @@ def retweeted_of_me(self, **params):
"""Returns the most recent tweets authored by the authenticating user
that have been retweeted by others.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/retweets_of_me
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweets_of_me
"""
return self.get('statuses/retweets_of_me', params=params)
@@ -73,34 +77,38 @@ def retweeted_of_me(self, **params):
def get_retweets(self, **params):
"""Returns up to 100 of the first retweets of a given tweet.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
"""
return self.get('statuses/retweets/%s' % params.get('id'),
params=params)
def show_status(self, **params):
- """Returns a single Tweet, specified by the id parameter
+ """Returns a single Tweet, specified by the ``id`` parameter
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
"""
return self.get('statuses/show/%s' % params.get('id'), params=params)
def lookup_status(self, **params):
"""Returns fully-hydrated tweet objects for up to 100 tweets per
- request, as specified by comma-separated values passed to the id
+ request, as specified by comma-separated values passed to the ``id``
parameter.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/lookup
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-lookup
"""
return self.post('statuses/lookup', params=params)
def destroy_status(self, **params):
- """Destroys the status specified by the required ID parameter
+ """Destroys the status specified by the required ``id`` parameter
- Docs: https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
"""
return self.post('statuses/destroy/%s' % params.get('id'))
@@ -108,15 +116,17 @@ def destroy_status(self, **params):
def update_status(self, **params):
"""Updates the authenticating user's current status, also known as tweeting
- Docs: https://dev.twitter.com/docs/api/1.1/post/statuses/update
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
"""
return self.post('statuses/update', params=params)
def retweet(self, **params):
- """Retweets a tweet specified by the id parameter
+ """Retweets a tweet specified by the ``id`` parameter
- Docs: https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/%3Aid
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
"""
return self.post('statuses/retweet/%s' % params.get('id'))
@@ -126,7 +136,7 @@ def update_status_with_media(self, **params): # pragma: no cover
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media
"""
warnings.warn(
@@ -139,21 +149,32 @@ def update_status_with_media(self, **params): # pragma: no cover
def upload_media(self, **params):
"""Uploads media file to Twitter servers. The file will be available to be attached
to a status for 60 minutes. To attach to a update, pass a list of returned media ids
- to the 'update_status' method using the 'media_ids' param.
+ to the :meth:`update_status` method using the ``media_ids`` param.
Docs:
- https://dev.twitter.com/rest/reference/post/media/upload
+ https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
+
"""
- # https://dev.twitter.com/rest/reference/get/media/upload-status
+ # https://developer.twitter.com/en/docs/media/upload-media/api-reference/get-media-upload-status
if params and params.get('command', '') == 'STATUS':
return self.get('https://upload.twitter.com/1.1/media/upload.json', params=params)
return self.post('https://upload.twitter.com/1.1/media/upload.json', params=params)
+ def create_metadata(self, **params):
+ """ Adds metadata to a media element, such as image descriptions for visually impaired.
+
+ Docs:
+ https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create
+
+ """
+ params = json.dumps(params)
+ return self.post("https://upload.twitter.com/1.1/media/metadata/create.json", params=params)
+
def upload_video(self, media, media_type, media_category=None, size=None, check_progress=False):
"""Uploads video file to Twitter servers in chunks. The file will be available to be attached
to a status for 60 minutes. To attach to a update, pass a list of returned media ids
- to the 'update_status' method using the 'media_ids' param.
+ to the :meth:`update_status` method using the ``media_ids`` param.
Upload happens in 3 stages:
- INIT call with size of media to be uploaded(in bytes). If this is more than 15mb, twitter will return error.
@@ -163,7 +184,8 @@ def upload_video(self, media, media_type, media_category=None, size=None, check_
Twitter media upload api expects each chunk to be not more than 5mb. We are sending chunk of 1mb each.
Docs:
- https://dev.twitter.com/rest/public/uploading-media#chunkedupload
+ https://developer.twitter.com/en/docs/media/upload-media/uploading-media/chunked-media-upload
+
"""
upload_url = 'https://upload.twitter.com/1.1/media/upload.json'
if not size:
@@ -208,7 +230,7 @@ def upload_video(self, media, media_type, media_category=None, size=None, check_
response = self.post(upload_url, params=params)
- # Only get the status if explicity asked to
+ # Only get the status if explicity asked to
# Default to False
if check_progress:
@@ -242,16 +264,18 @@ def get_oembed_tweet(self, **params):
"""Returns information allowing the creation of an embedded
representation of a Tweet on third party sites.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/oembed
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-oembed
"""
- return self.get('statuses/oembed', params=params)
+ return self.get('oembed', params=params)
def get_retweeters_ids(self, **params):
"""Returns a collection of up to 100 user IDs belonging to users who
- have retweeted the tweet specified by the id parameter.
+ have retweeted the tweet specified by the ``id`` parameter.
- Docs: https://dev.twitter.com/docs/api/1.1/get/statuses/retweeters/ids
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-retweeters-ids
"""
return self.get('statuses/retweeters/ids', params=params)
@@ -262,7 +286,8 @@ def get_retweeters_ids(self, **params):
def search(self, **params):
"""Returns a collection of relevant Tweets matching a specified query.
- Docs: https://dev.twitter.com/docs/api/1.1/get/search/tweets
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
"""
return self.get('search/tweets', params=params)
@@ -274,45 +299,50 @@ def search(self, **params):
def get_direct_messages(self, **params):
"""Returns the 20 most recent direct messages sent to the authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/direct_messages
+ Docs:
+ https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/list-events
"""
- return self.get('direct_messages', params=params)
+ return self.get('direct_messages/events/list', params=params)
get_direct_messages.iter_mode = 'id'
def get_sent_messages(self, **params):
"""Returns the 20 most recent direct messages sent by the authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent
+ Docs:
+ https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
"""
return self.get('direct_messages/sent', params=params)
get_sent_messages.iter_mode = 'id'
def get_direct_message(self, **params):
- """Returns a single direct message, specified by an id parameter.
+ """Returns a single direct message, specified by an ``id`` parameter.
- Docs: https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
+ Docs:
+ https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-event
"""
- return self.get('direct_messages/show', params=params)
+ return self.get('direct_messages/events/show', params=params)
def destroy_direct_message(self, **params):
- """Destroys the direct message specified in the required id parameter
+ """Destroys the direct message specified in the required ``id`` parameter
- Docs: https://dev.twitter.com/docs/api/1.1/post/direct_messages/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message-event
"""
- return self.post('direct_messages/destroy', params=params)
+ return self.delete('direct_messages/events/destroy', params=params)
def send_direct_message(self, **params):
"""Sends a new direct message to the specified user from the
authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/direct_messages/new
+ Docs:
+ https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event
"""
- return self.post('direct_messages/new', params=params)
+ return self.post('direct_messages/events/new', params=params, json_encoded=True)
# Friends & Followers
def get_user_ids_of_blocked_retweets(self, **params):
@@ -320,7 +350,7 @@ def get_user_ids_of_blocked_retweets(self, **params):
user does not want to receive retweets from.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/friendships/no_retweets/ids
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-no_retweets-ids
"""
return self.get('friendships/no_retweets/ids', params=params)
@@ -329,7 +359,8 @@ def get_friends_ids(self, **params):
"""Returns a cursored collection of user IDs for every user the
specified user is following (otherwise known as their "friends").
- Docs: https://dev.twitter.com/docs/api/1.1/get/friends/ids
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
"""
return self.get('friends/ids', params=params)
@@ -340,7 +371,8 @@ def get_followers_ids(self, **params):
"""Returns a cursored collection of user IDs for every user
following the specified user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/followers/ids
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
"""
return self.get('followers/ids', params=params)
@@ -349,9 +381,10 @@ def get_followers_ids(self, **params):
def lookup_friendships(self, **params):
"""Returns the relationships of the authenticating user to the
- comma-separated list of up to 100 screen_names or user_ids provided.
+ comma-separated list of up to 100 ``screen_names`` or ``user_ids`` provided.
- Docs: https://dev.twitter.com/docs/api/1.1/get/friendships/lookup
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-lookup
"""
return self.get('friendships/lookup', params=params)
@@ -360,7 +393,8 @@ def get_incoming_friendship_ids(self, **params):
"""Returns a collection of numeric IDs for every user who has a
pending request to follow the authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/friendships/incoming
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
"""
return self.get('friendships/incoming', params=params)
@@ -371,7 +405,8 @@ def get_outgoing_friendship_ids(self, **params):
"""Returns a collection of numeric IDs for every protected user for
whom the authenticating user has a pending follow request.
- Docs: https://dev.twitter.com/docs/api/1.1/get/friendships/outgoing
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-outgoing
"""
return self.get('friendships/outgoing', params=params)
@@ -380,18 +415,20 @@ def get_outgoing_friendship_ids(self, **params):
def create_friendship(self, **params):
"""Allows the authenticating users to follow the user specified
- in the ID parameter.
+ in the ``id`` parameter.
- Docs: https://dev.twitter.com/docs/api/1.1/post/friendships/create
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-create
"""
return self.post('friendships/create', params=params)
def destroy_friendship(self, **params):
"""Allows the authenticating user to unfollow the user specified
- in the ID parameter.
+ in the ``id`` parameter.
- Docs: https://dev.twitter.com/docs/api/1.1/post/friendships/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy
"""
return self.post('friendships/destroy', params=params)
@@ -400,7 +437,8 @@ def update_friendship(self, **params):
"""Allows one to enable or disable retweets and device notifications
from the specified user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/friendships/update
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-update
"""
return self.post('friendships/update', params=params)
@@ -409,7 +447,8 @@ def show_friendship(self, **params):
"""Returns detailed information about the relationship between two
arbitrary users.
- Docs: https://dev.twitter.com/docs/api/1.1/get/friendships/show
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-show
"""
return self.get('friendships/show', params=params)
@@ -418,7 +457,8 @@ def get_friends_list(self, **params):
"""Returns a cursored collection of user objects for every user the
specified user is following (otherwise known as their "friends").
- Docs: https://dev.twitter.com/docs/api/1.1/get/friends/list
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list
"""
return self.get('friends/list', params=params)
@@ -429,7 +469,8 @@ def get_followers_list(self, **params):
"""Returns a cursored collection of user objects for users
following the specified user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/followers/list
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-list
"""
return self.get('followers/list', params=params)
@@ -441,7 +482,8 @@ def get_account_settings(self, **params):
"""Returns settings (including current trend, geo and sleep time
information) for the authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/account/settings
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-settings
"""
return self.get('account/settings', params=params)
@@ -452,7 +494,7 @@ def verify_credentials(self, **params):
code and an error message if not.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
"""
return self.get('account/verify_credentials', params=params)
@@ -460,7 +502,8 @@ def verify_credentials(self, **params):
def update_account_settings(self, **params):
"""Updates the authenticating user's settings.
- Docs: https://dev.twitter.com/docs/api/1.1/post/account/settings
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings
"""
return self.post('account/settings', params=params)
@@ -478,7 +521,8 @@ def update_profile(self, **params):
"""Sets values that users are able to set under the "Account" tab of their
settings page.
- Docs: https://dev.twitter.com/docs/api/1.1/post/account/update_profile
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile
"""
return self.post('account/update_profile', params=params)
@@ -487,26 +531,35 @@ def update_profile_banner_image(self, **params): # pragma: no cover
"""Updates the authenticating user's profile background image.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/account/update_profile_background_image
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_background_image
"""
return self.post('account/update_profile_banner', params=params)
- def update_profile_colors(self, **params):
+ def update_profile_colors(self, **params): # pragma: no cover
"""Sets one or more hex values that control the color scheme of the
authenticating user's profile page on twitter.com.
+ This method is deprecated, replaced by the ``profile_link_color``
+ parameter to :meth:`update_profile`.
+
Docs:
- https://dev.twitter.com/docs/api/1.1/post/account/update_profile_colors
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile
"""
+ warnings.warn(
+ 'This method is deprecated. You should use the'
+ ' profile_link_color parameter in Twython.update_profile instead.',
+ TwythonDeprecationWarning,
+ stacklevel=2
+ )
return self.post('account/update_profile_colors', params=params)
def update_profile_image(self, **params): # pragma: no cover
"""Updates the authenticating user's profile image.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/account/update_profile_image
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
"""
return self.post('account/update_profile_image', params=params)
@@ -515,7 +568,8 @@ def list_blocks(self, **params):
"""Returns a collection of user objects that the authenticating user
is blocking.
- Docs: https://dev.twitter.com/docs/api/1.1/get/blocks/list
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
"""
return self.get('blocks/list', params=params)
@@ -525,7 +579,8 @@ def list_blocks(self, **params):
def list_block_ids(self, **params):
"""Returns an array of numeric user ids the authenticating user is blocking.
- Docs: https://dev.twitter.com/docs/api/1.1/get/blocks/ids
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-ids
"""
return self.get('blocks/ids', params=params)
@@ -535,35 +590,39 @@ def list_block_ids(self, **params):
def create_block(self, **params):
"""Blocks the specified user from following the authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/blocks/create
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-create
"""
return self.post('blocks/create', params=params)
def destroy_block(self, **params):
- """Un-blocks the user specified in the ID parameter for the
+ """Un-blocks the user specified in the ``id`` parameter for the
authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/blocks/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-blocks-destroy
"""
return self.post('blocks/destroy', params=params)
def lookup_user(self, **params):
"""Returns fully-hydrated user objects for up to 100 users per request,
- as specified by comma-separated values passed to the user_id and/or
- screen_name parameters.
+ as specified by comma-separated values passed to the ``user_id`` and/or
+ ``screen_name`` parameters.
- Docs: https://dev.twitter.com/docs/api/1.1/get/users/lookup
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
"""
return self.get('users/lookup', params=params)
def show_user(self, **params):
"""Returns a variety of information about the user specified by the
- required user_id or screen_name parameter.
+ required ``user_id`` or ``screen_name`` parameter.
- Docs: https://dev.twitter.com/docs/api/1.1/get/users/show
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
"""
return self.get('users/show', params=params)
@@ -572,7 +631,8 @@ def search_users(self, **params):
"""Provides a simple, relevance-based search interface to public user
accounts on Twitter.
- Docs: https://dev.twitter.com/docs/api/1.1/get/users/search
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
"""
return self.get('users/search', params=params)
@@ -598,7 +658,7 @@ def remove_profile_banner(self, **params):
Returns HTTP 200 upon success.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/account/remove_profile_banner
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-remove_profile_banner
"""
return self.post('account/remove_profile_banner', params=params)
@@ -607,7 +667,7 @@ def update_profile_background_image(self, **params):
"""Uploads a profile banner on behalf of the authenticating user.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/account/update_profile_banner
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_banner
"""
return self.post('account/update_profile_background_image',
@@ -617,7 +677,8 @@ def get_profile_banner_sizes(self, **params):
"""Returns a map of the available size variations of the specified
user's profile banner.
- Docs: https://dev.twitter.com/docs/api/1.1/get/users/profile_banner
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-users-profile_banner
"""
return self.get('users/profile_banner', params=params)
@@ -626,7 +687,8 @@ def list_mutes(self, **params):
"""Returns a collection of user objects that the authenticating user
is muting.
- Docs: https://dev.twitter.com/docs/api/1.1/get/mutes/users/list
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-list
"""
return self.get('mutes/users/list', params=params)
@@ -637,7 +699,8 @@ def list_mute_ids(self, **params):
"""Returns an array of numeric user ids the authenticating user
is muting.
- Docs: https://dev.twitter.com/docs/api/1.1/get/mutes/users/ids
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-mutes-users-ids
"""
return self.get('mutes/users/ids', params=params)
@@ -648,16 +711,18 @@ def create_mute(self, **params):
"""Mutes the specified user, preventing their tweets appearing
in the authenticating user's timeline.
- Docs: https://dev.twitter.com/docs/api/1.1/post/mutes/users/create
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-create
"""
return self.post('mutes/users/create', params=params)
def destroy_mute(self, **params):
- """Un-mutes the user specified in the user or ID parameter for
+ """Un-mutes the user specified in the user or ``id`` parameter for
the authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/mutes/users/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-destroy
"""
return self.post('mutes/users/destroy', params=params)
@@ -667,7 +732,7 @@ def get_user_suggestions_by_slug(self, **params):
"""Access the users in a given category of the Twitter suggested user list.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/users/suggestions/%3Aslug
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-suggestions-slug
"""
return self.get('users/suggestions/%s' % params.get('slug'),
@@ -676,7 +741,8 @@ def get_user_suggestions_by_slug(self, **params):
def get_user_suggestions(self, **params):
"""Access to Twitter's suggested user list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/users/suggestions
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-suggestions
"""
return self.get('users/suggestions', params=params)
@@ -687,7 +753,7 @@ def get_user_suggestions_statuses_by_slug(self, **params):
user.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/users/suggestions/%3Aslug/members
+ https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-suggestions-slug-members
"""
return self.get('users/suggestions/%s/members' % params.get('slug'),
@@ -698,26 +764,29 @@ def get_favorites(self, **params):
"""Returns the 20 most recent Tweets favorited by the authenticating
or specified user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/favorites/list
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list
"""
return self.get('favorites/list', params=params)
get_favorites.iter_mode = 'id'
def destroy_favorite(self, **params):
- """Un-favorites the status specified in the ID parameter as the
+ """Un-favorites the status specified in the ``id`` parameter as the
authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/favorites/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-favorites-destroy
"""
return self.post('favorites/destroy', params=params)
def create_favorite(self, **params):
- """Favorites the status specified in the ID parameter as the
+ """Favorites the status specified in the ``id`` parameter as the
authenticating user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/favorites/create
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-favorites-create
"""
return self.post('favorites/create', params=params)
@@ -727,7 +796,8 @@ def show_lists(self, **params):
"""Returns all lists the authenticating or specified user subscribes to,
including their own.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/list
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
"""
return self.get('lists/list', params=params)
@@ -735,7 +805,8 @@ def show_lists(self, **params):
def get_list_statuses(self, **params):
"""Returns a timeline of tweets authored by members of the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/statuses
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-statuses
"""
return self.get('lists/statuses', params=params)
@@ -744,7 +815,8 @@ def get_list_statuses(self, **params):
def delete_list_member(self, **params):
"""Removes the specified member from the list.
- Docs: https://dev.twitter.com/docs/api/1.1/post/lists/members/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-members-destroy
"""
return self.post('lists/members/destroy', params=params)
@@ -752,7 +824,8 @@ def delete_list_member(self, **params):
def get_list_memberships(self, **params):
"""Returns the lists the specified user has been added to.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/memberships
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships
"""
return self.get('lists/memberships', params=params)
@@ -762,7 +835,8 @@ def get_list_memberships(self, **params):
def get_list_subscribers(self, **params):
"""Returns the subscribers of the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/subscribers
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-subscribers
"""
return self.get('lists/subscribers', params=params)
@@ -773,7 +847,7 @@ def subscribe_to_list(self, **params):
"""Subscribes the authenticated user to the specified list.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/lists/subscribers/create
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-subscribers-create
"""
return self.post('lists/subscribers/create', params=params)
@@ -781,7 +855,8 @@ def subscribe_to_list(self, **params):
def is_list_subscriber(self, **params):
"""Check if the specified user is a subscriber of the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/subscribers/show
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-subscribers-show
"""
return self.get('lists/subscribers/show', params=params)
@@ -790,7 +865,7 @@ def unsubscribe_from_list(self, **params):
"""Unsubscribes the authenticated user from the specified list.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/lists/subscribers/destroy
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-subscribers-destroy
"""
return self.post('lists/subscribers/destroy', params=params)
@@ -800,7 +875,7 @@ def create_list_members(self, **params):
list of member ids or screen names.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/lists/members/create_all
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-members-create_all
"""
return self.post('lists/members/create_all', params=params)
@@ -808,7 +883,8 @@ def create_list_members(self, **params):
def is_list_member(self, **params):
"""Check if the specified user is a member of the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/members/show
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show
"""
return self.get('lists/members/show', params=params)
@@ -816,7 +892,8 @@ def is_list_member(self, **params):
def get_list_members(self, **params):
"""Returns the members of the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/members
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members
"""
return self.get('lists/members', params=params)
@@ -826,7 +903,8 @@ def get_list_members(self, **params):
def add_list_member(self, **params):
"""Add a member to a list.
- Docs: https://dev.twitter.com/docs/api/1.1/post/lists/members/create
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-members-create
"""
return self.post('lists/members/create', params=params)
@@ -834,7 +912,8 @@ def add_list_member(self, **params):
def delete_list(self, **params):
"""Deletes the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/post/lists/destroy
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
"""
return self.post('lists/destroy', params=params)
@@ -842,7 +921,8 @@ def delete_list(self, **params):
def update_list(self, **params):
"""Updates the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/post/lists/update
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
"""
return self.post('lists/update', params=params)
@@ -850,7 +930,8 @@ def update_list(self, **params):
def create_list(self, **params):
"""Creates a new list for the authenticated user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/lists/create
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
"""
return self.post('lists/create', params=params)
@@ -858,7 +939,8 @@ def create_list(self, **params):
def get_specific_list(self, **params):
"""Returns the specified list.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/show
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-show
"""
return self.get('lists/show', params=params)
@@ -866,7 +948,8 @@ def get_specific_list(self, **params):
def get_list_subscriptions(self, **params):
"""Obtain a collection of the lists the specified user is subscribed to.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/subscriptions
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-subscriptions
"""
return self.get('lists/subscriptions', params=params)
@@ -878,7 +961,7 @@ def delete_list_members(self, **params):
comma-separated list of member ids or screen names.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/lists/members/destroy_all
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-members-destroy_all
"""
return self.post('lists/members/destroy_all', params=params)
@@ -886,7 +969,8 @@ def delete_list_members(self, **params):
def show_owned_lists(self, **params):
"""Returns the lists owned by the specified Twitter user.
- Docs: https://dev.twitter.com/docs/api/1.1/get/lists/ownerships
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
"""
return self.get('lists/ownerships', params=params)
@@ -897,16 +981,17 @@ def show_owned_lists(self, **params):
def get_saved_searches(self, **params):
"""Returns the authenticated user's saved search queries.
- Docs: https://dev.twitter.com/docs/api/1.1/get/saved_searches/list
+ Docs:
+ https://developer.twitter.com/en/docs/tweets/search/api-reference/get-saved_searches-list
"""
return self.get('saved_searches/list', params=params)
def show_saved_search(self, **params):
- """Retrieve the information for the saved search represented by the given id.
+ """Retrieve the information for the saved search represented by the given ``id``.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/saved_searches/show/%3Aid
+ https://developer.twitter.com/en/docs/tweets/search/api-reference/get-saved_searches-show-id
"""
return self.get('saved_searches/show/%s' % params.get('id'),
@@ -915,7 +1000,8 @@ def show_saved_search(self, **params):
def create_saved_search(self, **params):
"""Create a new saved search for the authenticated user.
- Docs: https://dev.twitter.com/docs/api/1.1/post/saved_searches/create
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-mutes-users-create
"""
return self.post('saved_searches/create', params=params)
@@ -924,7 +1010,7 @@ def destroy_saved_search(self, **params):
"""Destroys a saved search for the authenticating user.
Docs:
- https://dev.twitter.com/docs/api/1.1/post/saved_searches/destroy/%3Aid
+ https://developer.twitter.com/en/docs/tweets/search/api-reference/post-saved_searches-destroy-id
"""
return self.post('saved_searches/destroy/%s' % params.get('id'),
@@ -934,7 +1020,8 @@ def destroy_saved_search(self, **params):
def get_geo_info(self, **params):
"""Returns all the information about a known place.
- Docs: https://dev.twitter.com/docs/api/1.1/get/geo/id/%3Aplace_id
+ Docs:
+ https://developer.twitter.com/en/docs/geo/place-information/api-reference/get-geo-id-place_id
"""
return self.get('geo/id/%s' % params.get('place_id'), params=params)
@@ -943,7 +1030,8 @@ def reverse_geocode(self, **params):
"""Given a latitude and a longitude, searches for up to 20 places
that can be used as a place_id when updating a status.
- Docs: https://dev.twitter.com/docs/api/1.1/get/geo/reverse_geocode
+ Docs:
+ https://developer.twitter.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode
"""
return self.get('geo/reverse_geocode', params=params)
@@ -951,7 +1039,8 @@ def reverse_geocode(self, **params):
def search_geo(self, **params):
"""Search for places that can be attached to a statuses/update.
- Docs: https://dev.twitter.com/docs/api/1.1/get/geo/search
+ Docs:
+ https://developer.twitter.com/en/docs/geo/places-near-location/api-reference/get-geo-search
"""
return self.get('geo/search', params=params)
@@ -977,7 +1066,8 @@ def get_place_trends(self, **params):
"""Returns the top 10 trending topics for a specific WOEID, if
trending information is available for it.
- Docs: https://dev.twitter.com/docs/api/1.1/get/trends/place
+ Docs:
+ https://developer.twitter.com/en/docs/trends/trends-for-location/api-reference/get-trends-place
"""
return self.get('trends/place', params=params)
@@ -985,7 +1075,8 @@ def get_place_trends(self, **params):
def get_available_trends(self, **params):
"""Returns the locations that Twitter has trending topic information for.
- Docs: https://dev.twitter.com/docs/api/1.1/get/trends/available
+ Docs:
+ https://developer.twitter.com/en/docs/trends/locations-with-trending-topics/api-reference/get-trends-available
"""
return self.get('trends/available', params=params)
@@ -994,7 +1085,8 @@ def get_closest_trends(self, **params):
"""Returns the locations that Twitter has trending topic information
for, closest to a specified location.
- Docs: https://dev.twitter.com/docs/api/1.1/get/trends/closest
+ Docs:
+ https://developer.twitter.com/en/docs/trends/locations-with-trending-topics/api-reference/get-trends-closest
"""
return self.get('trends/closest', params=params)
@@ -1003,7 +1095,8 @@ def get_closest_trends(self, **params):
def report_spam(self, **params): # pragma: no cover
"""Report the specified user as a spam account to Twitter.
- Docs: https://dev.twitter.com/docs/api/1.1/post/users/report_spam
+ Docs:
+ https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/post-users-report_spam
"""
return self.post('users/report_spam', params=params)
@@ -1013,7 +1106,8 @@ def invalidate_token(self, **params): # pragma: no cover
"""Allows a registered application to revoke an issued OAuth 2 Bearer
Token by presenting its client credentials.
- Docs: https://dev.twitter.com/docs/api/1.1/post/oauth2/invalidate_token
+ Docs:
+ https://developer.twitter.com/en/docs/basics/authentication/api-reference/invalidate_token
"""
return self.post('oauth2/invalidate_token', params=params)
@@ -1022,7 +1116,8 @@ def invalidate_token(self, **params): # pragma: no cover
def get_twitter_configuration(self, **params):
"""Returns the current configuration used by Twitter
- Docs: https://dev.twitter.com/docs/api/1.1/get/help/configuration
+ Docs:
+ https://developer.twitter.com/en/docs/developer-utilities/configuration/api-reference/get-help-configuration
"""
return self.get('help/configuration', params=params)
@@ -1031,7 +1126,8 @@ def get_supported_languages(self, **params):
"""Returns the list of languages supported by Twitter along with
their ISO 639-1 code.
- Docs: https://dev.twitter.com/docs/api/1.1/get/help/languages
+ Docs:
+ https://developer.twitter.com/en/docs/developer-utilities/supported-languages/api-reference/get-help-languages
"""
return self.get('help/languages', params=params)
@@ -1039,7 +1135,8 @@ def get_supported_languages(self, **params):
def get_privacy_policy(self, **params):
"""Returns Twitter's Privacy Policy
- Docs: https://dev.twitter.com/docs/api/1.1/get/help/privacy
+ Docs:
+ https://developer.twitter.com/en/docs/developer-utilities/privacy-policy/api-reference/get-help-privacy
"""
return self.get('help/privacy', params=params)
@@ -1047,7 +1144,8 @@ def get_privacy_policy(self, **params):
def get_tos(self, **params):
"""Return the Twitter Terms of Service
- Docs: https://dev.twitter.com/docs/api/1.1/get/help/tos
+ Docs:
+ https://developer.twitter.com/en/docs/developer-utilities/terms-of-service/api-reference/get-help-tos
"""
return self.get('help/tos', params=params)
@@ -1057,13 +1155,13 @@ def get_application_rate_limit_status(self, **params):
specified resource families.
Docs:
- https://dev.twitter.com/docs/api/1.1/get/application/rate_limit_status
+ https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status
"""
return self.get('application/rate_limit_status', params=params)
-# from https://dev.twitter.com/docs/error-codes-responses
+# from https://developer.twitter.com/en/docs/ads/general/guides/response-codes
TWITTER_HTTP_STATUS_CODE = {
200: ('OK', 'Success!'),
304: ('Not Modified', 'There was no new data to return.'),
diff --git a/twython/streaming/api.py b/twython/streaming/api.py
index 47678e47..6073abbe 100644
--- a/twython/streaming/api.py
+++ b/twython/streaming/api.py
@@ -86,8 +86,6 @@ def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret,
# Set up type methods
StreamTypes = TwythonStreamerTypes(self)
self.statuses = StreamTypes.statuses
- self.user = StreamTypes.user
- self.site = StreamTypes.site
self.connected = False
@@ -125,7 +123,7 @@ def _send(retry_counter):
self.on_timeout()
else:
if response.status_code != 200:
- self.on_error(response.status_code, response.content)
+ self.on_error(response.status_code, response.content, response.headers)
if self.retry_count and \
(self.retry_count - retry_counter) > 0:
@@ -169,16 +167,16 @@ def on_success(self, data): # pragma: no cover
Returns True if other handlers for this message should be invoked.
Feel free to override this to handle your streaming data how you
- want it handled.
- See https://dev.twitter.com/docs/streaming-apis/messages for messages
- sent along in stream responses.
+ want it handled. See
+ https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/streaming-message-types
+ for messages sent along in stream responses.
:param data: data recieved from the stream
:type data: dict
"""
return True
- def on_error(self, status_code, data): # pragma: no cover
+ def on_error(self, status_code, data, headers=None): # pragma: no cover
"""Called when stream returns non-200 status code
Feel free to override this to handle your streaming data how you
@@ -189,6 +187,9 @@ def on_error(self, status_code, data): # pragma: no cover
:param data: Error message sent from stream
:type data: dict
+
+ :param headers: Response headers sent from the stream (i.e. Retry-After)
+ :type headers: dict
"""
return
diff --git a/twython/streaming/types.py b/twython/streaming/types.py
index aa6b9adb..5042d294 100644
--- a/twython/streaming/types.py
+++ b/twython/streaming/types.py
@@ -20,33 +20,14 @@ def __init__(self, streamer):
self.streamer = streamer
self.statuses = TwythonStreamerTypesStatuses(streamer)
- def user(self, **params):
- """Stream user
-
- Accepted params found at:
- https://dev.twitter.com/docs/api/1.1/get/user
- """
- url = 'https://userstream.twitter.com/%s/user.json' \
- % self.streamer.api_version
- self.streamer._request(url, params=params)
-
- def site(self, **params):
- """Stream site
-
- Accepted params found at:
- https://dev.twitter.com/docs/api/1.1/get/site
- """
- url = 'https://sitestream.twitter.com/%s/site.json' \
- % self.streamer.api_version
- self.streamer._request(url, params=params)
-
class TwythonStreamerTypesStatuses(object):
"""Class for different statuses endpoints
- Available so TwythonStreamer.statuses.filter() is available.
- Just a bit cleaner than TwythonStreamer.statuses_filter(),
- statuses_sample(), etc. all being single methods in TwythonStreamer
+ Available so :meth:`TwythonStreamer.statuses.filter()` is available.
+ Just a bit cleaner than :meth:`TwythonStreamer.statuses_filter()`,
+ :meth:`statuses_sample()`, etc. all being single methods in
+ :class:`TwythonStreamer`.
"""
def __init__(self, streamer):
@@ -54,31 +35,31 @@ def __init__(self, streamer):
self.params = None
def filter(self, **params):
- """Stream statuses/filter
+ r"""Stream statuses/filter
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
- https://dev.twitter.com/docs/api/1.1/post/statuses/filter
+ https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter
"""
url = 'https://stream.twitter.com/%s/statuses/filter.json' \
% self.streamer.api_version
self.streamer._request(url, 'POST', params=params)
def sample(self, **params):
- """Stream statuses/sample
+ r"""Stream statuses/sample
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
- https://dev.twitter.com/docs/api/1.1/get/statuses/sample
+ https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample
"""
url = 'https://stream.twitter.com/%s/statuses/sample.json' \
% self.streamer.api_version
self.streamer._request(url, params=params)
def firehose(self, **params):
- """Stream statuses/firehose
+ r"""Stream statuses/firehose
:param \*\*params: Parameters to send with your stream request
@@ -90,12 +71,12 @@ def firehose(self, **params):
self.streamer._request(url, params=params)
def set_dynamic_filter(self, **params):
- """Set/update statuses/filter
+ r"""Set/update statuses/filter
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
- https://dev.twitter.com/docs/api/1.1/post/statuses/filter
+ https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter
"""
self.params = params
@@ -104,4 +85,4 @@ def dynamic_filter(self):
url = 'https://stream.twitter.com/%s/statuses/filter.json' \
% self.streamer.api_version
- self.streamer._request(url, 'POST', params=self.params)
+ self.streamer._request(url, 'POST', params=self.params)