diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 00000000..eb59bbc7 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,20 @@ +version: 2 +jobs: + build: + working_directory: ~/repo + docker: + - image: jeremylow/python-twitter + steps: + - checkout + - run: sudo chown -R circleci:circleci ~/repo + - run: + name: set up pyenv + command: pyenv local 2.7.15 3.7.1 pypy-5.7.1 pypy3.5-6.0.0 + - run: + name: install deps + command: pip install -r requirements.testing.txt + - run: + name: run tests + command: | + export PATH=/home/circleci/.local/bin:$PATH + make tox diff --git a/.circleci/images/Dockerfile b/.circleci/images/Dockerfile new file mode 100644 index 00000000..04d96343 --- /dev/null +++ b/.circleci/images/Dockerfile @@ -0,0 +1,21 @@ +# We could use a smaller image, but this ensures that everything CircleCI needs +# is installed already. +FROM circleci/python:3.6 +MAINTAINER Jeremy Low + +# These are the version of python currently supported. +ENV SUPPORTED_VERSIONS="2.7.15 3.7.1 pypy-5.7.1 pypy3.5-6.0.0" +ENV PYENV_ROOT /home/circleci/.pyenv +ENV PATH $PYENV_ROOT/shims:$PYENV_ROOT/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH + +# Get and install pyenv. +RUN curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash + +# pyenv installer doesn't set these for us. +RUN echo "export PATH=${PYENV_ROOT}/bin:$$PATH \n\ +eval '\$(pyenv init -)' \n\ +eval '\$(pyenv virtualenv-init -)'" >> ~/.bashrc +RUN pyenv update + +# Install each supported version into the container. +RUN for i in $SUPPORTED_VERSIONS; do pyenv install "$i"; done diff --git a/.gitignore b/.gitignore index 5f2ff1ee..f5955911 100644 --- a/.gitignore +++ b/.gitignore @@ -18,13 +18,23 @@ var sdist develop-eggs .installed.cfg +.eggs +.cache +.vscode # Installer logs pip-log.txt # Unit test / coverage reports .coverage +.codecov-token .tox +htmlcov +.tox +nosetests.xml +htmlcov +coverage.xml +.hypothesis # PyCharm data .idea @@ -34,3 +44,18 @@ pip-log.txt #Mr Developer .mr.developer.cfg + +#Environment +env +.python-version + +violations.flake8.txt + +# Built docs +doc/_build/** + +# Mypy cache +**/.mypy_cache + +# VS Code +**/.vscode diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 00000000..adb00cfa --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,38 @@ +Originally two libraries by DeWitt Clinton and Mike Taylor which was then merged into python-twitter. + +Now it's a full-on open source project with many contributors over time: + +* Jodok Batlogg, +* Kyle Bock, +* Brad Choate, +* Robert Clarke, +* Jim Cortez, +* Pierre-Jean Coudert, +* Aish Raj Dahal, +* Thomas Dyson, +* Jim Easterbrook +* Yoshinori Fukushima, +* Hameedullah Khan, +* Osama Khalid, +* Omar Kilani, +* Domen Kožar, +* Robert Laquey, +* Jason Lemoine, +* Pradeep Nayak, +* Ian Ozsvald, +* Nicolas Perriault, +* Trevor Prater, +* Glen Tregoning, +* Lars Weiler, +* Sebastian Wiesinger, +* Jake Robinson, +* Muthu Annamalai, +* abloch, +* cahlan, +* dpslwk, +* edleaf, +* ecesena, +* git-matrix, +* sbywater, +* thefinn93, +* themylogin, diff --git a/CHANGES b/CHANGES index 0bfe1f3c..3af38784 100644 --- a/CHANGES +++ b/CHANGES @@ -1,5 +1,100 @@ +2016-05-25 + Going forward all changes will be tracked in docs/changelog.rst + +2015-12-28 + Large number of changes related to making the code Python v3 compatible. + See the messy details at https://github.com/bear/python-twitter/pull/251 + + Pull Requests + #525 Adds support for 280 character limit for tweets by trevorprater + #267 initialize Api.__auth fixes #119 by rbpasker + #266 Add full_text and page options in GetDirectMessages function by mistersalmon + #264 Updates Media object with new methods, adds id param, adds tests by jeremylow + #262 Update get_access_token.py by lababidi + #261 Adding Collections by ryankicks + #260 Added UpdateBackgroundImage method and added profile_link_color argument to UpdateProfile by BrandonBielicki + #259 Added GetFriendIDsPaged by RockHoward + #254 Adding api methods for suggestions and suggestions/:slug by trentstollery + #253 Added who parameter to api.GetSearch by wilsonand1 + #250 adds UpdateFriendship (shared Add/Edit friendship) by jheld + #249 Fixed Non-ASCII printable representation in Trend by der-Daniel + #246 Add __repr__ for status by era + #245 Python-3 Fix: decode bytestreams for json load by ligthyear + #243 Remove references to outdated API functionality: GetUserByEmail by Vector919 + #239 Correct GetListsList docstring by tedmiston + + Probably a whole lot that I missed - ugh! + +2017-11-11 + Added support for 280 character limit + +2015-10-05 + Added who to api.GetSearch + +2014-12-29 + removed reference to simplejson + +2014-12-24 + bump version to v2.3 + bump version to v2.2 + PEP8 standardization + +2014-07-10 + bump version to v2.1 + +2014-07-10 + update copyright years + change setup.py to allow installing via wheel + renamed README.md to README.rst + added AUTHORS.rst + +2014-02-17 + changed version to 1.3 and then to 1.3.1 because I forgot to include CHANGES + fix Issue 143 - GetStatusOembed() url parameter was being stomped on + fix debugHTTP in a brute force way but it works again + Add id_str to Status class + Added LookupFriendship() method for checking follow status + pull request from lucas + Fix bug of GetListMembers when specifying `owner_screen_name` + pull request from shichao-an + +2014-01-18 + backfilling varioius lists endpoints + added a basic user stream call + +2014-01-17 + changed to version 1.2 + fixed python 3 issue in setup.py (print statements) + fixed error in CreateList(), changed count default for GetFollowers to 200 and added a GetFollowersPaged() method + +need to backfill commit log entries! + +2013-10-06 + changed version to 1.1 + The following changes have been made since the 1.0.1 release + + Remove from ParseTweet the Python 2.7 only dict comprehension item + Fix GetListTimeline condition to enable owner_screen_name based fetching + Many fixes for readability and PEP8 + Cleaning up some of the package importing. Only importing the functions that are needed + Also added first build of the sphinx documentation. Copied some info from the readme to the index page + Added lines to setup.py to help the user troubleshoot install problems. #109 + Removed the OAuth2 lines from the readme + Removed OAuth2 library requirements + Added GetListMembers() + + +2013-06-07 + changed version to 1.0.1 + added README bit about Python version requirement + +2013-06-04 + changed version to 1.0 + removed doc directory until we can update docs for v1.1 API + added to package MANIFEST.in the testdata directory + 2013-05-28 - bumped version to 1.0.0 + bumped version to 1.0rc1 merged in api_v1.1 branch The library is now only for Twitter API v1.1 @@ -9,7 +104,7 @@ removed GetPublicTimeline from the docs so as to stop confusing new folks since it was the first example given ... d'oh! - + 2013-02-10 bumped version to 0.8.6 @@ -33,7 +128,7 @@ to push to PyPI and other places all work now will be on getting the v1.1 API supported - + 2012-11-04 https://github.com/bear/python-twitter/issues/4 Api.UserLookUp() throws attribute error when corresponding screen_name is not found diff --git a/COPYING b/COPYING index 49f0e0cc..dfaa26e3 100644 --- a/COPYING +++ b/COPYING @@ -1,4 +1,4 @@ - Copyright 2007-2013 The Python-Twitter Developers + Copyright 2007-2014 The Python-Twitter Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/GAE.rst b/GAE.rst new file mode 100644 index 00000000..4429e02f --- /dev/null +++ b/GAE.rst @@ -0,0 +1,55 @@ +================================================ +How to use python-twitter with Google App Engine +================================================ + +********** +Background +********** + +Google App Engine uses virtual machines to do work and serve your application's content. In order to make a 'regular' external web request, the instance must use the built-in urlfetch library provided by Google in addition to the traditional python requests library. As a result, a few extra steps must be followed to use python-twitter on App Engine. + + +************* +Prerequisites +************* + +Follow the `third party vendor library install instructions `_ to include the dependency libraries listed in ``requirements.txt``: ``requests``, ``requests_oauthlib`` and ``requests_toolbelt``, as well as ``python-twitter`` library. Typically you can just place the module folders into the same place as your app.yaml file; it might look something like this: + +| myapp/ +| ├── twitter/ +| ├── requests_oauthlib/ +| ├── requests_toolbelt/ +| ├── main.py +| └── app.yaml + + +******** +app.yaml +******** + +In order to use HTTPS, you'll have to make sure the built-in SSL library is properly imported in your ``app.yaml`` file. Here's what that section of your ``app.yaml`` file might look like: + +| libraries: +| - name: jinja2 +| version: latest +| - name: webapp2 +| version: latest +| - name: ssl +| version: latest + + +**************************** +Limitations & Considerations +**************************** + +Caching +^^^^^^^ +When using twitter-python on App Engine, caching is disabled. You'll have to add and manage App Engine's memcache logic on your own if you require any caching beyond what is probably already setup on App Engine by default. + +Datastore +^^^^^^^^^ +If you plan to store tweets or other information returned by the API in Datastore, you'll probably want to make your own NDP models to store the desired components of the response rather than shoving the whole response into an entity. + +Sockets +^^^^^^^^^ +When urllib3 is imported on App Engine it will throw a warning about sockets: ``AppEnginePlatformWarning: urllib3 is using URLFetch on Google App Engine sandbox...`` This is just a warning that you'd have to use the Sockets API if you intend to use the sockets feature of the library, which we don't use in python-twitter so it can be ignored. diff --git a/MANIFEST.in b/MANIFEST.in index c535ffd5..ca78efe0 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,8 +2,7 @@ include CHANGES include COPYING include LICENSE include NOTICE -include README.md -include *.py -recursive-include examples *.py -recursive-include doc *.html +include *.rst +include requirements.txt prune .DS_Store +graft doc examples testdata tests diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..76039c40 --- /dev/null +++ b/Makefile @@ -0,0 +1,71 @@ +SUPPORTED_VERSIONS = 2.7.15 3.6.5 pypy-5.7.1 pypy3.5-6.0.0 + +help: + @echo " env install all production dependencies" + @echo " dev install all dev and production dependencies (virtualenv is assumed)" + @echo " docs build documentation" + @echo " clean remove unwanted stuff" + @echo " lint check style with flake8" + @echo " test run tests" + @echo " coverage run tests with code coverage" + +env: + pip install -Ur requirements.txt + +pyenv: + for version in $(SUPPORTED_VERSIONS) ; do \ + pyenv install -s $$version; \ + done + pyenv local $(SUPPORTED_VERSIONS) + +dev: pyenv env + pip install -Ur requirements.testing.txt + +info: + @python --version + @pyenv --version + @pip --version + +clean: + rm -fr build + rm -fr dist + find . -name '*.pyc' -exec rm -f {} \; + find . -name '*.pyo' -exec rm -f {} \; + find . -name '*~' ! -name '*.un~' -exec rm -f {} \; + +docs: + $(MAKE) -C doc html + +lint: + pycodestyle --config={toxinidir}/setup.cfg twitter tests + +test: lint + pytest -s + #python setup.py test + +tox: clean + tox + +coverage: clean + coverage run --source=twitter setup.py test --addopts "--ignore=venv" + coverage html + coverage report + +update-pyenv: + cd /opt/circleci/.pyenv/plugins/python-build/../.. && git pull && cd - + +ci: update-pyenv pyenv dev tox + CODECOV_TOKEN=`cat .codecov-token` codecov + +build: clean + python setup.py check + python setup.py sdist + python setup.py bdist_wheel + +upload: clean + pyenv 2.7.15 + python setup.py sdist upload + python setup.py bdist_wheel upload + pyenv 3.6.5 + python setup.py bdist_wheel upload + pyenv local $(SUPPORTED_VERSIONS) diff --git a/NOTICE b/NOTICE index 3fd547fd..ce8e6d5d 100644 --- a/NOTICE +++ b/NOTICE @@ -1,13 +1,3 @@ NOTICE -The simplejson library (http://simplejson.googlecode.com) is used under the terms of the MIT license and is copyright Bob Ippolito. -See http://simplejson.googlecode.com/svn/trunk/LICENSE.txt for details. - -The python-oauth2 library (http://github.com/simplegeo/python-oauth2) is used under the terms of the MIT license and is copyright Leah Culver. -See http://github.com/simplegeo/python-oauth2/blob/master/LICENSE.txt for details. - -The httplib2 library (http://code.google.com/p/httplib2) is used under the terms of the MIT license and is copyright Joe Gregorio. -See http://code.google.com/p/httplib2/source/browse/python2/httplib2/__init__.py for details. - This code is made available under the Apache License and is copyright the Python-Twitter Developers. - diff --git a/README.md b/README.md deleted file mode 100644 index 677d8b04..00000000 --- a/README.md +++ /dev/null @@ -1,212 +0,0 @@ -# Python Twitter - -**A Python wrapper around the Twitter API.** - -Author: The Python-Twitter Developers - -## Introduction - -This library provides a pure Python interface for the [Twitter API](https://dev.twitter.com/). - -[Twitter](http://twitter.com) provides a service that allows people to connect via the web, IM, and SMS. Twitter exposes a [web services API](http://dev.twitter.com/doc) and this library is intended to make it even easier for Python programmers to use. - -## Building - -From source: - -Install the dependencies: - -- [SimpleJson](http://cheeseshop.python.org/pypi/simplejson) -- [SimpleGeo's OAuth2](http://github.com/simplegeo/python-oauth2) or [OAuth2](http://pypi.python.org/pypi/oauth2) -- [HTTPLib2](http://code.google.com/p/httplib2/) (installed along with `oauth2` if you use `setuptools`) - -Alternatively use `pip`: - - $ pip install -r requirements.txt - -Download the latest `python-twitter` library from: http://code.google.com/p/python-twitter/ - -Extract the source distribution and run: - -``` -$ python setup.py build -$ python setup.py install -``` - -*Testing* - -With setuptools installed: - -``` -$ python setup.py test -``` - -Without setuptools installed: - -``` -$ python twitter_test.py -``` - -## Getting the code - -The code is hosted at [Github](https://github.com/bear/python-twitter). - -Check out the latest development version anonymously with: - -``` - $ git clone git://github.com/bear/python-twitter.git - $ cd python-twitter -``` - -## Documentation - -View the last release API documentation at: [http://dev.twitter.com/doc](http://dev.twitter.com/doc) - -## Using - -The library provides a Python wrapper around the Twitter API and the Twitter data model. - -**Model:** - -The three model classes are `twitter.Status`, `twitter.User`, and `twitter.DirectMessage`. The API methods return instances of these classes. - -To read the full API for `twitter.Status`, `twitter.User`, or `twitter.DirectMessage`, run: - -``` -$ pydoc twitter.Status -$ pydoc twitter.User -$ pydoc twitter.DirectMessage -``` - -*API:* - -The API is exposed via the `twitter.Api` class. - -To create an instance of the `twitter.Api` class: - -``` ->>> import twitter ->>> api = twitter.Api() -``` - -To create an instance of the `twitter.Api` with login credentials (many API calls required the client to be authenticated.) - -The python-twitter library now only supports oAuth authentication as the Twitter devs have indicated that OAuth is the only method that will be supported moving forward. - -``` ->>> api = twitter.Api(consumer_key='consumer_key', - consumer_secret='consumer_secret', - access_token_key='access_token', - access_token_secret='access_token_secret') -``` - -To see if your credentials are successful: - -``` ->>> print api.VerifyCredentials() -{"id": 16133, "location": "Philadelphia", "name": "bear"} -``` - -**NOTE -** much more than the small sample given here will print - -To fetch a single user's public status messages, where `user` is either -a Twitter *short name* or their user id. - -``` ->>> statuses = api.GetUserTimeline(user) ->>> print [s.text for s in statuses] -``` - -To fetch a list a user's friends (requires authentication): - -``` ->>> users = api.GetFriends() ->>> print [u.name for u in users] -``` - -To post a Twitter status message (requires authentication): - -``` ->>> status = api.PostUpdate('I love python-twitter!') ->>> print status.text -I love python-twitter! -``` - -There are many more API methods, to read the full API documentation: - -``` -$ pydoc twitter.Api -``` - -## Todo - -Patches and bug reports are [welcome](https://github.com/bear/python-twitter/issues/new), just please keep the style consistent with the original source. - -Add more example scripts. - -The twitter.Status and `twitter.User` classes are going to be hard to keep in sync with the API if the API changes. More of the code could probably be written with introspection. - -Statement coverage of `twitter_test` is only about 80% of twitter.py. - -The `twitter.Status` and `twitter.User` classes could perform more validation on the property setters. - -## More Information - -Please visit [the google group](http://groups.google.com/group/python-twitter) for more discussion. - -## Contributors - -Originally two libraries by DeWitt Clinton and Mike Taylor which was then merged into python-twitter. - -Now it's a full-on open source project with many contributors over time: - -* Jodok Batlogg, -* Kyle Bock, -* Brad Choate, -* Robert Clarke, -* Jim Cortez, -* Pierre-Jean Coudert, -* Aish Raj Dahal, -* Thomas Dyson, -* Yoshinori Fukushima, -* Hameedullah Khan, -* Osama Khalid, -* Omar Kilani, -* Domen Kožar, -* Robert Laquey, -* Jason Lemoine, -* Pradeep Nayak, -* Ian Ozsvald, -* Nicolas Perriault, -* Glen Tregoning, -* Lars Weiler, -* Sebastian Wiesinger, -* abloch, -* cahlan, -* dpslwk, -* edleaf, -* ecesena, -* git-matrix, -* sbywater, -* thefinn93, -* themylogin, - -and the rest of the python-twitter mailing list. - -## License - -``` -Copyright 2007-2013 The Python-Twitter Developers - -Licensed under the Apache License, Version 2.0 (the 'License'); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an 'AS IS' BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -``` diff --git a/README.rst b/README.rst new file mode 100644 index 00000000..bed3afb3 --- /dev/null +++ b/README.rst @@ -0,0 +1,225 @@ +Python Twitter + +A Python wrapper around the Twitter API. + +By the `Python-Twitter Developers `_ + +============ +NOTICE +============ +I've archived this repo to mark that I'm not going to be maintaining it. It's open-source so anyone using it can fork or take it over. +Thank you to all the people that contributed to it in the past + +============ +Introduction +============ + +This library provides a pure Python interface for the `Twitter API `_. It works with Python versions from 2.7+ and Python 3. + +`Twitter `_ provides a service that allows people to connect via the web, IM, and SMS. Twitter exposes a `web services API `_ and this library is intended to make it even easier for Python programmers to use. + +========== +Installing +========== + +You can install python-twitter using:: + + $ pip install python-twitter + + +If you are using python-twitter on Google App Engine, see `more information `_ about including 3rd party vendor library dependencies in your App Engine project. + + +================ +Getting the code +================ + +The code is hosted at https://github.com/bear/python-twitter + +Check out the latest development version anonymously with:: + + $ git clone git://github.com/bear/python-twitter.git + $ cd python-twitter + +To install dependencies, run either:: + + $ make dev + +or:: + + $ pip install -Ur requirements.testing.txt + $ pip install -Ur requirements.txt + +Note that ```make dev``` will install into your local ```pyenv``` all of the versions needed for test runs using ```tox```. + +To install the minimal dependencies for production use (i.e., what is installed +with ``pip install python-twitter``) run:: + + $ make env + +or:: + + $ pip install -Ur requirements.txt + +============= +Running Tests +============= +The test suite can be run against a single Python version or against a range of them depending on which Makefile target you select. + +Note that tests require ```pip install pytest``` and optionally ```pip install pytest-cov``` (these are included if you have installed dependencies from ```requirements.testing.txt```) + +To run the unit tests with a single Python version:: + + $ make test + +to also run code coverage:: + + $ make coverage + +To run the unit tests against a set of Python versions:: + + $ make tox + +============= +Documentation +============= + +View the latest python-twitter documentation at +https://python-twitter.readthedocs.io. You can view Twitter's API documentation at: https://dev.twitter.com/overview/documentation + +===== +Using +===== + +The library provides a Python wrapper around the Twitter API and the Twitter data model. To get started, check out the examples in the examples/ folder or read the documentation at https://python-twitter.readthedocs.io which contains information about getting your authentication keys from Twitter and using the library. + +------------------ +Using with Django +------------------ + +Additional template tags that expand tweet urls and urlize tweet text. See the django template tags available for use with python-twitter: https://github.com/radzhome/python-twitter-django-tags + +------ +Models +------ + +The library utilizes models to represent various data structures returned by Twitter. Those models are: + * twitter.Category + * twitter.DirectMessage + * twitter.Hashtag + * twitter.List + * twitter.Media + * twitter.Status + * twitter.Trend + * twitter.Url + * twitter.User + * twitter.UserStatus + +To read the documentation for any of these models, run:: + + $ pydoc twitter.[model] + +--- +API +--- + +The API is exposed via the ``twitter.Api`` class. + +The python-twitter requires the use of OAuth keys for nearly all operations. As of Twitter's API v1.1, authentication is required for most, if not all, endpoints. Therefore, you will need to register an app with Twitter in order to use this library. Please see the "Getting Started" guide on https://python-twitter.readthedocs.io for more information. + +To generate an Access Token you have to pick what type of access your application requires and then do one of the following: + +- `Generate a token to access your own account `_ +- `Generate a pin-based token `_ +- use the helper script `get_access_token.py `_ + +For full details see the `Twitter OAuth Overview `_ + +To create an instance of the ``twitter.Api`` with login credentials (Twitter now requires an OAuth Access Token for all API calls):: + + >>> import twitter + >>> api = twitter.Api(consumer_key='consumer_key', + consumer_secret='consumer_secret', + access_token_key='access_token', + access_token_secret='access_token_secret') + +To see if your credentials are successful:: + + >>> print(api.VerifyCredentials()) + {"id": 16133, "location": "Philadelphia", "name": "bear"} + +**NOTE**: much more than the small sample given here will print + +To fetch a single user's public status messages, where ``user`` is a Twitter user's screen name:: + + >>> statuses = api.GetUserTimeline(screen_name=user) + >>> print([s.text for s in statuses]) + +To fetch a list of a user's friends:: + + >>> users = api.GetFriends() + >>> print([u.name for u in users]) + +To post a Twitter status message:: + + >>> status = api.PostUpdate('I love python-twitter!') + >>> print(status.text) + I love python-twitter! + +There are many more API methods, to read the full API documentation either +check out the documentation on `readthedocs +`_, build the documentation locally +with:: + + $ make docs + +or check out the inline documentation with:: + + $ pydoc twitter.Api + +------ +Todo +------ + +Patches, pull requests, and bug reports are `welcome `_, just please keep the style consistent with the original source. + +In particular, having more example scripts would be a huge help. If you have +a program that uses python-twitter and would like a link in the documentation, +submit a pull request against ``twitter/doc/getting_started.rst`` and add your +program at the bottom. + +The twitter.Status and ``twitter.User`` classes are going to be hard to keep in sync with the API if the API changes. More of the code could probably be written with introspection. + +The ``twitter.Status`` and ``twitter.User`` classes could perform more validation on the property setters. + +---------------- +More Information +---------------- + +Please visit `the google group `_ for more discussion. + +------------ +Contributors +------------ + +Originally two libraries by DeWitt Clinton and Mike Taylor which were then merged into python-twitter. + +Now it's a full-on open source project with many contributors over time. See AUTHORS.rst for the complete list. + +------- +License +------- + +| Copyright 2007-2016 The Python-Twitter Developers +| +| Licensed under the Apache License, Version 2.0 (the 'License'); +| you may not use this file except in compliance with the License. +| You may obtain a copy of the License at +| +| http://www.apache.org/licenses/LICENSE-2.0 +| +| Unless required by applicable law or agreed to in writing, software +| distributed under the License is distributed on an 'AS IS' BASIS, +| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +| See the License for the specific language governing permissions and +| limitations under the License. diff --git a/coveragerc b/coveragerc new file mode 100644 index 00000000..1d7881d5 --- /dev/null +++ b/coveragerc @@ -0,0 +1,2 @@ +[run] +source = twitter diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 00000000..8c9d6add --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-twitter.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-twitter.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/python-twitter" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-twitter" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/doc/changelog.rst b/doc/changelog.rst new file mode 100644 index 00000000..18050c6e --- /dev/null +++ b/doc/changelog.rst @@ -0,0 +1,166 @@ +Changelog +--------- + +Version 3.4.2 +============= + +Bugfixes: + +* Allow upload of GIFs with size up to 15mb. See `#538 `_ + +Version 3.4.1 +============= + +Bugfixes: + +* Fix an issue where :py:func:`twitter.twitter_utils.calc_expected_status_length` was failing for python 2 due to a failure to convert a bytes string to unicode. `Github issue #546 `_. + +* Documentation fix for :py:func:`twitter.api.Api.UsersLookup`. UsersLookup can take a string or a list and properly parses both of them now. Github issues `#535 `_ and `#549 `_. + +* Properly decode response content for :py:func:`twitter.twitter_utils.http_to_file`. `Github issue #521 `_. + +* Fix an issue with loading extended_tweet entities from Streaming API where tweets would be truncated when converting to a :py:class:`twitter.models.Status`. Github issues `#491 `_ and `#506 `_. + +Version 3.4 +=========== + +Deprecations +++++++++++++ + +* :py:func:`twitter.api.Api.UpdateBackgroundImage`. Please make sure that your code does not call this function as it will now return a hard error. There is no replacement function. This was deprecated by Twitter around July 2015. + +* :py:func:`twitter.api.Api.PostMedia` has been removed. Please use :py:func:`twitter.api.Api.PostUpdate` instead. + +* :py:func:`twitter.api.Api.PostMultipleMedia`. Please use :py:func:`twitter.api.Api.PostUpdate` instead. + + +Version 3.3.1 +============= + +* Adds support for 280 character limit. + + +Version 3.3 +============= + +* Adds application only authentication. See `Twitter's documentation for details `_. To use application only authentication, pass `application_only_auth` when creating the Api; the bearer token will be automatically retrieved. + +* Adds function :py:func:`twitter.api.GetAppOnlyAuthToken` + +* Adds `filter_level` keyword argument for :py:func:`twitter.api.GetStreamFilter`, :py:func:`twitter.api.GetUserStream` + +* Adds `proxies` keyword argument for creating an Api instance. Pass a dictionary of proxies for the request to pass through, if not specified allows requests lib to use environmental variables for proxy if any. + +* Adds support for `quoted_status` to the :py:class:`twitter.models.Status` model. + + +Version 3.2.1 +============= + +* :py:func:`twitter.twitter_utils.calc_expected_status_length` should now function properly. Previously, URLs would be counted incorrectly. See `PR #416 `_ + +* :py:func:`twitter.api.Api.PostUpdates` now passes any keyword arguments on the edge case that only one tweet was actually being posted. + + +Version 3.2 +=========== + +Deprecations +++++++++++++ + +Nothing is being deprecationed this version, however here's what's being deprecated as of v. 3.3.0: + +* :py:func:`twitter.api.Api.UpdateBackgroundImage`. Please make sure that your code does not call this function as it will be returning a hard error. There is no replace function. This was deprecated by Twitter around July 2015. + +* :py:func:`twitter.api.Api.PostMedia` will be removed. Please use :py:func:`twitter.api.Api.PostUpdate` instead. + +* :py:func:`twitter.api.Api.PostMultipleMedia`. Please use :py:func:`twitter.api.Api.PostUpdate` instead. + +* :py:func:`twitter.api.GetFriends` will no longer accept a `cursor` or `count` parameter. Please use :py:func:`twitter.api.GetFriendsPaged` instead. + +* :py:func:`twitter.api.GetFollowers` will no longer accept a `cursor` or `count` parameter. Please use :py:func:`twitter.api.GetFollowersPaged` instead. + + +What's New +++++++++++ + +* We've added new deprecation warnings, so it's easier to track when things go away. All of python-twitter's deprecation warnings will be a subclass of :py:class:`twitter.error.PythonTwitterDeprecationWarning` and will have a version number associated with them such as :py:class:`twitter.error.PythonTwitterDeprecationWarning330`. + + +* :py:class:`twitter.models.User` now contains a ``following`` attribute, which describes whether the authenticated user is following the User. `PR #351 `_ + +* :py:class:`twitter.models.DirectMessage` contains a full :py:class:`twitter.models.User` object for both the ``DirectMessage.sender`` and ``DirectMessage.recipient`` properties. `PR #384 `_. + +* You can now upload Quicktime movies (``*.mov``). `PR #372 `_. + +* If you have a whitelisted app, you can now get the authenticated user's email address through a call to :py:func:`twitter.api.Api.VerifyCredentials()`. If your app isn't whitelisted, no error is returned. `PR #376 `_. + +* Google App Engine support has been reintegrated into the library. Check out `PR #383 `_. + +* `video_info` is now available on a `twitter.models.Media` object, which allows access to video urls/bitrates/etc. in the `extended_entities` node of a tweet. + +What's Changed +++++++++++++++ + +* :py:class:`twitter.models.Trend`'s `volume` attribute has been renamed `tweet_volume` in line with Twitter's naming convention. This change should allow users to access the number of tweets being tweeted for a given Trend. `PR #375 `_ + +* :py:class:`twitter.ratelimit.RateLimit` should behave better now and adds a 1-second padding to requests after sleeping. + +* :py:class:`twitter.ratelimit.RateLimit` now keeps track of your rate limit status even if you don't have ``sleep_on_rate_limit`` set to ``True`` when instatiating the API. If you want to add different behavior on hitting a rate limit, you should be able to now by querying the rate limit object. See `PR #370 `_ for the technical details of the change. There should be no difference in behavior for the defaults, but let us know. + + +Bugfixes +++++++++ + +* :py:class:`twitter.models.Media` again contains a ``sizes`` attribute, which was missed back in the Version 3.0 release. `PR #360 `_ + +* The previously bloated :py:func:`twitter.api.Api.UploadMediaChunked()` function has been broken out into three related functions and fixes two an incompatibility with python 2.7. Behavior remains the same, but this should simplify matters. `PR #347 `_ + +* Fix for :py:func:`twitter.api.Api.PostUpdate()` where a passing an integer to the ``media`` parameter would cause an iteration error to occur. `PR #347 `_ + +* Fix for 401 errors that were occuring in the Streaming Endpoints. `PR #364 `_ + + + +Version 3.1 +========== + +What's New +++++++++++ + +* :py:func:`twitter.api.Api.PostMediaMetadata()` Method allows the posting of alt text (hover text) to a photo on Twitter. Note that it appears that you have to call this method prior to attaching the photo to a status. + +* A couple new methods have been added related to showing the connections between two users: + + * :py:func:`twitter.api.Api.ShowFriendship()` shows the connection between two users (i.e., are they following each other?) + * :py:func:`twitter.api.Api.IncomingFriendship()` shows all of the authenticated user's pending follower requests (if the user has set their account to private). + * :py:func:`twitter.api.Api.OutgoingFriendship()` shows the authenticated user's request to follow other users (i.e. the user has attempted to follow a private account). + +* Several methods were added related to muting users: + + * :py:func:`twitter.api.Api.GetMutes()` returns **all** users the currently authenticated user is muting (as ``twitter.models.User`` objects). + * :py:func:`twitter.api.Api.GetMutesPaged()` returns a page of ``twitter.models.User`` objects. + * :py:func:`twitter.api.Api.GetMutesIDs()` returns **all** of the users the currently authenticated user is muting as integers. + * :py:func:`twitter.api.Api.GetMutesIDsPaged()` returns a single page of the users the currently authenticated user is muting as integers. + + +What's Changed +++++++++++++++ + +* :py:func:`twitter.api.Api.GetStatus()` Now accepts the keyword argument ``include_ext_alt_text`` which will request alt text to be included with the Status object being returned (if available). Defaults to ``True``. + +* ``[model].__repr__()`` functions have been revised for better Unicode compatibility. If you notice any weirdness, please let us know. + +* :py:func:`twitter.api.Api()` no longer accepts the ``shortner`` parameter; however, see ``examples/shorten_url.py`` for an example of how to use a URL shortener with the API. + +* :py:func:`twitter.api.Api._Encode()` and :py:func:`twitter.api.Api._EncodePostData()` have both been refactored out of the API. + +* :py:class:`twitter.models.Media` now has an attribute ``ext_alt_text`` for alt (hover) text for images posted to Twitter. + +* :py:class:`twitter.models.Status` no longer has the properties ``relative_created_at``, ``now``, or ``Now``. If you require a relative time, we suggest using a third-party library. + +* Updated examples, specifically ``examples/twitter-to-xhtml.py``, ``examples/view_friends.py``, ``examples/shorten_url.py`` + +* Updated ``get_access_token.py`` script to be python3 compatible. + +* :py:func:`twitter.api.Api.GetStreamFilter()` now accepts an optional languages parameter as a list. diff --git a/doc/changes_to_tweet_counting.rst b/doc/changes_to_tweet_counting.rst new file mode 100644 index 00000000..d1c9b249 --- /dev/null +++ b/doc/changes_to_tweet_counting.rst @@ -0,0 +1,79 @@ +REST API Changes +================= + +Information compiled on Sept 14, 2016. + +``statuses/update`` Endpoint +---------------------------- + +``auto_populate_reply_metadata`` ++++++++++++++++++++++++++++++++ + +* Default is ``false`` + +* Must have ``in_reply_to_status_id`` set. + +* Unknown what happens if not set. Probably error (does it get posted?) + +* If the status to which you're replying is deleted, tweet will fail to post. + +``exclude_reply_user_ids`` +++++++++++++++++++++++++++ + +* List of ``user_ids`` to remove from result of ``auto_populate_reply_metadata``. + +* Doesn't apply to the first ``user_id``. + +* If you try to remove it, this will be silently ignored by Twitter. + +``attachment_url`` +++++++++++++++++++ + +* Must be a status permalnk or a DM deep link. + +* If it's anything else and included in this parameter, Twitter will return an error. + + +Most Other Endpoints +-------------------- + +``tweet_mode`` +++++++++++++++ + +* Any endpoint that returns a tweet will accept this param. + +* Must be in ``['compat', 'extended']`` + +* If ``tweet_mode == 'compat'``, then no ``extended_tweet`` node in the json returned. + +* If ``tweet_mode == 'extended'``, then you'll get the ``extended_tweet`` node. + + +Errors +------ +* 44 -> URL passed to attachment_url is invalid + +* 385 -> Replied to deleted tweet or tweet not visible to you + +* 386 -> Too many attachments types (ie a GIF + quote tweet) + + +Streaming API +============= + +Everything is going to be compatibility mode for now; however **all** tweets with have an ``extended_tweet`` node, which will contain the new information. According to Twitter's documentation though, there's the possibility that this node may not exist. We should be careful about making assumptions here. + + +Changes to Models +================= + +Classic tweet: tweet with length < 140 char. +Extended tweet: tweet with extended entities and text > 140 chars. + +Twitter doesn't say if extended tweet with a total length of < 140 characters will be considered a "Classic tweet". They also state that an extended tweet shall have "text content [that] exceeds 140 characters in length", however this is contradictory to earlier statements about total text length retaining a hard max at 140 characters. + +There will be two rendering modes: Compatibility and Extended. If in compatibility mode and tweet is "classic", no changes to tweet JSON. If in Extended mode, the following will change: + +* ``text`` -> truncated version of the extended tweet's text + "..." + permalink to tweet. (Twitter is mute on whether an extended tweet's with (text + @mentions + urls) < 140 characters will have the @mentions + urls put back in ``text`` field.) + +* ``truncated`` -> gets set to ``True`` if extended tweet is rendered in compat mode. diff --git a/doc/conf.py b/doc/conf.py new file mode 100644 index 00000000..2121447d --- /dev/null +++ b/doc/conf.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# +# python-twitter documentation build configuration file, created by +# sphinx-quickstart on Fri Aug 30 14:37:05 2013. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +sys.path.append(os.path.abspath('../')) + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.coverage', + 'sphinx.ext.viewcode', + 'sphinx.ext.napoleon' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'python-twitter' +copyright = u'2016, python-twitter@googlegroups.com' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '3.4' +# The full version, including alpha/beta/rc tags. +release = '3.4.2' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'python-twitterdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + #'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'python-twitter.tex', u'python-twitter Documentation', + u'python-twitter@googlegroups.com', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'python-twitter', u'python-twitter Documentation', + [u'python-twitter@googlegroups.com'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'python-twitter', u'python-twitter Documentation', + u'python-twitter@googlegroups.com', 'python-twitter', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/doc/contributing.rst b/doc/contributing.rst new file mode 100644 index 00000000..8f6f0874 --- /dev/null +++ b/doc/contributing.rst @@ -0,0 +1,37 @@ +Contributing +------------ + +Getting the code +================ + +The code is hosted at `Github `_. + +Check out the latest development version anonymously with:: + + $ git clone git://github.com/bear/python-twitter.git + $ cd python-twitter + +The following sections assuming that you have `pyenv +`_ installed and working on your computer. + +To install dependencies, run:: + + $ make dev + +This will install all of the required packages for the core library, testing, +and installation. + +Testing +======= + +Once you have your development environment set up, you can run:: + + $ make test + +to ensure that all tests are currently passing before starting work. You can +also check test coverage by running:: + + $ make coverage + +Pull requests are welcome or, if you are having trouble, please open an issue on +GitHub. diff --git a/doc/getting_started.rst b/doc/getting_started.rst new file mode 100644 index 00000000..b5044a18 --- /dev/null +++ b/doc/getting_started.rst @@ -0,0 +1,57 @@ +Getting Started +=============== + +Getting your application tokens ++++++++++++++++++++++++++++++++ + +.. danger:: + +This section is subject to changes made by Twitter and may not always be completely up-to-date. If you see something change on their end, please create a `new issue on Github `_ or submit a pull request to update it. + + +In order to use the python-twitter API client, you first need to acquire a set of application tokens. These will be your ``consumer_key`` and ``consumer_secret``, which get passed to ``twitter.Api()`` when starting your application. + +Create your app +________________ + +The first step in doing so is to create a `Twitter App `_. Click the "Create New App" button and fill out the fields on the next page. + + +.. image:: python-twitter-app-creation-part1.png + +If there are any problems with the information on that page, Twitter will complain and you can fix it. (Make sure to get the name correct - it is unclear if you can change this later.) On the next screen, you'll see the application that you created and some information about it: + +Your app +_________ + +Once your app is created, you'll be directed to a new page showing you some information about it. + +.. image:: python-twitter-app-creation-part2-new.png + +Your Keys +_________ + +Click on the "Keys and Access Tokens" tab on the top. + + +.. image:: python-twitter-app-creation-part3-new.png + + +Under the "Access token & access token secret" option, click on the "create" button to generate a new access token and token secret. + +.. image:: python-twitter-app-creation-part3-1-new.png + + +At this point, you can test out your application using the keys under "Your Application Tokens". The ``twitter.Api()`` object can be created as follows:: + + import twitter + api = twitter.Api(consumer_key=, + consumer_secret=, + access_token_key=, + access_token_secret=) + +Note: Make sure to enclose your keys in quotes (ie, api = twitter.Api(consumer_key='1234567', ...) and so on) or you will receive a NameError. + +If you are creating an application for end users/consumers, then you will want them to authorize your application, but that is outside the scope of this document. + +And that should be it! If you need a little more help, check out the `examples on Github `_. If you have an open source application using python-twitter, send us a link and we'll add a link to it here. diff --git a/doc/index.rst b/doc/index.rst new file mode 100644 index 00000000..11297339 --- /dev/null +++ b/doc/index.rst @@ -0,0 +1,39 @@ +.. python-twitter documentation master file, created by + +Welcome to python-twitter's documentation! +========================================== +**A Python wrapper around the Twitter API.** + +Author: The Python-Twitter Developers + + +Contents: + +.. toctree:: + :maxdepth: 1 + + installation.rst + getting_started.rst + contributing.rst + migration_v30.rst + changelog.rst + rate_limits.rst + models.rst + searching.rst + with_django.rst + twitter.rst + + +Introduction +------------ +This library provides a pure Python interface for the `Twitter API `_. It works with Python 2.7+ and Python 3. + +`Twitter `_ provides a service that allows people to connect via the web, IM, and SMS. Twitter exposes a `web services API `_ and this library is intended to make it even easier for Python programmers to use. + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/doc/installation.rst b/doc/installation.rst new file mode 100644 index 00000000..2e64eb6b --- /dev/null +++ b/doc/installation.rst @@ -0,0 +1,51 @@ +Installation & Testing +------------ + +Installation +============ + +**From PyPI** :: + + $ pip install python-twitter + + +**From source** + +Install the dependencies: + +- `Requests `_ +- `Requests OAuthlib `_ + +Alternatively use `pip`:: + + $ pip install -r requirements.txt + +Download the latest `python-twitter` library from: https://github.com/bear/python-twitter/ + +Extract the source distribution and run:: + + $ python setup.py build + $ python setup.py install + + +Testing +======= + +The following requires ``pip install pytest`` and ``pip install pytest-cov``. Run:: + + $ make test + +If you would like to see coverage information:: + + $ make coverage + + +Getting the code +================ + +The code is hosted at `Github `_. + +Check out the latest development version anonymously with:: + +$ git clone git://github.com/bear/python-twitter.git +$ cd python-twitter diff --git a/doc/make.bat b/doc/make.bat new file mode 100644 index 00000000..595cd0d1 --- /dev/null +++ b/doc/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-twitter.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-twitter.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/doc/migration_v30.rst b/doc/migration_v30.rst new file mode 100644 index 00000000..81a80f2f --- /dev/null +++ b/doc/migration_v30.rst @@ -0,0 +1,153 @@ +Migration from v2 to v3 +----------------------- + +Changes to Existing Methods +=========================== + +:py:func:`twitter.api.Api()` +++++++++++++++++++++++++++++ +* ``shortner`` parameter has been removed. Please see `Issue + #298 `_. + +:py:func:`twitter.api.Api.CreateFavorite` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* kwarg param has been changed to ``status_id`` from ``id`` to be consistent + with other method calls and avoid shadowing builtin function ``id``. + +:py:func:`twitter.api.Api.DestroyFavorite` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* kwarg param has been changed to ``status_id`` from ``id`` to be consistent + with other method calls and avoid shadowing builtin function ``id``. + +:py:func:`twitter.api.Api.DestroyBlock` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Kwarg ``id`` has been changed to ``user_id`` in order to avoid shadowing + a builtin and be more descriptive. + +:py:func:`twitter.api.Api.DestroyStatus` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* kwarg ``id`` has been changed to ``status_id`` in keeping with the rest of + the Api and to avoid shadowing a builtin. + +:py:func:`twitter.api.Api.GetBlocks` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Method no longer accepts parameters ``user_id`` or ``screen_name`` as these are not honored by Twitter. The data returned will be for the authenticated user only. +* Parameter ``cursor`` is no longer accepted -- this method will return **all** users being blocked by the currently authenticated user. If you need paging, please use :py:func:`twitter.api.Api.GetBlocksPaged` instead. + +:py:func:`twitter.api.Api.GetFollowers` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Method no longer honors a ``count`` or ``cursor`` parameter. These have been deprecated in favor of making this method explicitly a convenience function to return a list of every ``twitter.User`` who is following the specified or authenticated user. A warning will be raised if ``count`` or ``cursor`` is passed with the expectation that breaking behavior will be introduced in a later version. +* Method now takes an optional parameter of ``total_count``, which limits the number of users to return. If this is not set, the data returned will be all users following the specified user. +* The kwarg ``include_user_entities`` now defaults to ``True``. This was set to ``False`` previously, but would not be included in query parameters sent to Twitter. Without the query parameter in the URL, Twitter would default to returning user_entities, so this change makes this behavior explicit. + +:py:func:`twitter.api.Api.GetFollowersPaged` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* The third value of the tuple returned by this method is now a list of twitter.User objects in accordance with its doc string rather than the raw data from API. +* The kwarg ``include_user_entities`` now defaults to ``True``. This was set to ``False`` previously, but would not be included in query parameters sent to Twitter. Without the query parameter in the URL, Twitter would default to returning user_entities, so this change makes this behavior explicit and consistent with the previously ambiguous behavior. + +:py:func:`twitter.api.Api.GetFriends` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Method no longer honors a ``count`` or ``cursor`` parameter. These have been deprecated in favor of making this method explicitly a convenience function to return a list of every ``twitter.User`` who is followed by the specified or authenticated user. A warning will be raised if ``count`` or ``cursor`` is passed with the expectation that breaking behavior will be introduced in a later version. +* Method now takes an optional parameter of ``total_count``, which limits the number of users to return. If this is not set, the data returned will be all users followed by the specified user. +* The kwarg ``include_user_entities`` now defaults to ``True``. This was set to ``False`` previously, but would not be included in query parameters sent to Twitter. Without the query parameter in the URL, Twitter would default to returning user_entities, so this change makes this behavior explicit. + +:py:func:`twitter.api.Api.GetFriendsPaged` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* The third value of the tuple returned by this method is now a list of twitter.User objects in accordance with its doc string rather than the raw data from API. +* The kwarg ``include_user_entities`` now defaults to ``True``. This was set to ``False`` previously, but would not be included in query parameters sent to Twitter. Without the query parameter in the URL, Twitter would default to returning user_entities, so this change makes this behavior explicit. + +:py:func:`twitter.api.Api.GetListMembers` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* No longer accepts ``cursor`` parameter. If you require granular control over the paging of the twitter.list.List members, please user twitter.api.Api.GetListMembersPaged instead. + +:py:func:`twitter.api.Api.GetStatus` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Kwarg ``id`` has been changed to ``status_id`` in keeping with the rest of + the Api and to avoid shadowing a builtin. + +:py:func:`twitter.api.Api.GetStatusOembed` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Kwarg ``id`` has been changed to ``status_id`` in keeping with the rest of + the Api and to avoid shadowing a builtin. + +:py:func:`twitter.api.Api.GetSearch` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Adds ``raw_query`` method. See :ref:`raw_queries` for more information. + + +:py:func:`twitter.api.Api.GetTrendsWoeid` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Kwarg ``id`` has been changed to ``woeid`` in order to avoid shadowing + a builtin and be more descriptive. + +:py:func:`twitter.api.Api.GetUserStream` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Parameter 'stall_warning' is now 'stall_warnings' in line with GetStreamFilter and Twitter's naming convention. This should now actually return stall warnings, whereas it did not have any effect previously. + +:py:func:`twitter.api.Api.LookupFriendship` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Method will now accept a list for either ``user_id`` or ``screen_name``. The list can contain either ints, strings, or :py:mod:`twitter.user.User` objects for either ``user_id`` or ``screen_name``. +* Return value is a list of :py:mod:`twitter.user.UserStatus` objects. + +:py:func:`twitter.api.Api.PostUpdate` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Now accepts three new parameters: ``media``, ``media_additional_owners``, and ``media_category``. ``media`` can be a URL, a local file, or a file-like object (something with a ``read()`` method), or a list of any combination of the above. +* ``media_additional_owners`` should be a list of user ids representing Twitter users that should be able to use the uploaded media in their tweets. If you pass a list of media, then **additional owners will apply to each object.** If you need more granular control, please use the UploadMedia* methods. +* ``media_category``: Only for use with the AdsAPI. See https://dev.twitter.com/ads/creative/promoted-video-overview if this applies to your application. + +:py:func:`twitter.api.Api.PostRetweet` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Kwarg ``original_id`` has been changed to ``status_id`` in order to avoid shadowing + a builtin and be more descriptive. + +Deprecation +=========== + +:py:func:`twitter.api.Api.PostMedia` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* This endpoint is deprecated by Twitter. Python-twitter will throw a warning about using the method and advise you to use PostUpdate() instead. There is no schedule for when this will be removed from Twitter. + +:py:func:`twitter.api.Api.PostMultipleMedia` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* This method should be replaced by passing a list of media objects (either URLs, local files, or file-like objects) to PostUpdate. You are limited to a maximum of 4 media files per tweet. + + +New Methods +=========== + +:py:func:`twitter.api.Api.GetBlocksIDs` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Returns **all** the users currently blocked by the authenticated user as user IDs. The user IDs will be integers. + +:py:func:`twitter.api.Api.GetBlocksIDsPaged` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Returns one page, specified by the cursor parameter, of the users currently blocked by the authenticated user as user IDs. + +:py:func:`twitter.api.Api.GetBlocksPaged` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Allows you to page through the currently authenticated user's blocked users. Method returns three values: the next cursor, the previous cursor, and a list of ``twitter.User`` instances representing the blocked users. + +:py:func:`twitter.api.Api.GetListMembersPaged` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Allows you to page through a the members of a given twitter.list.List. +* ``cursor`` parameter operates as with other methods, denoting the page of members that you wish to retrieve. +* Returns ``next_cursor``, ``previous_cursor``, and a list containing the users that are members of the given twitter.list.List. + + +:py:func:`twitter.api.Api.GetListsPaged` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Much like :py:func:`twitter.api.Api.GetFriendsPaged` and similar methods, this allows you to retrieve an arbitrary page of :py:mod:`twitter.list.List` for either the currently authenticated user or a user specified by ``user_id`` or ``screen_name``. +* ``cursor`` should be ``-1`` for the first page. +* Returns the ``next_cursor``, ``previous_cursor``, and a list of :py:mod:`twitter.list.List` instances. + +:py:func:`twitter.api.Api.UploadMediaChunked` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* API method allows chunked upload to upload.twitter.com. Similar to Api.PostMedia(), this method can take either a local filename (str), a URL (str), or a file-like object. The image or video type will be determined by ``mimetypes`` (see :py:func:`twitter.twitter_utils.parse_media_file` for details). +* Optionally, you can specify a chunk_size for uploads when instantiating the Api object. This should be given in bytes. The default is 1MB (that is, 1048576 bytes). Any chunk_size given below 16KB will result in a warning: Twitter will return an error if you try to upload more than 999 chunks of data; for example, if you are uploading a 15MB video, then a chunk_size lower than 15729 bytes will result in 1000 APPEND commands being sent to the API, so you'll get an error. 16KB seems like a reasonable lower bound, but if your use case is well-defined, then python-twitter will not enforce this behavior. +* Another thing to take into consideration: if you're working in a RAM-constrained environment, a very large chunk_size will increase your RAM usage when uploading media through this endpoint. +* The return value will be the ``media_id`` of the uploaded file. + +:py:func:`twitter.api.Api.UploadMediaSimple` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +* Provides the ability to upload a single media file to Twitter without using the ChunkedUpload endpoint. This method should be used on smaller files and reduces the roundtrips from Twitter from three (for UploadMediaChunked) to one. +* Return value is the ``media_id`` of the uploaded file. diff --git a/doc/models.rst b/doc/models.rst new file mode 100644 index 00000000..5e981e8f --- /dev/null +++ b/doc/models.rst @@ -0,0 +1,15 @@ +Models +====== + +Python-twitter provides the following models of the objects returned by the Twitter API: + +* :py:class:`twitter.models.Category` +* :py:class:`twitter.models.DirectMessage` +* :py:class:`twitter.models.Hashtag` +* :py:class:`twitter.models.List` +* :py:class:`twitter.models.Media` +* :py:class:`twitter.models.Status` +* :py:class:`twitter.models.Trend` +* :py:class:`twitter.models.Url` +* :py:class:`twitter.models.User` +* :py:class:`twitter.models.UserStatus` diff --git a/doc/modules.rst b/doc/modules.rst new file mode 100644 index 00000000..aa26b462 --- /dev/null +++ b/doc/modules.rst @@ -0,0 +1,10 @@ +.. _modules: + +Modules +******* + +.. toctree:: + :maxdepth: 4 + + twitter + diff --git a/doc/python-twitter-app-creation-part1.png b/doc/python-twitter-app-creation-part1.png new file mode 100644 index 00000000..1686de68 Binary files /dev/null and b/doc/python-twitter-app-creation-part1.png differ diff --git a/doc/python-twitter-app-creation-part2-new.png b/doc/python-twitter-app-creation-part2-new.png new file mode 100644 index 00000000..f88e18b7 Binary files /dev/null and b/doc/python-twitter-app-creation-part2-new.png differ diff --git a/doc/python-twitter-app-creation-part2.png b/doc/python-twitter-app-creation-part2.png new file mode 100644 index 00000000..9ab561fc Binary files /dev/null and b/doc/python-twitter-app-creation-part2.png differ diff --git a/doc/python-twitter-app-creation-part3-1-new.png b/doc/python-twitter-app-creation-part3-1-new.png new file mode 100644 index 00000000..3de5bf44 Binary files /dev/null and b/doc/python-twitter-app-creation-part3-1-new.png differ diff --git a/doc/python-twitter-app-creation-part3-new.png b/doc/python-twitter-app-creation-part3-new.png new file mode 100644 index 00000000..739d6162 Binary files /dev/null and b/doc/python-twitter-app-creation-part3-new.png differ diff --git a/doc/python-twitter-app-creation-part3.png b/doc/python-twitter-app-creation-part3.png new file mode 100644 index 00000000..9c29b360 Binary files /dev/null and b/doc/python-twitter-app-creation-part3.png differ diff --git a/doc/rate_limits.rst b/doc/rate_limits.rst new file mode 100644 index 00000000..c6e3cf67 --- /dev/null +++ b/doc/rate_limits.rst @@ -0,0 +1,83 @@ +Rate Limiting +------------- + +Overview +++++++++ + +Twitter imposes rate limiting based either on user tokens or application +tokens. Please see: `API Rate Limits +`_ for a more detailed +explanation of Twitter's policies. What follows will be a summary of how Python-Twitter attempts to +deal with rate limits and how you should expect those limits to be respected +(or not). + + +Python-Twitter tries to abstract away the details of Twitter's rate limiting by +allowing you to globally respect those limits or ignore them. If you wish to +have the application sleep when it hits a rate limit, you should instantiate +the API with ``sleep_on_rate_limit=True`` like so:: + + import twitter + api = twitter.Api(consumer_key=[consumer key], + consumer_secret=[consumer secret], + access_token_key=[access token], + access_token_secret=[access token secret], + sleep_on_rate_limit=True) + +**By default, python-twitter will raise a hard error for rate limits** + +Effectively, when the API determines that the **next** call to an endpoint will +result in a rate limit error being thrown by Twitter, it will sleep until you +are able to safely make that call. For most API methods, the headers in the +response from Twitter will contain the following information: + + ``x-rate-limit-limit``: The number of times you can request the given + endpoint within a certain number of minutes (otherwise known as a window). + + ``x-rate-limit-remaining``: The number of times you have left for a given endpoint within a window. + + ``x-rate-limit-reset``: The number of seconds left until the window resets. + +For most endpoints, this is 15 requests per 15 minutes. So if you have set the +global ``sleep_on_rate_limit`` to ``True``, the process looks something like this:: + + api.GetListMembersPaged() + # GET /list/{id}/members.json?cursor=-1 + # GET /list/{id}/members.json?cursor=2 + # GET /list/{id}/members.json?cursor=3 + # GET /list/{id}/members.json?cursor=4 + # GET /list/{id}/members.json?cursor=5 + # GET /list/{id}/members.json?cursor=6 + # GET /list/{id}/members.json?cursor=7 + # GET /list/{id}/members.json?cursor=8 + # GET /list/{id}/members.json?cursor=9 + # GET /list/{id}/members.json?cursor=10 + # GET /list/{id}/members.json?cursor=11 + # GET /list/{id}/members.json?cursor=12 + # GET /list/{id}/members.json?cursor=13 + # GET /list/{id}/members.json?cursor=14 + + # This last GET request returns a response where x-rate-limit-remaining + # is equal to 0, so the API sleeps for 15 minutes + + # GET /list/{id}/members.json?cursor=15 + + # ... etc ... + +If you would rather not have your API instance sleep when hitting, then do not +pass ``sleep_on_rate_limit=True`` to your API instance. This will cause the API +to raise a hard error when attempting to make call #15 above. + +Technical ++++++++++ + +The ``twitter/ratelimit.py`` file contains the code that handles storing and +checking rate limits for endpoints. Since Twitter does not send any information +regarding the endpoint that you are requesting with the ``x-rate-limit-*`` +headers, the endpoint is determined by some regex using the URL. + +The twitter.Api instance contains an ``Api.rate_limit`` object that you can inspect +to see the current limits for any URL and exposes a number of methods for +querying and setting rate limits on a per-resource (i.e., endpoint) basis. See +:py:func:`twitter.ratelimit.RateLimit` for more information. + diff --git a/doc/searching.rst b/doc/searching.rst new file mode 100644 index 00000000..b569dc5e --- /dev/null +++ b/doc/searching.rst @@ -0,0 +1,19 @@ +.. _searching: + +Searching ++++++++++ + + +.. _raw_queries: + +Raw Queries +=========== + +To the ``Api.GetSearch()`` method, you can pass the parameter ``raw_query``, which should be the query string you wish to use for the search **omitting the leading "?"**. This will override every other parameter. Twitter's search parameters are quite complex, so if you have a need for a very particular search, you can find Twitter's documentation at https://dev.twitter.com/rest/public/search. + +For example, if you want to search for only tweets containing the word "twitter", then you could do the following: :: + + results = api.GetSearch( + raw_query="q=twitter%20&result_type=recent&since=2014-07-19&count=100") + +If you want to build a search query and you're not quite sure how it should look all put together, you can use Twitter's Advanced Search tool: https://twitter.com/search-advanced, and then use the part of search URL after the "?" to use for the Api, removing the ``&src=typd`` portion. diff --git a/doc/twitter.html b/doc/twitter.html index 9ce5acca..9218cb80 100644 --- a/doc/twitter.html +++ b/doc/twitter.html @@ -1,1999 +1,3080 @@ -Python: module twitter - + +Python: module twitter + + - -
 
- 
twitter (version 0.8)
index
twitter.py
-

A library that provides a Python interface to the Twitter API

+ +  
+  
twitter + (version 0.8)
+ index
twitter.py
+ + +

+ A library that provides a Python interface to the Twitter API +

+

- - - - -
 
-Modules
       
StringIO
-base64
-calendar
-datetime
-gzip
-
httplib
-oauth2
-os
-rfc822
-json
-
sys
-tempfile
-textwrap
-time
-urllib
-
urllib2
-urlparse
-

- - - - - - + + + + + + + + +
 
-Classes
       
-
__builtin__.object -
-
-
Api -
DirectMessage -
Hashtag -
List -
Status -
Trend -
Url -
User -
-
-
exceptions.Exception(exceptions.BaseException) -
-
-
TwitterError -
-
-
-

- - - - - - - -
 
-class Api(__builtin__.object)
   A python interface into the Twitter API

-By default, the Api caches results for 1 minute.

-Example usage:

-  To create an instance of the twitter.Api class, with no authentication:

-    >>> import twitter
-    >>> api = twitter.Api()

-  To fetch a single user's public status messages, where "user" is either
-  a Twitter "short name" or their user id.

-    >>> statuses = api.GetUserTimeline(user)
-    >>> print [s.text for s in statuses]

-  To use authentication, instantiate the twitter.Api class with a
-  consumer key and secret; and the oAuth key and secret:

-    >>> api = twitter.Api(consumer_key='twitter consumer key',
-                          consumer_secret='twitter consumer secret',
-                          access_token_key='the_key_given',
-                          access_token_secret='the_key_secret')

-  To fetch your friends (after being authenticated):

-    >>> users = api.GetFriends()
-    >>> print [u.name for u in users]

-  To post a twitter status message (after being authenticated):

-    >>> status = api.PostUpdate('I love python-twitter!')
-    >>> print status.text
-    I love python-twitter!

-  There are many other methods, including:

-    >>> api.PostUpdates(status)
-    >>> api.PostDirectMessage(user, text)
-    >>> api.GetUser(user)
-    >>> api.GetReplies()
-    >>> api.GetUserTimeline(user)
-    >>> api.GetStatus(id)
-    >>> api.DestroyStatus(id)
-    >>> api.GetFriendsTimeline(user)
-    >>> api.GetFriends(user)
-    >>> api.GetFollowers()
-    >>> api.GetFeatured()
-    >>> api.GetDirectMessages()
-    >>> api.PostDirectMessage(user, text)
-    >>> api.DestroyDirectMessage(id)
-    >>> api.DestroyFriendship(user)
-    >>> api.CreateFriendship(user)
-    >>> api.GetUserByEmail(email)
-    >>> api.VerifyCredentials()
 
 Methods defined here:
-
ClearCredentials(self)
Clear the any credentials for this instance
- -
CreateFavorite(self, status)
Favorites the status specified in the status parameter as the authenticating user.
-Returns the favorite status when successful.

-The twitter.Api instance must be authenticated.

-Args:
-  The twitter.Status instance to mark as a favorite.
-Returns:
-  A twitter.Status instance representing the newly-marked favorite.
- -
CreateFriendship(self, user)
Befriends the user specified in the user parameter as the authenticating user.

-The twitter.Api instance must be authenticated.

-Args:
-  The ID or screen name of the user to befriend.
-Returns:
-  A twitter.User instance representing the befriended user.
- -
CreateList(self, user, name, mode=None, description=None)
Creates a new list with the give name

-The twitter.Api instance must be authenticated.

-Args:
-  user:
-    Twitter name to create the list for
-  name:
-    New name for the list
-  mode:
-    'public' or 'private'.
-    Defaults to 'public'. [Optional]
-  description:
-    Description of the list. [Optional]

-Returns:
-  A twitter.List instance representing the new list
- -
CreateSubscription(self, owner, list)
Creates a subscription to a list by the authenticated user

-The twitter.Api instance must be authenticated.

-Args:
-  owner:
-    User name or id of the owner of the list being subscribed to.
-  list:
-    The slug or list id to subscribe the user to

-Returns:
-  A twitter.List instance representing the list subscribed to
- -
DestroyDirectMessage(self, id)
Destroys the direct message specified in the required ID parameter.

-The twitter.Api instance must be authenticated, and the
-authenticating user must be the recipient of the specified direct
-message.

-Args:
-  id: The id of the direct message to be destroyed

-Returns:
-  A twitter.DirectMessage instance representing the message destroyed
- -
DestroyFavorite(self, status)
Un-favorites the status specified in the ID parameter as the authenticating user.
-Returns the un-favorited status in the requested format when successful.

-The twitter.Api instance must be authenticated.

-Args:
-  The twitter.Status to unmark as a favorite.
-Returns:
-  A twitter.Status instance representing the newly-unmarked favorite.
- -
DestroyFriendship(self, user)
Discontinues friendship with the user specified in the user parameter.

-The twitter.Api instance must be authenticated.

-Args:
-  The ID or screen name of the user  with whom to discontinue friendship.
-Returns:
-  A twitter.User instance representing the discontinued friend.
- -
DestroyList(self, user, id)
Destroys the list from the given user

-The twitter.Api instance must be authenticated.

-Args:
-  user:
-    The user to remove the list from.
-  id:
-    The slug or id of the list to remove.
-Returns:
-  A twitter.List instance representing the removed list.
- -
DestroyStatus(self, id)
Destroys the status specified by the required ID parameter.

-The twitter.Api instance must be authenticated and the
-authenticating user must be the author of the specified status.

-Args:
-  id:
-    The numerical ID of the status you're trying to destroy.

-Returns:
-  A twitter.Status instance representing the destroyed status message
- -
DestroySubscription(self, owner, list)
Destroys the subscription to a list for the authenticated user

-The twitter.Api instance must be authenticated.

-Args:
-  owner:
-    The user id or screen name of the user that owns the
-    list that is to be unsubscribed from
-  list:
-    The slug or list id of the list to unsubscribe from

-Returns:
-  A twitter.List instance representing the removed list.
- -
FilterPublicTimeline(self, term, since_id=None)
Filter the public twitter timeline by a given search term on
-the local machine.

-Args:
-  term:
-    term to search by.
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]

-Returns:
-  A sequence of twitter.Status instances, one for each message
-  containing the term
- -
GetDirectMessages(self, since=None, since_id=None, page=None)
Returns a list of the direct messages sent to the authenticating user.

-The twitter.Api instance must be authenticated.

-Args:
-  since:
-    Narrows the returned results to just those statuses created
-    after the specified HTTP-formatted date. [Optional]
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]

-Returns:
-  A sequence of twitter.DirectMessage instances
- -
GetFavorites(self, user=None, page=None)
Return a list of Status objects representing favorited tweets.
-By default, returns the (up to) 20 most recent tweets for the
-authenticated user.

-Args:
-  user:
-    The twitter name or id of the user whose favorites you are fetching.
-    If not specified, defaults to the authenticated user. [Optional]
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]
- -
GetFeatured(self)
Fetch the sequence of twitter.User instances featured on twitter.com

-The twitter.Api instance must be authenticated.

-Returns:
-  A sequence of twitter.User instances
- -
GetFollowerIDs(self, userid=None, cursor=-1)
Fetch the sequence of twitter.User instances, one for each follower

-The twitter.Api instance must be authenticated.

-Returns:
-  A sequence of twitter.User instances, one for each follower
- -
GetFollowers(self, page=None)
Fetch the sequence of twitter.User instances, one for each follower

-The twitter.Api instance must be authenticated.

-Args:
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]

-Returns:
-  A sequence of twitter.User instances, one for each follower
- -
GetFriendIDs(self, user=None, cursor=-1)
Returns a list of twitter user id's for every person
-the specified user is following.

-Args:
-  user:
-    The id or screen_name of the user to retrieve the id list for
-    [Optional]

-Returns:
-  A list of integers, one for each user id.
- -
GetFriends(self, user=None, cursor=-1)
Fetch the sequence of twitter.User instances, one for each friend.

-The twitter.Api instance must be authenticated.

-Args:
-  user:
-    The twitter name or id of the user whose friends you are fetching.
-    If not specified, defaults to the authenticated user. [Optional]

-Returns:
-  A sequence of twitter.User instances, one for each friend
- -
GetFriendsTimeline(self, user=None, count=None, page=None, since_id=None, retweets=None, include_entities=None)
Fetch the sequence of twitter.Status messages for a user's friends

-The twitter.Api instance must be authenticated if the user is private.

-Args:
-  user:
-    Specifies the ID or screen name of the user for whom to return
-    the friends_timeline.  If not specified then the authenticated
-    user set in the twitter.Api instance will be used.  [Optional]
-  count:
-    Specifies the number of statuses to retrieve. May not be
-    greater than 100. [Optional]
-  page:
-     Specifies the page of results to retrieve.
-     Note: there are pagination limits. [Optional]
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  retweets:
-    If True, the timeline will contain native retweets. [Optional]
-  include_entities:
-    If True, each tweet will include a node called "entities,".
-    This node offers a variety of metadata about the tweet in a
-    discreet structure, including: user_mentions, urls, and
-    hashtags. [Optional]

-Returns:
-  A sequence of twitter.Status instances, one for each message
- -
GetLists(self, user, cursor=-1)
Fetch the sequence of lists for a user.

-The twitter.Api instance must be authenticated.

-Args:
-  user:
-    The twitter name or id of the user whose friends you are fetching.
-    If the passed in user is the same as the authenticated user
-    then you will also receive private list data.
-  cursor:
-    "page" value that Twitter will use to start building the
-    list sequence from.  -1 to start at the beginning.
-    Twitter will return in the result the values for next_cursor
-    and previous_cursor. [Optional]

-Returns:
-  A sequence of twitter.List instances, one for each list
- -
GetMentions(self, since_id=None, max_id=None, page=None)
Returns the 20 most recent mentions (status containing @twitterID)
-for the authenticating user.

-Args:
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  max_id:
-    Returns only statuses with an ID less than
-    (that is, older than) the specified ID.  [Optional]
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]

-Returns:
-  A sequence of twitter.Status instances, one for each mention of the user.
- -
GetRateLimitStatus(self)
Fetch the rate limit status for the currently authorized user.

-Returns:
-  A dictionary containing the time the limit will reset (reset_time),
-  the number of remaining hits allowed before the reset (remaining_hits),
-  the number of hits allowed in a 60-minute period (hourly_limit), and
-  the time of the reset in seconds since The Epoch (reset_time_in_seconds).
- -
GetReplies(self, since=None, since_id=None, page=None)
Get a sequence of status messages representing the 20 most
-recent replies (status updates prefixed with @twitterID) to the
-authenticating user.

-Args:
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]
-  since:

-Returns:
-  A sequence of twitter.Status instances, one for each reply to the user.
- -
GetRetweets(self, statusid)
Returns up to 100 of the first retweets of the tweet identified
-by statusid

-Args:
-  statusid:
-    The ID of the tweet for which retweets should be searched for

-Returns:
-  A list of twitter.Status instances, which are retweets of statusid
- -
GetSearch(self, term, geocode=None, since_id=None, per_page=15, page=1, lang='en', show_user='true', query_users=False)
Return twitter search results for a given term.

-Args:
-  term:
-    term to search by.
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  geocode:
-    geolocation information in the form (latitude, longitude, radius)
-    [Optional]
-  per_page:
-    number of results to return.  Default is 15 [Optional]
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]
-  lang:
-    language for results.  Default is English [Optional]
-  show_user:
-    prefixes screen name in status
-  query_users:
-    If set to False, then all users only have screen_name and
-    profile_image_url available.
-    If set to True, all information of users are available,
-    but it uses lots of request quota, one per status.

-Returns:
-  A sequence of twitter.Status instances, one for each message containing
-  the term
- -
GetStatus(self, id)
Returns a single status message.

-The twitter.Api instance must be authenticated if the
-status message is private.

-Args:
-  id:
-    The numeric ID of the status you are trying to retrieve.

-Returns:
-  A twitter.Status instance representing that status message
- -
GetSubscriptions(self, user, cursor=-1)
Fetch the sequence of Lists that the given user is subscribed to

-The twitter.Api instance must be authenticated.

-Args:
-  user:
-    The twitter name or id of the user
-  cursor:
-    "page" value that Twitter will use to start building the
-    list sequence from.  -1 to start at the beginning.
-    Twitter will return in the result the values for next_cursor
-    and previous_cursor. [Optional]

-Returns:
-  A sequence of twitter.List instances, one for each list
- -
GetTrendsCurrent(self, exclude=None)
Get the current top trending topics

-Args:
-  exclude:
-    Appends the exclude parameter as a request parameter.
-    Currently only exclude=hashtags is supported. [Optional]

-Returns:
-  A list with 10 entries. Each entry contains the twitter.
- -
GetTrendsDaily(self, exclude=None, startdate=None)
Get the current top trending topics for each hour in a given day

-Args:
-  startdate:
-    The start date for the report.
-    Should be in the format YYYY-MM-DD. [Optional]
-  exclude:
-    Appends the exclude parameter as a request parameter.
-    Currently only exclude=hashtags is supported. [Optional]

-Returns:
-  A list with 24 entries. Each entry contains the twitter.
-  Trend elements that were trending at the corresponding hour of the day.
- -
GetTrendsWeekly(self, exclude=None, startdate=None)
Get the top 30 trending topics for each day in a given week.

-Args:
-  startdate:
-    The start date for the report.
-    Should be in the format YYYY-MM-DD. [Optional]
-  exclude:
-    Appends the exclude parameter as a request parameter.
-    Currently only exclude=hashtags is supported. [Optional]
-Returns:
-  A list with each entry contains the twitter.
-  Trend elements of trending topics for the corrsponding day of the week
- -
GetUser(self, user)
Returns a single user.

-The twitter.Api instance must be authenticated.

-Args:
-  user: The twitter name or id of the user to retrieve.

-Returns:
-  A twitter.User instance representing that user
- -
GetUserByEmail(self, email)
Returns a single user by email address.

-Args:
-  email:
-    The email of the user to retrieve.

-Returns:
-  A twitter.User instance representing that user
- -
GetUserRetweets(self, count=None, since_id=None, max_id=None, include_entities=False)
Fetch the sequence of retweets made by a single user.

-The twitter.Api instance must be authenticated.

-Args:
-  count:
-    The number of status messages to retrieve. [Optional]
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  max_id:
-    Returns results with an ID less than (that is, older than) or
-    equal to the specified ID. [Optional]
-  include_entities:
-    If True, each tweet will include a node called "entities,".
-    This node offers a variety of metadata about the tweet in a
-    discreet structure, including: user_mentions, urls, and
-    hashtags. [Optional]

-Returns:
-  A sequence of twitter.Status instances, one for each message up to count
- -
GetUserTimeline(self, id=None, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, page=None, include_rts=None, include_entities=None)
Fetch the sequence of public Status messages for a single user.

-The twitter.Api instance must be authenticated if the user is private.

-Args:
-  id:
-    Specifies the ID or screen name of the user for whom to return
-    the user_timeline. [Optional]
-  user_id:
-    Specfies the ID of the user for whom to return the
-    user_timeline. Helpful for disambiguating when a valid user ID
-    is also a valid screen name. [Optional]
-  screen_name:
-    Specfies the screen name of the user for whom to return the
-    user_timeline. Helpful for disambiguating when a valid screen
-    name is also a user ID. [Optional]
-  since_id:
-    Returns results with an ID greater than (that is, more recent
-    than) the specified ID. There are limits to the number of
-    Tweets which can be accessed through the API. If the limit of
-    Tweets has occured since the since_id, the since_id will be
-    forced to the oldest ID available. [Optional]
-  max_id:
-    Returns only statuses with an ID less than (that is, older
-    than) or equal to the specified ID. [Optional]
-  count:
-    Specifies the number of statuses to retrieve. May not be
-    greater than 200.  [Optional]
-  page:
-    Specifies the page of results to retrieve.
-    Note: there are pagination limits. [Optional]
-  include_rts:
-    If True, the timeline will contain native retweets (if they
-    exist) in addition to the standard stream of tweets. [Optional]
-  include_entities:
-    If True, each tweet will include a node called "entities,".
-    This node offers a variety of metadata about the tweet in a
-    discreet structure, including: user_mentions, urls, and
-    hashtags. [Optional]

-Returns:
-  A sequence of Status instances, one for each message up to count
- -
MaximumHitFrequency(self)
Determines the minimum number of seconds that a program must wait
-before hitting the server again without exceeding the rate_limit
-imposed for the currently authenticated user.

-Returns:
-  The minimum second interval that a program must use so as to not
-  exceed the rate_limit imposed for the user.
- -
PostDirectMessage(self, user, text)
Post a twitter direct message from the authenticated user

-The twitter.Api instance must be authenticated.

-Args:
-  user: The ID or screen name of the recipient user.
-  text: The message text to be posted.  Must be less than 140 characters.

-Returns:
-  A twitter.DirectMessage instance representing the message posted
- -
PostUpdate(self, status, in_reply_to_status_id=None)
Post a twitter status message from the authenticated user.

-The twitter.Api instance must be authenticated.

-Args:
-  status:
-    The message text to be posted.
-    Must be less than or equal to 140 characters.
-  in_reply_to_status_id:
-    The ID of an existing status that the status to be posted is
-    in reply to.  This implicitly sets the in_reply_to_user_id
-    attribute of the resulting status to the user ID of the
-    message being replied to.  Invalid/missing status IDs will be
-    ignored. [Optional]
-Returns:
-  A twitter.Status instance representing the message posted.
- -
PostUpdates(self, status, continuation=None, **kwargs)
Post one or more twitter status messages from the authenticated user.

-Unlike api.PostUpdate, this method will post multiple status updates
-if the message is longer than 140 characters.

-The twitter.Api instance must be authenticated.

-Args:
-  status:
-    The message text to be posted.
-    May be longer than 140 characters.
-  continuation:
-    The character string, if any, to be appended to all but the
-    last message.  Note that Twitter strips trailing '...' strings
-    from messages.  Consider using the unicode \u2026 character
-    (horizontal ellipsis) instead. [Defaults to None]
-  **kwargs:
-    See api.PostUpdate for a list of accepted parameters.

-Returns:
-  A of list twitter.Status instance representing the messages posted.
- -
SetCache(self, cache)
Override the default cache.  Set to None to prevent caching.

-Args:
-  cache:
-    An instance that supports the same API as the twitter._FileCache
- -
SetCacheTimeout(self, cache_timeout)
Override the default cache timeout.

-Args:
-  cache_timeout:
-    Time, in seconds, that responses should be reused.
- -
SetCredentials(self, consumer_key, consumer_secret, access_token_key=None, access_token_secret=None)
Set the consumer_key and consumer_secret for this instance

-Args:
-  consumer_key:
-    The consumer_key of the twitter account.
-  consumer_secret:
-    The consumer_secret for the twitter account.
-  access_token_key:
-    The oAuth access token key value you retrieved
-    from running get_access_token.py.
-  access_token_secret:
-    The oAuth access token's secret, also retrieved
-    from the get_access_token.py run.
- -
SetSource(self, source)
Suggest the "from source" value to be displayed on the Twitter web site.

-The value of the 'source' parameter must be first recognized by
-the Twitter server.  New source values are authorized on a case by
-case basis by the Twitter development team.

-Args:
-  source:
-    The source name as a string.  Will be sent to the server as
-    the 'source' parameter.
- -
SetUrllib(self, urllib)
Override the default urllib implementation.

-Args:
-  urllib:
-    An instance that supports the same API as the urllib2 module
- -
SetUserAgent(self, user_agent)
Override the default user agent

-Args:
-  user_agent:
-    A string that should be send to the server as the User-agent
- -
SetXTwitterHeaders(self, client, url, version)
Set the X-Twitter HTTP headers that will be sent to the server.

-Args:
-  client:
-     The client name as a string.  Will be sent to the server as
-     the 'X-Twitter-Client' header.
-  url:
-     The URL of the meta.xml as a string.  Will be sent to the server
-     as the 'X-Twitter-Client-URL' header.
-  version:
-     The client version as a string.  Will be sent to the server
-     as the 'X-Twitter-Client-Version' header.
- -
UsersLookup(self, user_id=None, screen_name=None, users=None)
Fetch extended information for the specified users.

-Users may be specified either as lists of either user_ids,
-screen_names, or twitter.User objects. The list of users that
-are queried is the union of all specified parameters.

-The twitter.Api instance must be authenticated.

-Args:
-  user_id:
-    A list of user_ids to retrieve extended information.
-    [Optional]
-  screen_name:
-    A list of screen_names to retrieve extended information.
-    [Optional]
-  users:
-    A list of twitter.User objects to retrieve extended information.
-    [Optional]

-Returns:
-  A list of twitter.User objects for the requested users
- -
VerifyCredentials(self)
Returns a twitter.User instance if the authenticating user is valid.

-Returns:
-  A twitter.User instance representing that user if the
-  credentials are valid, None otherwise.
- -
__init__(self, consumer_key=None, consumer_secret=None, access_token_key=None, access_token_secret=None, input_encoding=None, request_headers=None, cache=<object object at 0x1001da0a0>, shortner=None, base_url=None, use_gzip_compression=False, debugHTTP=False)
Instantiate a new twitter.Api object.

-Args:
-  consumer_key:
-    Your Twitter user's consumer_key.
-  consumer_secret:
-    Your Twitter user's consumer_secret.
-  access_token_key:
-    The oAuth access token key value you retrieved
-    from running get_access_token.py.
-  access_token_secret:
-    The oAuth access token's secret, also retrieved
-    from the get_access_token.py run.
-  input_encoding:
-    The encoding used to encode input strings. [Optional]
-  request_header:
-    A dictionary of additional HTTP request headers. [Optional]
-  cache:
-    The cache instance to use. Defaults to DEFAULT_CACHE.
-    Use None to disable caching. [Optional]
-  shortner:
-    The shortner instance to use.  Defaults to None.
-    See shorten_url.py for an example shortner. [Optional]
-  base_url:
-    The base URL to use to contact the Twitter API.
-    Defaults to https://twitter.com. [Optional]
-  use_gzip_compression:
-    Set to True to tell enable gzip compression for any call
-    made to Twitter.  Defaults to False. [Optional]
-  debugHTTP:
-    Set to True to enable debug output from urllib2 when performing
-    any HTTP requests.  Defaults to False. [Optional]
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-
-Data and other attributes defined here:
-
DEFAULT_CACHE_TIMEOUT = 60
- -

- - - - - - - -
 
-class DirectMessage(__builtin__.object)
   A class representing the DirectMessage structure used by the twitter API.

-The DirectMessage structure exposes the following properties:

-  direct_message.id
-  direct_message.created_at
-  direct_message.created_at_in_seconds # read only
-  direct_message.sender_id
-  direct_message.sender_screen_name
-  direct_message.recipient_id
-  direct_message.recipient_screen_name
-  direct_message.text
 
 Methods defined here:
-
AsDict(self)
A dict representation of this twitter.DirectMessage instance.

-The return value uses the same key names as the JSON representation.

-Return:
-  A dict representing this twitter.DirectMessage instance
- -
AsJsonString(self)
A JSON string representation of this twitter.DirectMessage instance.

-Returns:
-  A JSON string representation of this twitter.DirectMessage instance
- -
GetCreatedAt(self)
Get the time this direct message was posted.

-Returns:
-  The time this direct message was posted
- -
GetCreatedAtInSeconds(self)
Get the time this direct message was posted, in seconds since the epoch.

-Returns:
-  The time this direct message was posted, in seconds since the epoch.
- -
GetId(self)
Get the unique id of this direct message.

-Returns:
-  The unique id of this direct message
- -
GetRecipientId(self)
Get the unique recipient id of this direct message.

-Returns:
-  The unique recipient id of this direct message
- -
GetRecipientScreenName(self)
Get the unique recipient screen name of this direct message.

-Returns:
-  The unique recipient screen name of this direct message
- -
GetSenderId(self)
Get the unique sender id of this direct message.

-Returns:
-  The unique sender id of this direct message
- -
GetSenderScreenName(self)
Get the unique sender screen name of this direct message.

-Returns:
-  The unique sender screen name of this direct message
- -
GetText(self)
Get the text of this direct message.

-Returns:
-  The text of this direct message.
- -
SetCreatedAt(self, created_at)
Set the time this direct message was posted.

-Args:
-  created_at:
-    The time this direct message was created
- -
SetId(self, id)
Set the unique id of this direct message.

-Args:
-  id:
-    The unique id of this direct message
- -
SetRecipientId(self, recipient_id)
Set the unique recipient id of this direct message.

-Args:
-  recipient_id:
-    The unique recipient id of this direct message
- -
SetRecipientScreenName(self, recipient_screen_name)
Set the unique recipient screen name of this direct message.

-Args:
-  recipient_screen_name:
-    The unique recipient screen name of this direct message
- -
SetSenderId(self, sender_id)
Set the unique sender id of this direct message.

-Args:
-  sender_id:
-    The unique sender id of this direct message
- -
SetSenderScreenName(self, sender_screen_name)
Set the unique sender screen name of this direct message.

-Args:
-  sender_screen_name:
-    The unique sender screen name of this direct message
- -
SetText(self, text)
Set the text of this direct message.

-Args:
-  text:
-    The text of this direct message
- -
__eq__(self, other)
- -
__init__(self, id=None, created_at=None, sender_id=None, sender_screen_name=None, recipient_id=None, recipient_screen_name=None, text=None)
An object to hold a Twitter direct message.

-This class is normally instantiated by the twitter.Api class and
-returned in a sequence.

-Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"

-Args:
-  id:
-    The unique id of this direct message. [Optional]
-  created_at:
-    The time this direct message was posted. [Optional]
-  sender_id:
-    The id of the twitter user that sent this message. [Optional]
-  sender_screen_name:
-    The name of the twitter user that sent this message. [Optional]
-  recipient_id:
-    The id of the twitter that received this message. [Optional]
-  recipient_screen_name:
-    The name of the twitter that received this message. [Optional]
-  text:
-    The text of this direct message. [Optional]
- -
__ne__(self, other)
- -
__str__(self)
A string representation of this twitter.DirectMessage instance.

-The return value is the same as the JSON string representation.

-Returns:
-  A string representation of this twitter.DirectMessage instance.
- -
-Static methods defined here:
-
NewFromJsonDict(data)
Create a new instance based on a JSON dict.

-Args:
-  data:
-    A JSON dict, as converted from the JSON in the twitter API

-Returns:
-  A twitter.DirectMessage instance
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-
created_at
-
The time this direct message was posted.
-
-
created_at_in_seconds
-
The time this direct message was posted, in seconds since the epoch
-
-
id
-
The unique id of this direct message.
-
-
recipient_id
-
The unique recipient id of this direct message.
-
-
recipient_screen_name
-
The unique recipient screen name of this direct message.
-
-
sender_id
-
The unique sender id of this direct message.
-
-
sender_screen_name
-
The unique sender screen name of this direct message.
-
-
text
-
The text of this direct message
-
-

- - - - - - - -
 
-class Hashtag(__builtin__.object)
   A class represeinting a twitter hashtag
 
 Methods defined here:
-
__init__(self, text=None)
- -
-Static methods defined here:
-
NewFromJsonDict(data)
Create a new instance based on a JSON dict.

-Args:
-  data:
-    A JSON dict, as converted from the JSON in the twitter API

-Returns:
-  A twitter.Hashtag instance
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-

- - - - - - - -
 
-class List(__builtin__.object)
   A class representing the List structure used by the twitter API.

-The List structure exposes the following properties:

-  list.id
-  list.name
-  list.slug
-  list.description
-  list.full_name
-  list.mode
-  list.uri
-  list.member_count
-  list.subscriber_count
-  list.following
 
 Methods defined here:
-
AsDict(self)
A dict representation of this twitter.List instance.

-The return value uses the same key names as the JSON representation.

-Return:
-  A dict representing this twitter.List instance
- -
AsJsonString(self)
A JSON string representation of this twitter.List instance.

-Returns:
-  A JSON string representation of this twitter.List instance
- -
GetDescription(self)
Get the description of this list.

-Returns:
-  The description of this list
- -
GetFollowing(self)
Get the following status of this list.

-Returns:
-  The following status of this list
- -
GetFull_name(self)
Get the full_name of this list.

-Returns:
-  The full_name of this list
- -
GetId(self)
Get the unique id of this list.

-Returns:
-  The unique id of this list
- -
GetMember_count(self)
Get the member_count of this list.

-Returns:
-  The member_count of this list
- -
GetMode(self)
Get the mode of this list.

-Returns:
-  The mode of this list
- -
GetName(self)
Get the real name of this list.

-Returns:
-  The real name of this list
- -
GetSlug(self)
Get the slug of this list.

-Returns:
-  The slug of this list
- -
GetSubscriber_count(self)
Get the subscriber_count of this list.

-Returns:
-  The subscriber_count of this list
- -
GetUri(self)
Get the uri of this list.

-Returns:
-  The uri of this list
- -
GetUser(self)
Get the user of this list.

-Returns:
-  The owner of this list
- -
SetDescription(self, description)
Set the description of this list.

-Args:
-  description:
-    The description of this list.
- -
SetFollowing(self, following)
Set the following status of this list.

-Args:
-  following:
-    The following of this list.
- -
SetFull_name(self, full_name)
Set the full_name of this list.

-Args:
-  full_name:
-    The full_name of this list.
- -
SetId(self, id)
Set the unique id of this list.

-Args:
-  id:
-    The unique id of this list.
- -
SetMember_count(self, member_count)
Set the member_count of this list.

-Args:
-  member_count:
-    The member_count of this list.
- -
SetMode(self, mode)
Set the mode of this list.

-Args:
-  mode:
-    The mode of this list.
- -
SetName(self, name)
Set the real name of this list.

-Args:
-  name:
-    The real name of this list
- -
SetSlug(self, slug)
Set the slug of this list.

-Args:
-  slug:
-    The slug of this list.
- -
SetSubscriber_count(self, subscriber_count)
Set the subscriber_count of this list.

-Args:
-  subscriber_count:
-    The subscriber_count of this list.
- -
SetUri(self, uri)
Set the uri of this list.

-Args:
-  uri:
-    The uri of this list.
- -
SetUser(self, user)
Set the user of this list.

-Args:
-  user:
-    The owner of this list.
- -
__eq__(self, other)
- -
__init__(self, id=None, name=None, slug=None, description=None, full_name=None, mode=None, uri=None, member_count=None, subscriber_count=None, following=None, user=None)
- -
__ne__(self, other)
- -
__str__(self)
A string representation of this twitter.List instance.

-The return value is the same as the JSON string representation.

-Returns:
-  A string representation of this twitter.List instance.
- -
-Static methods defined here:
-
NewFromJsonDict(data)
Create a new instance based on a JSON dict.

-Args:
-  data:
-    A JSON dict, as converted from the JSON in the twitter API

-Returns:
-  A twitter.List instance
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-
description
-
The description of this list.
-
-
following
-
The following status of this list.
-
-
full_name
-
The full_name of this list.
-
-
id
-
The unique id of this list.
-
-
member_count
-
The member_count of this list.
-
-
mode
-
The mode of this list.
-
-
name
-
The real name of this list.
-
-
slug
-
The slug of this list.
-
-
subscriber_count
-
The subscriber_count of this list.
-
-
uri
-
The uri of this list.
-
-
user
-
The owner of this list.
-
-

- - - - - - - -
 
-class Status(__builtin__.object)
   A class representing the Status structure used by the twitter API.

-The Status structure exposes the following properties:

-  status.created_at
-  status.created_at_in_seconds # read only
-  status.favorited
-  status.in_reply_to_screen_name
-  status.in_reply_to_user_id
-  status.in_reply_to_status_id
-  status.truncated
-  status.source
-  status.id
-  status.text
-  status.location
-  status.relative_created_at # read only
-  status.user
-  status.urls
-  status.user_mentions
-  status.hashtags
 
 Methods defined here:
-
AsDict(self)
A dict representation of this twitter.Status instance.

-The return value uses the same key names as the JSON representation.

-Return:
-  A dict representing this twitter.Status instance
- -
AsJsonString(self)
A JSON string representation of this twitter.Status instance.

-Returns:
-  A JSON string representation of this twitter.Status instance
- -
GetCreatedAt(self)
Get the time this status message was posted.

-Returns:
-  The time this status message was posted
- -
GetCreatedAtInSeconds(self)
Get the time this status message was posted, in seconds since the epoch.

-Returns:
-  The time this status message was posted, in seconds since the epoch.
- -
GetFavorited(self)
Get the favorited setting of this status message.

-Returns:
-  True if this status message is favorited; False otherwise
- -
GetId(self)
Get the unique id of this status message.

-Returns:
-  The unique id of this status message
- -
GetInReplyToScreenName(self)
- -
GetInReplyToStatusId(self)
- -
GetInReplyToUserId(self)
- -
GetLocation(self)
Get the geolocation associated with this status message

-Returns:
-  The geolocation string of this status message.
- -
GetNow(self)
Get the wallclock time for this status message.

-Used to calculate relative_created_at.  Defaults to the time
-the object was instantiated.

-Returns:
-  Whatever the status instance believes the current time to be,
-  in seconds since the epoch.
- -
GetRelativeCreatedAt(self)
Get a human redable string representing the posting time

-Returns:
-  A human readable string representing the posting time
- -
GetSource(self)
- -
GetText(self)
Get the text of this status message.

-Returns:
-  The text of this status message.
- -
GetTruncated(self)
- -
GetUser(self)
Get a twitter.User reprenting the entity posting this status message.

-Returns:
-  A twitter.User reprenting the entity posting this status message
- -
SetCreatedAt(self, created_at)
Set the time this status message was posted.

-Args:
-  created_at:
-    The time this status message was created
- -
SetFavorited(self, favorited)
Set the favorited state of this status message.

-Args:
-  favorited:
-    boolean True/False favorited state of this status message
- -
SetId(self, id)
Set the unique id of this status message.

-Args:
-  id:
-    The unique id of this status message
- -
SetInReplyToScreenName(self, in_reply_to_screen_name)
- -
SetInReplyToStatusId(self, in_reply_to_status_id)
- -
SetInReplyToUserId(self, in_reply_to_user_id)
- -
SetLocation(self, location)
Set the geolocation associated with this status message

-Args:
-  location:
-    The geolocation string of this status message
- -
SetNow(self, now)
Set the wallclock time for this status message.

-Used to calculate relative_created_at.  Defaults to the time
-the object was instantiated.

-Args:
-  now:
-    The wallclock time for this instance.
- -
SetSource(self, source)
- -
SetText(self, text)
Set the text of this status message.

-Args:
-  text:
-    The text of this status message
- -
SetTruncated(self, truncated)
- -
SetUser(self, user)
Set a twitter.User reprenting the entity posting this status message.

-Args:
-  user:
-    A twitter.User reprenting the entity posting this status message
- -
__eq__(self, other)
- -
__init__(self, created_at=None, favorited=None, id=None, text=None, location=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None, urls=None, user_mentions=None, hashtags=None)
An object to hold a Twitter status message.

-This class is normally instantiated by the twitter.Api class and
-returned in a sequence.

-Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"

-Args:
-  created_at:
-    The time this status message was posted. [Optiona]
-  favorited:
-    Whether this is a favorite of the authenticated user. [Optiona]
-  id:
-    The unique id of this status message. [Optiona]
-  text:
-    The text of this status message. [Optiona]
-  location:
-    the geolocation string associated with this message. [Optiona]
-  relative_created_at:
-    A human readable string representing the posting time. [Optiona]
-  user:
-    A twitter.User instance representing the person posting the
-    message. [Optiona]
-  now:
-    The current time, if the client choses to set it.
-    Defaults to the wall clock time. [Optiona]
- -
__ne__(self, other)
- -
__str__(self)
A string representation of this twitter.Status instance.

-The return value is the same as the JSON string representation.

-Returns:
-  A string representation of this twitter.Status instance.
- -
-Static methods defined here:
-
NewFromJsonDict(data)
Create a new instance based on a JSON dict.

-Args:
-  data: A JSON dict, as converted from the JSON in the twitter API
-Returns:
-  A twitter.Status instance
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-
created_at
-
The time this status message was posted.
-
-
created_at_in_seconds
-
The time this status message was posted, in seconds since the epoch
-
-
favorited
-
The favorited state of this status message.
-
-
id
-
The unique id of this status message.
-
-
in_reply_to_screen_name
-
-
-
in_reply_to_status_id
-
-
-
in_reply_to_user_id
-
-
-
location
-
The geolocation string of this status message
-
-
now
-
The wallclock time for this status instance.
-
-
relative_created_at
-
Get a human readable string representing the posting time
-
-
source
-
-
-
text
-
The text of this status message
-
-
truncated
-
-
-
user
-
A twitter.User reprenting the entity posting this status message
-
-

- - - - - - - -
 
-class Trend(__builtin__.object)
   A class representing a trending topic
 
 Methods defined here:
-
__init__(self, name=None, query=None, timestamp=None)
- -
__str__(self)
- -
-Static methods defined here:
-
NewFromJsonDict(data, timestamp=None)
Create a new instance based on a JSON dict

-Args:
-  data:
-    A JSON dict
-  timestamp:
-    Gets set as the timestamp property of the new object

-Returns:
-  A twitter.Trend object
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-

- - - - - - - -
 
-class TwitterError(exceptions.Exception)
   Base class for Twitter errors
 
 
Method resolution order:
-
TwitterError
-
exceptions.Exception
-
exceptions.BaseException
-
__builtin__.object
-
-
-Data descriptors defined here:
-
__weakref__
-
list of weak references to the object (if defined)
-
-
message
-
Returns the first argument used to construct this error.
-
-
-Methods inherited from exceptions.Exception:
-
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
- -
-Data and other attributes inherited from exceptions.Exception:
-
__new__ = <built-in method __new__ of type object at 0x100119f80>
T.__new__(S, ...) -> a new object with type S, a subtype of T
- -
-Methods inherited from exceptions.BaseException:
-
__delattr__(...)
x.__delattr__('name') <==> del x.name
- -
__getattribute__(...)
x.__getattribute__('name') <==> x.name
- -
__getitem__(...)
x.__getitem__(y) <==> x[y]
- -
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]

-Use of negative indices is not supported.
- -
__reduce__(...)
- -
__repr__(...)
x.__repr__() <==> repr(x)
- -
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
- -
__setstate__(...)
- -
__str__(...)
x.__str__() <==> str(x)
- -
__unicode__(...)
- -
-Data descriptors inherited from exceptions.BaseException:
-
__dict__
-
-
args
-
-

- - - - - - - -
 
-class Url(__builtin__.object)
   A class representing an URL contained in a tweet
 
 Methods defined here:
-
__init__(self, url=None, expanded_url=None)
- -
-Static methods defined here:
-
NewFromJsonDict(data)
Create a new instance based on a JSON dict.

-Args:
-  data:
-    A JSON dict, as converted from the JSON in the twitter API

-Returns:
-  A twitter.Url instance
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-

+

 
+ Modules
        + + + + + + + +
StringIO
+ base64
+ calendar
+ datetime
+ gzip
+
httplib
+ oauth2
+ os
+ rfc822
+ json
+
sys
+ tempfile
+ textwrap
+ time
+ urllib
+
urllib2
+ urlparse
+
+
+

- - - - - - -
 
-class User(__builtin__.object)
   A class representing the User structure used by the twitter API.

-The User structure exposes the following properties:

-  user.id
-  user.name
-  user.screen_name
-  user.location
-  user.description
-  user.profile_image_url
-  user.profile_background_tile
-  user.profile_background_image_url
-  user.profile_sidebar_fill_color
-  user.profile_background_color
-  user.profile_link_color
-  user.profile_text_color
-  user.protected
-  user.utc_offset
-  user.time_zone
-  user.url
-  user.status
-  user.statuses_count
-  user.followers_count
-  user.friends_count
-  user.favourites_count
 
 Methods defined here:
-
AsDict(self)
A dict representation of this twitter.User instance.

-The return value uses the same key names as the JSON representation.

-Return:
-  A dict representing this twitter.User instance
- -
AsJsonString(self)
A JSON string representation of this twitter.User instance.

-Returns:
-  A JSON string representation of this twitter.User instance
- -
GetDescription(self)
Get the short text description of this user.

-Returns:
-  The short text description of this user
- -
GetFavouritesCount(self)
Get the number of favourites for this user.

-Returns:
-  The number of favourites for this user.
- -
GetFollowersCount(self)
Get the follower count for this user.

-Returns:
-  The number of users following this user.
- -
GetFriendsCount(self)
Get the friend count for this user.

-Returns:
-  The number of users this user has befriended.
- -
GetId(self)
Get the unique id of this user.

-Returns:
-  The unique id of this user
- -
GetLocation(self)
Get the geographic location of this user.

-Returns:
-  The geographic location of this user
- -
GetName(self)
Get the real name of this user.

-Returns:
-  The real name of this user
- -
GetProfileBackgroundColor(self)
- -
GetProfileBackgroundImageUrl(self)
- -
GetProfileBackgroundTile(self)
Boolean for whether to tile the profile background image.

-Returns:
-  True if the background is to be tiled, False if not, None if unset.
- -
GetProfileImageUrl(self)
Get the url of the thumbnail of this user.

-Returns:
-  The url of the thumbnail of this user
- -
GetProfileLinkColor(self)
- -
GetProfileSidebarFillColor(self)
- -
GetProfileTextColor(self)
- -
GetProtected(self)
- -
GetScreenName(self)
Get the short twitter name of this user.

-Returns:
-  The short twitter name of this user
- -
GetStatus(self)
Get the latest twitter.Status of this user.

-Returns:
-  The latest twitter.Status of this user
- -
GetStatusesCount(self)
Get the number of status updates for this user.

-Returns:
-  The number of status updates for this user.
- -
GetTimeZone(self)
Returns the current time zone string for the user.

-Returns:
-  The descriptive time zone string for the user.
- -
GetUrl(self)
Get the homepage url of this user.

-Returns:
-  The homepage url of this user
- -
GetUtcOffset(self)
- -
SetDescription(self, description)
Set the short text description of this user.

-Args:
-  description: The short text description of this user
- -
SetFavouritesCount(self, count)
Set the favourite count for this user.

-Args:
-  count:
-    The number of favourites for this user.
- -
SetFollowersCount(self, count)
Set the follower count for this user.

-Args:
-  count:
-    The number of users following this user.
- -
SetFriendsCount(self, count)
Set the friend count for this user.

-Args:
-  count:
-    The number of users this user has befriended.
- -
SetId(self, id)
Set the unique id of this user.

-Args:
-  id: The unique id of this user.
- -
SetLocation(self, location)
Set the geographic location of this user.

-Args:
-  location: The geographic location of this user
- -
SetName(self, name)
Set the real name of this user.

-Args:
-  name: The real name of this user
- -
SetProfileBackgroundColor(self, profile_background_color)
- -
SetProfileBackgroundImageUrl(self, profile_background_image_url)
- -
SetProfileBackgroundTile(self, profile_background_tile)
Set the boolean flag for whether to tile the profile background image.

-Args:
-  profile_background_tile: Boolean flag for whether to tile or not.
- -
SetProfileImageUrl(self, profile_image_url)
Set the url of the thumbnail of this user.

-Args:
-  profile_image_url: The url of the thumbnail of this user
- -
SetProfileLinkColor(self, profile_link_color)
- -
SetProfileSidebarFillColor(self, profile_sidebar_fill_color)
- -
SetProfileTextColor(self, profile_text_color)
- -
SetProtected(self, protected)
- -
SetScreenName(self, screen_name)
Set the short twitter name of this user.

-Args:
-  screen_name: the short twitter name of this user
- -
SetStatus(self, status)
Set the latest twitter.Status of this user.

-Args:
-  status:
-    The latest twitter.Status of this user
- -
SetStatusesCount(self, count)
Set the status update count for this user.

-Args:
-  count:
-    The number of updates for this user.
- -
SetTimeZone(self, time_zone)
Sets the user's time zone string.

-Args:
-  time_zone:
-    The descriptive time zone to assign for the user.
- -
SetUrl(self, url)
Set the homepage url of this user.

-Args:
-  url: The homepage url of this user
- -
SetUtcOffset(self, utc_offset)
- -
__eq__(self, other)
- -
__init__(self, id=None, name=None, screen_name=None, location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, profile_sidebar_fill_color=None, profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, utc_offset=None, time_zone=None, followers_count=None, friends_count=None, statuses_count=None, favourites_count=None, url=None, status=None)
- -
__ne__(self, other)
- -
__str__(self)
A string representation of this twitter.User instance.

-The return value is the same as the JSON string representation.

-Returns:
-  A string representation of this twitter.User instance.
- -
-Static methods defined here:
-
NewFromJsonDict(data)
Create a new instance based on a JSON dict.

-Args:
-  data:
-    A JSON dict, as converted from the JSON in the twitter API

-Returns:
-  A twitter.User instance
- -
-Data descriptors defined here:
-
__dict__
-
dictionary for instance variables (if defined)
-
-
__weakref__
-
list of weak references to the object (if defined)
-
-
description
-
The short text description of this user.
-
-
favourites_count
-
The number of favourites for this user.
-
-
followers_count
-
The number of users following this user.
-
-
friends_count
-
The number of friends for this user.
-
-
id
-
The unique id of this user.
-
-
location
-
The geographic location of this user.
-
-
name
-
The real name of this user.
-
-
profile_background_color
-
-
profile_background_image_url
-
The url of the profile background of this user.
-
-
profile_background_tile
-
Boolean for whether to tile the background image.
-
-
profile_image_url
-
The url of the thumbnail of this user.
-
-
profile_link_color
-
-
profile_sidebar_fill_color
-
-
profile_text_color
-
-
protected
-
-
screen_name
-
The short twitter name of this user.
-
-
status
-
The latest twitter.Status of this user.
-
-
statuses_count
-
The number of updates for this user.
-
-
time_zone
-
Returns the current time zone string for the user.

-Returns:
-  The descriptive time zone string for the user.
-
-
url
-
The homepage url of this user.
-
-
utc_offset
-
-

+ +  
+ Classes + + + +        +   + +

+
__builtin__.object +
+
+
+
Api +
+
DirectMessage +
+
Hashtag +
+
List +
+
Status +
+
Trend +
+
Url +
+
User +
+
+
+
exceptions.Exception(exceptions.BaseException) +
+
+
+
TwitterError +
+
+
+
+

+ + + + + + + + + + + + + +
 
+ class Api(__builtin__.object)
   A python interface into the Twitter API
+  
+ By default, the Api caches results for 1 minute.
+  
+ Example usage:
+  
+   To create an instance of the twitter.Api class, with no authentication:
+  
+     >>> import twitter
+     >>> api = twitter.Api()
+  
+   To fetch a single user's public status messages, where "user" is either
+   a Twitter "short name" or their user id.
+  
+     >>> statuses = api.GetUserTimeline(user)
+     >>> print [s.text for s in statuses]
+  
+   To use authentication, instantiate the twitter.Api class with a
+   consumer key and secret; and the oAuth key and secret:
+  
+     >>> api = twitter.Api(consumer_key='twitter consumer key',
+                           consumer_secret='twitter consumer secret',
+                           access_token_key='the_key_given',
+                           access_token_secret='the_key_secret')
+  
+   To fetch your friends (after being authenticated):
+  
+     >>> users = api.GetFriends()
+     >>> print [u.name for u in users]
+  
+   To post a twitter status message (after being authenticated):
+  
+     >>> status = api.PostUpdate('I love python-twitter!')
+     >>> print status.text
+     I love python-twitter!
+  
+   There are many other methods, including:
+  
+     >>> api.PostUpdates(status)
+     >>> api.PostDirectMessage(user, text)
+     >>> api.GetUser(user)
+     >>> api.GetReplies()
+     >>> api.GetUserTimeline(user)
+     >>> api.GetStatus(id)
+     >>> api.DestroyStatus(id)
+     >>> api.GetFriends(user)
+     >>> api.GetFollowers()
+     >>> api.GetFeatured()
+     >>> api.GetDirectMessages()
+     >>> api.PostDirectMessage(user, text)
+     >>> api.DestroyDirectMessage(id)
+     >>> api.DestroyFriendship(user)
+     >>> api.CreateFriendship(user)
+     >>> api.VerifyCredentials()
 
 Methods defined here:
+
+
ClearCredentials(self)
+
Clear the any credentials for this instance
+
+ +
+
CreateFavorite(self, status)
+
Favorites the status specified in the status parameter as the authenticating user.
+ Returns the favorite status when successful.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   The twitter.Status instance to mark as a favorite.
+ Returns:
+   A twitter.Status instance representing the newly-marked favorite.
+
+
+ +
+
CreateFriendship(self, user)
+
Befriends the user specified in the user parameter as the authenticating user.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   The ID or screen name of the user to befriend.
+ Returns:
+   A twitter.User instance representing the befriended user.
+
+
+ +
+
CreateList(self, user, name, mode=None, description=None) +
+
Creates a new list with the given name
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user:
+     Twitter name to create the list for
+   name:
+     New name for the list
+   mode:
+     'public' or 'private'.
+     Defaults to 'public'. [Optional]
+   description:
+     Description of the list. [Optional]
+  
+ Returns:
+   A twitter.List instance representing the new list
+
+
+ +
+
CreateSubscription(self, owner, + list) +
+
Creates a subscription to a list by the authenticated user
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   owner:
+     User name or id of the owner of the list being subscribed to.
+   list:
+     The slug or list id to subscribe the user to
+  
+ Returns:
+   A twitter.List instance representing the list subscribed to
+
+
+ +
+
DestroyDirectMessage(self, id) +
+
Destroys the direct message specified in the required ID parameter.
+  
+ The twitter.Api instance must be authenticated, and the
+ authenticating user must be the recipient of the specified direct
+ message.
+  
+ Args:
+   id: The id of the direct message to be destroyed
+  
+ Returns:
+   A twitter.DirectMessage instance representing the message destroyed
+
+
+ +
+
DestroyFavorite(self, status)
+
Un-favorites the status specified in the ID parameter as the authenticating user.
+ Returns the un-favorited status in the requested format when successful.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   The twitter.Status to unmark as a favorite.
+ Returns:
+   A twitter.Status instance representing the newly-unmarked favorite.
+
+
+ +
+
DestroyFriendship(self, user)
+
Discontinues friendship with the user specified in the user parameter.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   The ID or screen name of the user  with whom to discontinue friendship.
+ Returns:
+   A twitter.User instance representing the discontinued friend.
+
+
+ +
+
DestroyList(self, user, id)
+
Destroys the list from the given user
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user:
+     The user to remove the list from.
+   id:
+     The slug or id of the list to remove.
+ Returns:
+   A twitter.List instance representing the removed list.
+
+
+ +
+
DestroyStatus(self, id)
+
Destroys the status specified by the required ID parameter.
+  
+ The twitter.Api instance must be authenticated and the
+ authenticating user must be the author of the specified status.
+  
+ Args:
+   id:
+     The numerical ID of the status you're trying to destroy.
+  
+ Returns:
+   A twitter.Status instance representing the destroyed status message
+
+
+ +
+
DestroySubscription(self, owner, + list) +
+
Destroys the subscription to a list for the authenticated user
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   owner:
+     The user id or screen name of the user that owns the
+     list that is to be unsubscribed from
+   list:
+     The slug or list id of the list to unsubscribe from
+  
+ Returns:
+   A twitter.List instance representing the removed list.
+
+
+ +
+
FilterPublicTimeline(self, term, + since_id=None) +
+
Filter the public twitter timeline by a given search term on
+ the local machine.
+  
+ Args:
+   term:
+     term to search by.
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+  
+ Returns:
+   A sequence of twitter.Status instances, one for each message
+   containing the term
+
+ +
+
GetDirectMessages(self, since=None, since_id=None, page=None) +
+
Returns a list of the direct messages sent to the authenticating user.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   since:
+     Narrows the returned results to just those statuses created
+     after the specified HTTP-formatted date. [Optional]
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+  
+ Returns:
+   A sequence of twitter.DirectMessage instances
+
+ +
+
GetFavorites(self, user=None, page=None) +
+
Return a list of Status objects representing favorited tweets.
+ By default, returns the (up to) 20 most recent tweets for the
+ authenticated user.
+  
+ Args:
+   user:
+     The twitter name or id of the user whose favorites you are fetching.
+     If not specified, defaults to the authenticated user. [Optional]
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+
+
+ +
+
GetFeatured(self)
+
Fetch the sequence of twitter.User instances featured on twitter.com
+  
+ The twitter.Api instance must be authenticated.
+  
+ Returns:
+   A sequence of twitter.User instances
+
+
+ +
+
GetFollowerIDs(self, userid=None, cursor=-1) +
+
Fetch the sequence of twitter.User instances, one for each follower
+  
+ The twitter.Api instance must be authenticated.
+  
+ Returns:
+   A sequence of twitter.User instances, one for each follower
+
+
+ +
+
GetFollowers(self, page=None) +
+
Fetch the sequence of twitter.User instances, one for each follower
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+  
+ Returns:
+   A sequence of twitter.User instances, one for each follower
+
+
+ +
+
GetFriendIDs(self, user=None, cursor=-1) +
+
Returns a list of twitter user id's for every person
+ the specified user is following.
+  
+ Args:
+   user:
+     The id or screen_name of the user to retrieve the id list for
+     [Optional]
+  
+ Returns:
+   A list of integers, one for each user id.
+
+
+ +
+
GetFriends(self, user=None, cursor=-1) +
+
Fetch the sequence of twitter.User instances, one for each friend.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user:
+     The twitter name or id of the user whose friends you are fetching.
+     If not specified, defaults to the authenticated user. [Optional]
+  
+ Returns:
+   A sequence of twitter.User instances, one for each friend
+
+
+ +
+
GetLists(self, user, cursor=-1) +
+
Fetch the sequence of lists for a user.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user:
+     The twitter name or id of the user whose friends you are fetching.
+     If the passed in user is the same as the authenticated user
+     then you will also receive private list data.
+   cursor:
+     "page" value that Twitter will use to start building the
+     list sequence from.  -1 to start at the beginning.
+     Twitter will return in the result the values for next_cursor
+     and previous_cursor. [Optional]
+  
+ Returns:
+   A sequence of twitter.List instances, one for each list
+
+
+ +
+
GetMentions(self, since_id=None, max_id=None, page=None) +
+
Returns the 20 most recent mentions (status containing @twitterID)
+ for the authenticating user.
+  
+ Args:
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+   max_id:
+     Returns only statuses with an ID less than
+     (that is, older than) the specified ID.  [Optional]
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+  
+ Returns:
+   A sequence of twitter.Status instances, one for each mention of the user.
+
+
+ +
+
GetRateLimitStatus(self)
+
Fetch the rate limit status for the currently authorized user.
+  
+ Returns:
+   A dictionary containing the time the limit will reset (reset_time),
+   the number of remaining hits allowed before the reset (remaining_hits),
+   the number of hits allowed in a 60-minute period (hourly_limit), and
+   the time of the reset in seconds since The Epoch (reset_time_in_seconds).
+
+
+ +
+
GetReplies(self, since=None, since_id=None, page=None) +
+
Get a sequence of status messages representing the 20 most
+ recent replies (status updates prefixed with @twitterID) to the
+ authenticating user.
+  
+ Args:
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+   since:
+  
+ Returns:
+   A sequence of twitter.Status instances, one for each reply to the user.
+
+
+ +
+
GetRetweets(self, statusid)
+
Returns up to 100 of the first retweets of the tweet identified
+ by statusid
+  
+ Args:
+   statusid:
+     The ID of the tweet for which retweets should be searched for
+  
+ Returns:
+   A list of twitter.Status instances, which are retweets of statusid
+
+
+ +
+
GetSearch(self, term, geocode=None, since_id=None, + per_page=15, page=1, lang='en', show_user='true', + query_users=False) +
+
+ Return twitter search results for a given term.
+  
+ Args:
+   term:
+     term to search by.
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+   geocode:
+     geolocation information in the form (latitude, longitude, radius)
+     [Optional]
+   per_page:
+     number of results to return.  Default is 15 [Optional]
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+   lang:
+     language for results.  Default is English [Optional]
+   show_user:
+     prefixes screen name in status
+   query_users:
+     If set to False, then all users only have screen_name and
+     profile_image_url available.
+     If set to True, all information of users are available,
+     but it uses lots of request quota, one per status.
+  
+ Returns:
+   A sequence of twitter.Status instances, one for each message containing
+   the term
+
+ +
+
GetStatus(self, id)
+
Returns a single status message.
+  
+ The twitter.Api instance must be authenticated if the
+ status message is private.
+  
+ Args:
+   id:
+     The numeric ID of the status you are trying to retrieve.
+  
+ Returns:
+   A twitter.Status instance representing that status message
+
+
+ +
+
GetSubscriptions(self, user, + cursor=-1) +
+
Fetch the sequence of Lists that the given user is subscribed to
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user:
+     The twitter name or id of the user
+   cursor:
+     "page" value that Twitter will use to start building the
+     list sequence from.  -1 to start at the beginning.
+     Twitter will return in the result the values for next_cursor
+     and previous_cursor. [Optional]
+  
+ Returns:
+   A sequence of twitter.List instances, one for each list
+
+
+ +
+
GetTrendsCurrent(self, exclude=None) +
+
Get the current top trending topics
+  
+ Args:
+   exclude:
+     Appends the exclude parameter as a request parameter.
+     Currently only exclude=hashtags is supported. [Optional]
+  
+ Returns:
+   A list with 10 entries. Each entry contains the twitter.
+
+
+ +
+
GetTrendsDaily(self, exclude=None, startdate=None) +
+
Get the current top trending topics for each hour in a given day
+  
+ Args:
+   startdate:
+     The start date for the report.
+     Should be in the format YYYY-MM-DD. [Optional]
+   exclude:
+     Appends the exclude parameter as a request parameter.
+     Currently only exclude=hashtags is supported. [Optional]
+  
+ Returns:
+   A list with 24 entries. Each entry contains the twitter.
+   Trend elements that were trending at the corresponding hour of the day.
+
+
+ +
+
GetTrendsWeekly(self, exclude=None, startdate=None) +
+
Get the top 30 trending topics for each day in a given week.
+  
+ Args:
+   startdate:
+     The start date for the report.
+     Should be in the format YYYY-MM-DD. [Optional]
+   exclude:
+     Appends the exclude parameter as a request parameter.
+     Currently only exclude=hashtags is supported. [Optional]
+ Returns:
+   A list with each entry contains the twitter.
+   Trend elements of trending topics for the corrsponding day of the week
+
+
+ +
+
GetUser(self, user)
+
Returns a single user.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user: The twitter name or id of the user to retrieve.
+  
+ Returns:
+   A twitter.User instance representing that user
+
+
+ +
+
GetUserRetweets(self, count=None, since_id=None, + max_id=None, include_entities=False) +
+
Fetch the sequence of retweets made by a single user.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   count:
+     The number of status messages to retrieve. [Optional]
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+   max_id:
+     Returns results with an ID less than (that is, older than) or
+     equal to the specified ID. [Optional]
+   include_entities:
+     If True, each tweet will include a node called "entities,".
+     This node offers a variety of metadata about the tweet in a
+     discreet structure, including: user_mentions, urls, and
+     hashtags. [Optional]
+  
+ Returns:
+   A sequence of twitter.Status instances, one for each message up to count
+
+
+ +
+
GetUserTimeline(self, id=None, user_id=None, screen_name=None, since_id=None, + max_id=None, count=None, + page=None, include_rts=None, + include_entities=None) +
+
Fetch the sequence of public Status messages for a single user.
+  
+ The twitter.Api instance must be authenticated if the user is private.
+  
+ Args:
+   id:
+     Specifies the ID or screen name of the user for whom to return
+     the user_timeline. [Optional]
+   user_id:
+     Specfies the ID of the user for whom to return the
+     user_timeline. Helpful for disambiguating when a valid user ID
+     is also a valid screen name. [Optional]
+   screen_name:
+     Specfies the screen name of the user for whom to return the
+     user_timeline. Helpful for disambiguating when a valid screen
+     name is also a user ID. [Optional]
+   since_id:
+     Returns results with an ID greater than (that is, more recent
+     than) the specified ID. There are limits to the number of
+     Tweets which can be accessed through the API. If the limit of
+     Tweets has occured since the since_id, the since_id will be
+     forced to the oldest ID available. [Optional]
+   max_id:
+     Returns only statuses with an ID less than (that is, older
+     than) or equal to the specified ID. [Optional]
+   count:
+     Specifies the number of statuses to retrieve. May not be
+     greater than 200.  [Optional]
+   page:
+     Specifies the page of results to retrieve.
+     Note: there are pagination limits. [Optional]
+   include_rts:
+     If True, the timeline will contain native retweets (if they
+     exist) in addition to the standard stream of tweets. [Optional]
+   include_entities:
+     If True, each tweet will include a node called "entities,".
+     This node offers a variety of metadata about the tweet in a
+     discreet structure, including: user_mentions, urls, and
+     hashtags. [Optional]
+  
+ Returns:
+   A sequence of Status instances, one for each message up to count
+
+
+ +
+
MaximumHitFrequency(self)
+
Determines the minimum number of seconds that a program must wait
+ before hitting the server again without exceeding the rate_limit
+ imposed for the currently authenticated user.
+  
+ Returns:
+   The minimum second interval that a program must use so as to not
+   exceed the rate_limit imposed for the user.
+
+
+ +
+
PostDirectMessage(self, user, text) +
+
Post a twitter direct message from the authenticated user
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user: The ID or screen name of the recipient user.
+   text: The message text to be posted.  Must be less than 140 characters.
+  
+ Returns:
+   A twitter.DirectMessage instance representing the message posted
+
+
+ +
+
PostUpdate(self, status, + in_reply_to_status_id=None) +
+
Post a twitter status message from the authenticated user.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   status:
+     The message text to be posted.
+     Must be less than or equal to 140 characters.
+   in_reply_to_status_id:
+     The ID of an existing status that the status to be posted is
+     in reply to.  This implicitly sets the in_reply_to_user_id
+     attribute of the resulting status to the user ID of the
+     message being replied to.  Invalid/missing status IDs will be
+     ignored. [Optional]
+ Returns:
+   A twitter.Status instance representing the message posted.
+
+
+ +
+
PostUpdates(self, status, + continuation=None, **kwargs) +
+
Post one or more twitter status messages from the authenticated user.
+  
+ Unlike api.PostUpdate, this method will post multiple status updates
+ if the message is longer than 140 characters.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   status:
+     The message text to be posted.
+     May be longer than 140 characters.
+   continuation:
+     The character string, if any, to be appended to all but the
+     last message.  Note that Twitter strips trailing '...' strings
+     from messages.  Consider using the unicode \u2026 character
+     (horizontal ellipsis) instead. [Defaults to None]
+   **kwargs:
+     See api.PostUpdate for a list of accepted parameters.
+  
+ Returns:
+   A of list twitter.Status instance representing the messages posted.
+
+
+ +
+
SetCache(self, cache)
+
Override the default cache.  Set to None to prevent caching.
+  
+ Args:
+   cache:
+     An instance that supports the same API as the twitter._FileCache
+
+
+ +
+
SetCacheTimeout(self, cache_timeout) +
+
Override the default cache timeout.
+  
+ Args:
+   cache_timeout:
+     Time, in seconds, that responses should be reused.
+
+
+ +
+
SetCredentials(self, consumer_key, + consumer_secret, access_token_key=None, access_token_secret=None) +
+
Set the consumer_key and consumer_secret for this instance
+  
+ Args:
+   consumer_key:
+     The consumer_key of the twitter account.
+   consumer_secret:
+     The consumer_secret for the twitter account.
+   access_token_key:
+     The oAuth access token key value you retrieved
+     from running get_access_token.py.
+   access_token_secret:
+     The oAuth access token's secret, also retrieved
+     from the get_access_token.py run.
+
+ +
+
SetSource(self, source)
+
Suggest the "from source" value to be displayed on the Twitter web site.
+  
+ The value of the 'source' parameter must be first recognized by
+ the Twitter server.  New source values are authorized on a case by
+ case basis by the Twitter development team.
+  
+ Args:
+   source:
+     The source name as a string.  Will be sent to the server as
+     the 'source' parameter.
+
+ +
+
SetUrllib(self, urllib)
+
Override the default urllib implementation.
+  
+ Args:
+   urllib:
+     An instance that supports the same API as the urllib2 module
+
+
+ +
+
SetUserAgent(self, user_agent)
+
Override the default user agent
+  
+ Args:
+   user_agent:
+     A string that should be send to the server as the User-agent
+
+ +
+
SetXTwitterHeaders(self, client, + url, version) +
+
Set the X-Twitter HTTP headers that will be sent to the server.
+  
+ Args:
+   client:
+      The client name as a string.  Will be sent to the server as
+      the 'X-Twitter-Client' header.
+   url:
+      The URL of the meta.xml as a string.  Will be sent to the server
+      as the 'X-Twitter-Client-URL' header.
+   version:
+      The client version as a string.  Will be sent to the server
+      as the 'X-Twitter-Client-Version' header.
+
+
+ +
+
UsersLookup(self, user_id=None, screen_name=None, + users=None) +
+
+ Fetch extended information for the specified users.
+  
+ Users may be specified either as lists of either user_ids,
+ screen_names, or twitter.User objects. The list of users that
+ are queried is the union of all specified parameters.
+  
+ The twitter.Api instance must be authenticated.
+  
+ Args:
+   user_id:
+     A list of user_ids to retrieve extended information.
+     [Optional]
+   screen_name:
+     A list of screen_names to retrieve extended information.
+     [Optional]
+   users:
+     A list of twitter.User objects to retrieve extended information.
+     [Optional]
+  
+ Returns:
+   A list of twitter.User objects for the requested users
+
+
+ +
+
VerifyCredentials(self)
+
Returns a twitter.User instance if the authenticating user is valid.
+  
+ Returns:
+   A twitter.User instance representing that user if the
+   credentials are valid, None otherwise.
+
+ +
+
__init__(self, consumer_key=None, consumer_secret=None, + access_token_key=None, access_token_secret=None, input_encoding=None, + request_headers=None, cache=<object + object at 0x1001da0a0>, shortner=None, + base_url=None, use_gzip_compression=False, + debugHTTP=False) +
+
Instantiate a new twitter.Api object.
+  
+ Args:
+   consumer_key:
+     Your Twitter user's consumer_key.
+   consumer_secret:
+     Your Twitter user's consumer_secret.
+   access_token_key:
+     The oAuth access token key value you retrieved
+     from running get_access_token.py.
+   access_token_secret:
+     The oAuth access token's secret, also retrieved
+     from the get_access_token.py run.
+   input_encoding:
+     The encoding used to encode input strings. [Optional]
+   request_header:
+     A dictionary of additional HTTP request headers. [Optional]
+   cache:
+     The cache instance to use. Defaults to DEFAULT_CACHE.
+     Use None to disable caching. [Optional]
+   shortner:
+     The shortner instance to use.  Defaults to None.
+     See shorten_url.py for an example shortner. [Optional]
+   base_url:
+     The base URL to use to contact the Twitter API.
+     Defaults to https://twitter.com. [Optional]
+   use_gzip_compression:
+     Set to True to tell enable gzip compression for any call
+     made to Twitter.  Defaults to False. [Optional]
+   debugHTTP:
+     Set to True to enable debug output from urllib2 when performing
+     any HTTP requests.  Defaults to False. [Optional]
+
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+ Data and other attributes defined here:
+
+
DEFAULT_CACHE_TIMEOUT = 60 +
+ +
+

+ + + + + + + + + + + + + +
 
+ class DirectMessage(__builtin__.object)
   A class representing the DirectMessage structure used by the twitter API.
+  
+ The DirectMessage structure exposes the following properties:
+  
+   direct_message.id
+   direct_message.created_at
+   direct_message.created_at_in_seconds # read only
+   direct_message.sender_id
+   direct_message.sender_screen_name
+   direct_message.recipient_id
+   direct_message.recipient_screen_name
+   direct_message.text
 
 Methods defined here:
+
+
AsDict(self)
+
A dict representation of this twitter.DirectMessage instance.
+  
+ The return value uses the same key names as the JSON representation.
+  
+ Return:
+   A dict representing this twitter.DirectMessage instance
+
+ +
+
AsJsonString(self)
+
A JSON string representation of this twitter.DirectMessage instance.
+  
+ Returns:
+   A JSON string representation of this twitter.DirectMessage instance
+
+ +
+
GetCreatedAt(self)
+
Get the time this direct message was posted.
+  
+ Returns:
+   The time this direct message was posted
+
+
+ +
+
GetCreatedAtInSeconds(self) +
+
Get the time this direct message was posted, in seconds since the epoch.
+  
+ Returns:
+   The time this direct message was posted, in seconds since the epoch.
+
+
+ +
+
GetId(self)
+
Get the unique id of this direct message.
+  
+ Returns:
+   The unique id of this direct message
+
+ +
+
GetRecipientId(self)
+
Get the unique recipient id of this direct message.
+  
+ Returns:
+   The unique recipient id of this direct message
+
+
+ +
+
+ GetRecipientScreenName(self) +
+
Get the unique recipient screen name of this direct message.
+  
+ Returns:
+   The unique recipient screen name of this direct message
+
+
+ +
+
GetSenderId(self)
+
Get the unique sender id of this direct message.
+  
+ Returns:
+   The unique sender id of this direct message
+
+
+ +
+
GetSenderScreenName(self) +
+
Get the unique sender screen name of this direct message.
+  
+ Returns:
+   The unique sender screen name of this direct message
+
+
+ +
+
GetText(self)
+
Get the text of this direct message.
+  
+ Returns:
+   The text of this direct message.
+
+ +
+
SetCreatedAt(self, created_at) +
+
Set the time this direct message was posted.
+  
+ Args:
+   created_at:
+     The time this direct message was created
+
+
+ +
+
SetId(self, id)
+
Set the unique id of this direct message.
+  
+ Args:
+   id:
+     The unique id of this direct message
+
+
+ +
+
SetRecipientId(self, + recipient_id) +
+
Set the unique recipient id of this direct message.
+  
+ Args:
+   recipient_id:
+     The unique recipient id of this direct message
+
+
+ +
+
+ SetRecipientScreenName(self, + recipient_screen_name) +
+
Set the unique recipient screen name of this direct message.
+  
+ Args:
+   recipient_screen_name:
+     The unique recipient screen name of this direct message
+
+
+ +
+
SetSenderId(self, sender_id) +
+
Set the unique sender id of this direct message.
+  
+ Args:
+   sender_id:
+     The unique sender id of this direct message
+
+
+ +
+
SetSenderScreenName(self, + sender_screen_name) +
+
Set the unique sender screen name of this direct message.
+  
+ Args:
+   sender_screen_name:
+     The unique sender screen name of this direct message
+
+
+ +
+
SetText(self, text)
+
Set the text of this direct message.
+  
+ Args:
+   text:
+     The text of this direct message
+
+
+ +
+
__eq__(self, other)
+
+ +
+
__init__(self, id=None, created_at=None, + sender_id=None, sender_screen_name=None, + recipient_id=None, recipient_screen_name=None, text=None) +
+
An object to hold a Twitter direct message.
+  
+ This class is normally instantiated by the twitter.Api class and
+ returned in a sequence.
+  
+ Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
+  
+ Args:
+   id:
+     The unique id of this direct message. [Optional]
+   created_at:
+     The time this direct message was posted. [Optional]
+   sender_id:
+     The id of the twitter user that sent this message. [Optional]
+   sender_screen_name:
+     The name of the twitter user that sent this message. [Optional]
+   recipient_id:
+     The id of the twitter that received this message. [Optional]
+   recipient_screen_name:
+     The name of the twitter that received this message. [Optional]
+   text:
+     The text of this direct message. [Optional]
+
+
+ +
+
__ne__(self, other)
+
+ +
+
__str__(self)
+
A string representation of this twitter.DirectMessage instance.
+  
+ The return value is the same as the JSON string representation.
+  
+ Returns:
+   A string representation of this twitter.DirectMessage instance.
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data)
+
+ Create a new instance based on a JSON dict.
+  
+ Args:
+   data:
+     A JSON dict, as converted from the JSON in the twitter API
+  
+ Returns:
+   A twitter.DirectMessage instance
+
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+
created_at
+
The time this direct message was posted.
+
+
+
created_at_in_seconds
+
The time this direct message was posted, in seconds since the epoch +
+
+
+
id
+
The unique id of this direct message.
+
+
+
recipient_id
+
+ The unique recipient id of this direct message. +
+
+
+
recipient_screen_name
+
The unique recipient screen name of this direct message. +
+
+
+
sender_id
+
The unique sender id of this direct message. +
+
+
+
sender_screen_name
+
The unique sender screen name of this direct message. +
+
+
+
text
+
The text of this direct message
+
+
+

+ + + + + + + + + + + + + +
 
+ class + Hashtag(__builtin__.object)
   A class represeinting a twitter hashtag
 
+
 Methods defined here:
+
+
__init__(self, text=None) +
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data)
+
+ Create a new instance based on a JSON dict.
+  
+ Args:
+   data:
+     A JSON dict, as converted from the JSON in the twitter API
+  
+ Returns:
+   A twitter.Hashtag instance
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+

+ + + + + + + + + + + + + +
 
+ class List(__builtin__.object)
   A class representing the List structure used by the twitter API.
+  
+ The List structure exposes the following properties:
+  
+   list.id
+   list.name
+   list.slug
+   list.description
+   list.full_name
+   list.mode
+   list.uri
+   list.member_count
+   list.subscriber_count
+   list.following
 
 Methods defined here:
+
+
AsDict(self)
+
A dict representation of this twitter.List instance.
+  
+ The return value uses the same key names as the JSON representation.
+  
+ Return:
+   A dict representing this twitter.List instance
+
+ +
+
AsJsonString(self)
+
A JSON string representation of this twitter.List instance.
+  
+ Returns:
+   A JSON string representation of this twitter.List instance
+
+ +
+
GetDescription(self)
+
Get the description of this list.
+  
+ Returns:
+   The description of this list
+
+ +
+
GetFollowing(self)
+
Get the following status of this list.
+  
+ Returns:
+   The following status of this list
+
+ +
+
GetFull_name(self)
+
Get the full_name of this list.
+  
+ Returns:
+   The full_name of this list
+
+ +
+
GetId(self)
+
Get the unique id of this list.
+  
+ Returns:
+   The unique id of this list
+
+ +
+
GetMember_count(self)
+
Get the member_count of this list.
+  
+ Returns:
+   The member_count of this list
+
+ +
+
GetMode(self)
+
Get the mode of this list.
+  
+ Returns:
+   The mode of this list
+
+ +
+
GetName(self)
+
Get the real name of this list.
+  
+ Returns:
+   The real name of this list
+
+ +
+
GetSlug(self)
+
Get the slug of this list.
+  
+ Returns:
+   The slug of this list
+
+ +
+
GetSubscriber_count(self)
+
Get the subscriber_count of this list.
+  
+ Returns:
+   The subscriber_count of this list
+
+ +
+
GetUri(self)
+
Get the uri of this list.
+  
+ Returns:
+   The uri of this list
+
+ +
+
GetUser(self)
+
Get the user of this list.
+  
+ Returns:
+   The owner of this list
+
+ +
+
SetDescription(self, description) +
+
Set the description of this list.
+  
+ Args:
+   description:
+     The description of this list.
+
+ +
+
SetFollowing(self, following)
+
Set the following status of this list.
+  
+ Args:
+   following:
+     The following of this list.
+
+ +
+
SetFull_name(self, full_name)
+
Set the full_name of this list.
+  
+ Args:
+   full_name:
+     The full_name of this list.
+
+ +
+
SetId(self, id)
+
Set the unique id of this list.
+  
+ Args:
+   id:
+     The unique id of this list.
+
+ +
+
SetMember_count(self, member_count) +
+
Set the member_count of this list.
+  
+ Args:
+   member_count:
+     The member_count of this list.
+
+ +
+
SetMode(self, mode)
+
Set the mode of this list.
+  
+ Args:
+   mode:
+     The mode of this list.
+
+ +
+
SetName(self, name)
+
Set the real name of this list.
+  
+ Args:
+   name:
+     The real name of this list
+
+ +
+
SetSlug(self, slug)
+
Set the slug of this list.
+  
+ Args:
+   slug:
+     The slug of this list.
+
+ +
+
SetSubscriber_count(self, + subscriber_count) +
+
Set the subscriber_count of this list.
+  
+ Args:
+   subscriber_count:
+     The subscriber_count of this list.
+
+ +
+
SetUri(self, uri)
+
Set the uri of this list.
+  
+ Args:
+   uri:
+     The uri of this list.
+
+ +
+
SetUser(self, user)
+
Set the user of this list.
+  
+ Args:
+   user:
+     The owner of this list.
+
+ +
+
__eq__(self, other)
+
+ +
+
__init__(self, id=None, + name=None, slug=None, + description=None, full_name=None, mode=None, uri=None, member_count=None, + subscriber_count=None, following=None, user=None) +
+
+ +
+
__ne__(self, other)
+
+ +
+
__str__(self)
+
A string representation of this twitter.List instance.
+  
+ The return value is the same as the JSON string representation.
+  
+ Returns:
+   A string representation of this twitter.List instance.
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data)
+
+ Create a new instance based on a JSON dict.
+  
+ Args:
+   data:
+     A JSON dict, as converted from the JSON in the twitter API
+  
+ Returns:
+   A twitter.List instance
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+
description
+
The description of this list.
+
+
+
following
+
The following status of this list.
+
+
+
full_name
+
The full_name of this list.
+
+
+
id
+
The unique id of this list.
+
+
+
member_count
+
The member_count of this list.
+
+
+
mode
+
The mode of this list.
+
+
+
name
+
The real name of this list.
+
+
+
slug
+
The slug of this list.
+
+
+
subscriber_count
+
The subscriber_count of this list.
+
+
+
uri
+
The uri of this list.
+
+
+
user
+
The owner of this list.
+
+
+

+ + + + + + + + + + + + + +
 
+ class Status(__builtin__.object)
   A class representing the Status structure used by the twitter API.
+  
+ The Status structure exposes the following properties:
+  
+   status.created_at
+   status.created_at_in_seconds # read only
+   status.favorited
+   status.in_reply_to_screen_name
+   status.in_reply_to_user_id
+   status.in_reply_to_status_id
+   status.truncated
+   status.source
+   status.id
+   status.text
+   status.location
+   status.relative_created_at # read only
+   status.user
+   status.urls
+   status.user_mentions
+   status.hashtags
 
 Methods defined here:
+
+
AsDict(self)
+
A dict representation of this twitter.Status instance.
+  
+ The return value uses the same key names as the JSON representation.
+  
+ Return:
+   A dict representing this twitter.Status instance
+
+
+ +
+
AsJsonString(self)
+
A JSON string representation of this twitter.Status instance.
+  
+ Returns:
+   A JSON string representation of this twitter.Status instance
+
+ +
+
GetCreatedAt(self)
+
Get the time this status message was posted.
+  
+ Returns:
+   The time this status message was posted
+
+
+ +
+
GetCreatedAtInSeconds(self) +
+
Get the time this status message was posted, in seconds since the epoch.
+  
+ Returns:
+   The time this status message was posted, in seconds since the epoch.
+
+
+ +
+
GetFavorited(self)
+
Get the favorited setting of this status message.
+  
+ Returns:
+   True if this status message is favorited; False otherwise
+
+
+ +
+
GetId(self)
+
Get the unique id of this status message.
+  
+ Returns:
+   The unique id of this status message
+
+ +
+
GetInReplyToScreenName(self) +
+
+ +
+
GetInReplyToStatusId(self) +
+
+ +
+
GetInReplyToUserId(self)
+
+ +
+
GetLocation(self)
+
Get the geolocation associated with this status message
+  
+ Returns:
+   The geolocation string of this status message.
+
+
+ +
+
GetNow(self)
+
+ Get the wallclock time for this status message.
+  
+ Used to calculate relative_created_at.  Defaults to the time
+ the object was instantiated.
+  
+ Returns:
+   Whatever the status instance believes the current time to be,
+   in seconds since the epoch.
+
+ +
+
GetRelativeCreatedAt(self) +
+
Get a human redable string representing the posting time
+  
+ Returns:
+   A human readable string representing the posting time
+
+
+ +
+
GetSource(self)
+
+ +
+
GetText(self)
+
Get the text of this status message.
+  
+ Returns:
+   The text of this status message.
+
+ +
+
GetTruncated(self)
+
+ +
+
GetUser(self)
+
Get a twitter.User reprenting the entity posting this status message.
+  
+ Returns:
+   A twitter.User reprenting the entity posting this status message
+
+
+ +
+
SetCreatedAt(self, created_at)
+
Set the time this status message was posted.
+  
+ Args:
+   created_at:
+     The time this status message was created
+
+
+ +
+
SetFavorited(self, favorited)
+
+ Set the favorited state of this status message.
+  
+ Args:
+   favorited:
+     boolean True/False favorited state of this status message
+
+
+ +
+
SetId(self, id)
+
Set the unique id of this status message.
+  
+ Args:
+   id:
+     The unique id of this status message
+
+
+ +
+
SetInReplyToScreenName(self, + in_reply_to_screen_name) +
+
+ +
+
SetInReplyToStatusId(self, + in_reply_to_status_id) +
+
+ +
+
SetInReplyToUserId(self, + in_reply_to_user_id) +
+
+ +
+
SetLocation(self, location)
+
Set the geolocation associated with this status message
+  
+ Args:
+   location:
+     The geolocation string of this status message
+
+
+ +
+
SetNow(self, now)
+
+ Set the wallclock time for this status message.
+  
+ Used to calculate relative_created_at.  Defaults to the time
+ the object was instantiated.
+  
+ Args:
+   now:
+     The wallclock time for this instance.
+
+
+ +
+
SetSource(self, source)
+
+ +
+
SetText(self, text)
+
Set the text of this status message.
+  
+ Args:
+   text:
+     The text of this status message
+
+
+ +
+
SetTruncated(self, truncated)
+
+ +
+
SetUser(self, user)
+
Set a twitter.User reprenting the entity posting this status message.
+  
+ Args:
+   user:
+     A twitter.User reprenting the entity posting this status message
+
+
+ +
+
__eq__(self, other)
+
+ +
+
__init__(self, created_at=None, favorited=None, id=None, text=None, location=None, user=None, + in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, + source=None, now=None, + urls=None, user_mentions=None, + hashtags=None) +
+
An object to hold a Twitter status message.
+  
+ This class is normally instantiated by the twitter.Api class and
+ returned in a sequence.
+  
+ Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
+  
+ Args:
+   created_at:
+     The time this status message was posted. [Optiona]
+   favorited:
+     Whether this is a favorite of the authenticated user. [Optiona]
+   id:
+     The unique id of this status message. [Optiona]
+   text:
+     The text of this status message. [Optiona]
+   location:
+     the geolocation string associated with this message. [Optiona]
+   relative_created_at:
+     A human readable string representing the posting time. [Optiona]
+   user:
+     A twitter.User instance representing the person posting the
+     message. [Optiona]
+   now:
+     The current time, if the client choses to set it.
+     Defaults to the wall clock time. [Optiona]
+
+
+ +
+
__ne__(self, other)
+
+ +
+
__str__(self)
+
A string representation of this twitter.Status instance.
+  
+ The return value is the same as the JSON string representation.
+  
+ Returns:
+   A string representation of this twitter.Status instance.
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data)
+
+ Create a new instance based on a JSON dict.
+  
+ Args:
+   data: A JSON dict, as converted from the JSON in the twitter API
+ Returns:
+   A twitter.Status instance
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+
created_at
+
The time this status message was posted.
+
+
+
created_at_in_seconds
+
The time this status message was posted, in seconds since the epoch +
+
+
+
favorited
+
The favorited state of this status message.
+
+
+
id
+
The unique id of this status message.
+
+
+
in_reply_to_screen_name
+
+
+
+
in_reply_to_status_id
+
+
+
+
in_reply_to_user_id
+
+
+
+
location
+
The geolocation string of this status message +
+
+
+
now
+
The wallclock time for this status instance.
+
+
+
relative_created_at
+
Get a human readable string representing the posting time +
+
+
+
source
+
+
+
+
text
+
The text of this status message
+
+
+
truncated
+
+
+
+
user
+
A twitter.User reprenting the entity posting this status message +
+
+
+

+ + + + + + + + + + + + + +
 
+ class + Trend(__builtin__.object) +
   A class representing a trending topic
 
 Methods defined here:
+
+
__init__(self, name=None, + query=None, timestamp=None) +
+
+ +
+
__str__(self)
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data, + timestamp=None) +
+
+ Create a new instance based on a JSON dict
+  
+ Args:
+   data:
+     A JSON dict
+   timestamp:
+     Gets set as the timestamp property of the new object
+  
+ Returns:
+   A twitter.Trend object
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+

+ + + + + + + + + + + + + +
 
+ class + TwitterError(exceptions.Exception)
   Base class for Twitter errors
 
  +
+
Method resolution order:
+
TwitterError
+
exceptions.Exception
+
exceptions.BaseException
+
__builtin__.object
+
+
+ Data descriptors defined here:
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+
message
+
Returns the first argument used to construct this error. +
+
+
+ Methods inherited from exceptions.Exception:
+
+
__init__(...)
+
x.__init__(...) initializes x; see x.__class__.__doc__ for signature +
+
+ +
+ Data and other attributes inherited from exceptions.Exception:
+
+
__new__ = <built-in method __new__ of type object at 0x100119f80> +
T.__new__(S, ...) -> a new object with type S, a subtype of T +
+ +
+ Methods inherited from exceptions.BaseException:
+
+
__delattr__(...)
+
x.__delattr__('name') <==> del x.name +
+
+ +
+
__getattribute__(...)
+
x.__getattribute__('name') <==> x.name +
+
+ +
+
__getitem__(...)
+
x.__getitem__(y) <==> x[y] +
+
+ +
+
__getslice__(...)
+
x.__getslice__(i, j) <==> x[i:j]
+  
+ Use of negative indices is not supported.
+
+ +
+
__reduce__(...)
+
+ +
+
__repr__(...)
+
x.__repr__() <==> repr(x) +
+
+ +
+
__setattr__(...)
+
x.__setattr__('name', value) <==> x.name = value +
+
+ +
+
__setstate__(...)
+
+ +
+
__str__(...)
+
x.__str__() <==> str(x) +
+
+ +
+
__unicode__(...)
+
+ +
+ Data descriptors inherited from exceptions.BaseException:
+
+
__dict__
+
+
+
args
+
+
+

+ + + + + + + + + + + + + +
 
+ class Url(__builtin__.object)
   A class representing an URL contained in a tweet
  +
 Methods defined here:
+
+
__init__(self, url=None, + expanded_url=None) +
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data)
+
+ Create a new instance based on a JSON dict.
+  
+ Args:
+   data:
+     A JSON dict, as converted from the JSON in the twitter API
+  
+ Returns:
+   A twitter.Url instance
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+

+ + + + + + + + + + + + + +
 
+ class User(__builtin__.object)
   A class representing the User structure used by the twitter API.
+  
+ The User structure exposes the following properties:
+  
+   user.id
+   user.name
+   user.screen_name
+   user.location
+   user.description
+   user.profile_image_url
+   user.profile_background_tile
+   user.profile_background_image_url
+   user.profile_sidebar_fill_color
+   user.profile_background_color
+   user.profile_link_color
+   user.profile_text_color
+   user.protected
+   user.utc_offset
+   user.time_zone
+   user.url
+   user.status
+   user.statuses_count
+   user.followers_count
+   user.friends_count
+   user.favourites_count
 
 Methods defined here:
+
+
AsDict(self)
+
A dict representation of this twitter.User instance.
+  
+ The return value uses the same key names as the JSON representation.
+  
+ Return:
+   A dict representing this twitter.User instance
+
+ +
+
AsJsonString(self)
+
A JSON string representation of this twitter.User instance.
+  
+ Returns:
+   A JSON string representation of this twitter.User instance
+
+ +
+
GetDescription(self)
+
Get the short text description of this user.
+  
+ Returns:
+   The short text description of this user
+
+
+ +
+
GetFavouritesCount(self)
+
Get the number of favourites for this user.
+  
+ Returns:
+   The number of favourites for this user.
+
+
+ +
+
GetFollowersCount(self)
+
Get the follower count for this user.
+  
+ Returns:
+   The number of users following this user.
+
+
+ +
+
GetFriendsCount(self)
+
Get the friend count for this user.
+  
+ Returns:
+   The number of users this user has befriended.
+
+
+ +
+
GetId(self)
+
Get the unique id of this user.
+  
+ Returns:
+   The unique id of this user
+
+ +
+
GetLocation(self)
+
Get the geographic location of this user.
+  
+ Returns:
+   The geographic location of this user
+
+ +
+
GetName(self)
+
Get the real name of this user.
+  
+ Returns:
+   The real name of this user
+
+ +
+
GetProfileBackgroundColor(self) +
+
+ +
+
+ GetProfileBackgroundImageUrl(self) +
+
+ +
+
GetProfileBackgroundTile(self) +
+
Boolean for whether to tile the profile background image.
+  
+ Returns:
+   True if the background is to be tiled, False if not, None if unset.
+
+
+ +
+
GetProfileImageUrl(self)
+
+ Get the url of the thumbnail of this user.
+  
+ Returns:
+   The url of the thumbnail of this user
+
+
+ +
+
GetProfileLinkColor(self)
+
+ +
+
+ GetProfileSidebarFillColor(self) +
+
+ +
+
GetProfileTextColor(self)
+
+ +
+
GetProtected(self)
+
+ +
+
GetScreenName(self)
+
Get the short twitter name of this user.
+  
+ Returns:
+   The short twitter name of this user
+
+ +
+
GetStatus(self)
+
Get the latest twitter.Status of this user.
+  
+ Returns:
+   The latest twitter.Status of this user
+
+
+ +
+
GetStatusesCount(self)
+
Get the number of status updates for this user.
+  
+ Returns:
+   The number of status updates for this user.
+
+
+ +
+
GetTimeZone(self)
+
Returns the current time zone string for the user.
+  
+ Returns:
+   The descriptive time zone string for the user.
+
+
+ +
+
GetUrl(self)
+
Get the homepage url of this user.
+  
+ Returns:
+   The homepage url of this user
+
+ +
+
GetUtcOffset(self)
+
+ +
+
SetDescription(self, description) +
+
Set the short text description of this user.
+  
+ Args:
+   description: The short text description of this user
+
+
+ +
+
SetFavouritesCount(self, count) +
+
Set the favourite count for this user.
+  
+ Args:
+   count:
+     The number of favourites for this user.
+
+
+ +
+
SetFollowersCount(self, count) +
+
Set the follower count for this user.
+  
+ Args:
+   count:
+     The number of users following this user.
+
+
+ +
+
SetFriendsCount(self, count)
+
Set the friend count for this user.
+  
+ Args:
+   count:
+     The number of users this user has befriended.
+
+
+ +
+
SetId(self, id)
+
Set the unique id of this user.
+  
+ Args:
+   id: The unique id of this user.
+
+ +
+
SetLocation(self, location)
+
Set the geographic location of this user.
+  
+ Args:
+   location: The geographic location of this user
+
+
+ +
+
SetName(self, name)
+
Set the real name of this user.
+  
+ Args:
+   name: The real name of this user
+
+ +
+
SetProfileBackgroundColor(self, + profile_background_color) +
+
+ +
+
+ SetProfileBackgroundImageUrl(self, + profile_background_image_url) +
+
+ +
+
SetProfileBackgroundTile(self, + profile_background_tile) +
+
Set the boolean flag for whether to tile the profile background image.
+  
+ Args:
+   profile_background_tile: Boolean flag for whether to tile or not.
+
+
+ +
+
SetProfileImageUrl(self, + profile_image_url) +
+
+ Set the url of the thumbnail of this user.
+  
+ Args:
+   profile_image_url: The url of the thumbnail of this user
+
+
+ +
+
SetProfileLinkColor(self, + profile_link_color) +
+
+ +
+
+ SetProfileSidebarFillColor(self, + profile_sidebar_fill_color) +
+
+ +
+
SetProfileTextColor(self, + profile_text_color) +
+
+ +
+
SetProtected(self, protected)
+
+ +
+
SetScreenName(self, screen_name)
+
Set the short twitter name of this user.
+  
+ Args:
+   screen_name: the short twitter name of this user
+
+
+ +
+
SetStatus(self, status)
+
Set the latest twitter.Status of this user.
+  
+ Args:
+   status:
+     The latest twitter.Status of this user
+
+
+ +
+
SetStatusesCount(self, count)
+
Set the status update count for this user.
+  
+ Args:
+   count:
+     The number of updates for this user.
+
+
+ +
+
SetTimeZone(self, time_zone)
+
Sets the user's time zone string.
+  
+ Args:
+   time_zone:
+     The descriptive time zone to assign for the user.
+
+
+ +
+
SetUrl(self, url)
+
Set the homepage url of this user.
+  
+ Args:
+   url: The homepage url of this user
+
+ +
+
SetUtcOffset(self, utc_offset)
+
+ +
+
__eq__(self, other)
+
+ +
+
__init__(self, id=None, + name=None, screen_name=None, + location=None, description=None, profile_image_url=None, profile_background_tile=None, profile_background_image_url=None, + profile_sidebar_fill_color=None, + profile_background_color=None, profile_link_color=None, profile_text_color=None, protected=None, + utc_offset=None, time_zone=None, followers_count=None, + friends_count=None, statuses_count=None, + favourites_count=None, url=None, status=None) +
+
+ +
+
__ne__(self, other)
+
+ +
+
__str__(self)
+
A string representation of this twitter.User instance.
+  
+ The return value is the same as the JSON string representation.
+  
+ Returns:
+   A string representation of this twitter.User instance.
+
+ +
+ Static methods defined here:
+
+
NewFromJsonDict(data)
+
+ Create a new instance based on a JSON dict.
+  
+ Args:
+   data:
+     A JSON dict, as converted from the JSON in the twitter API
+  
+ Returns:
+   A twitter.User instance
+
+ +
+ Data descriptors defined here:
+
+
__dict__
+
dictionary for instance variables (if defined)
+
+
+
__weakref__
+
list of weak references to the object (if defined) +
+
+
+
description
+
The short text description of this user.
+
+
+
favourites_count
+
The number of favourites for this user.
+
+
+
followers_count
+
The number of users following this user.
+
+
+
friends_count
+
The number of friends for this user.
+
+
+
id
+
The unique id of this user.
+
+
+
location
+
The geographic location of this user.
+
+
+
name
+
The real name of this user.
+
+
+
profile_background_color
+
+
+
profile_background_image_url
+
The url of the profile background of this user. +
+
+
+
profile_background_tile
+
+ Boolean for whether to tile the background image. +
+
+
+
profile_image_url
+
The url of the thumbnail of this user.
+
+
+
profile_link_color
+
+
+
profile_sidebar_fill_color
+
+
+
profile_text_color
+
+
+
protected
+
+
+
screen_name
+
The short twitter name of this user.
+
+
+
status
+
The latest twitter.Status of this user.
+
+
+
statuses_count
+
The number of updates for this user.
+
+
+
time_zone
+
Returns the current time zone string for the user.
+  
+ Returns:
+   The descriptive time zone string for the user.
+
+
+
+
url
+
The homepage url of this user.
+
+
+
utc_offset
+
+
+ + + +

- - - - -
 
-Functions
       
md5 = openssl_md5(...)
Returns a md5 hash object; optionally initialized with a string
-

+ +  
+ Functions + + + +        +   + +

+
md5 = openssl_md5(...)
+
Returns a md5 hash object; optionally initialized with a string +
+
+ + + +

- - - - -
 
-Data
       ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
-AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
-CHARACTER_LIMIT = 140
-DEFAULT_CACHE = <object object at 0x1001da0a0>
-REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
-SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'
-__author__ = 'python-twitter@googlegroups.com'
-__version__ = '0.8'

+ +  
+ Data + + + +        +   + ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
+ AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
+ CHARACTER_LIMIT = 140
+ DEFAULT_CACHE = <object object at 0x1001da0a0>
+ REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
+ SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'
+ __author__ = 'python-twitter@googlegroups.com'
+ __version__ = '0.8' + + + +

- - - - -
 
-Author
       python-twitter@googlegroups.com
- \ No newline at end of file + +  
+ Author + + + +        +   + python-twitter@googlegroups.com + + + + diff --git a/doc/twitter.rst b/doc/twitter.rst new file mode 100644 index 00000000..331b82e9 --- /dev/null +++ b/doc/twitter.rst @@ -0,0 +1,38 @@ +Modules Documentation +===================== + + +API +---------------- + +.. automodule:: twitter.api + :members: + :undoc-members: + :show-inheritance: + +.. automodule:: twitter.error + :members: + :undoc-members: + :show-inheritance: + +Models +--------------------- + +.. automodule:: twitter.models + :members: + :undoc-members: + :show-inheritance: + +.. automodule:: twitter.ratelimit + :members: + :undoc-members: + :show-inheritance: + + +Utilities +--------------------- + +.. automodule:: twitter.twitter_utils + :members: + :undoc-members: + :show-inheritance: diff --git a/doc/with_django.rst b/doc/with_django.rst new file mode 100644 index 00000000..a0006347 --- /dev/null +++ b/doc/with_django.rst @@ -0,0 +1,4 @@ +Using with Django +================= + +Additional template tags that expand tweet urls and urlize tweet text. See the django template tags available for use with python-twitter: https://github.com/radzhome/python-twitter-django-tags \ No newline at end of file diff --git a/examples/get_all_user_tweets.py b/examples/get_all_user_tweets.py new file mode 100644 index 00000000..96524250 --- /dev/null +++ b/examples/get_all_user_tweets.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Downloads all tweets from a given user. + +Uses twitter.Api.GetUserTimeline to retreive the last 3,200 tweets from a user. +Twitter doesn't allow retreiving more tweets than this through the API, so we get +as many as possible. + +t.py should contain the imported variables. +""" + +from __future__ import print_function + +import json +import sys + +import twitter +from t import ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET + + +def get_tweets(api=None, screen_name=None): + timeline = api.GetUserTimeline(screen_name=screen_name, count=200) + earliest_tweet = min(timeline, key=lambda x: x.id).id + print("getting tweets before:", earliest_tweet) + + while True: + tweets = api.GetUserTimeline( + screen_name=screen_name, max_id=earliest_tweet, count=200 + ) + new_earliest = min(tweets, key=lambda x: x.id).id + + if not tweets or new_earliest == earliest_tweet: + break + else: + earliest_tweet = new_earliest + print("getting tweets before:", earliest_tweet) + timeline += tweets + + return timeline + + +if __name__ == "__main__": + api = twitter.Api( + CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET + ) + screen_name = sys.argv[1] + print(screen_name) + timeline = get_tweets(api=api, screen_name=screen_name) + + with open('examples/timeline.json', 'w+') as f: + for tweet in timeline: + f.write(json.dumps(tweet._json)) + f.write('\n') diff --git a/examples/shorten_url.py b/examples/shorten_url.py old mode 100644 new mode 100755 index 7af69a36..e07ee7a3 --- a/examples/shorten_url.py +++ b/examples/shorten_url.py @@ -1,71 +1,147 @@ -#!/usr/bin/python2.4 -# -# Copyright 2007 The Python-Twitter Developers -# +#!/usr/bin/env python + +# Copyright 2007-2016 The Python-Twitter Developers + # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# + +# http://www.apache.org/licenses/LICENSE-2.0 + # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -'''A class that defines the default URL Shortener. +# ---------------------------------------------------------------------- +# Change History +# +# 2010-05-16 +# TinyURL example and the idea for this comes from a bug filed by +# acolorado with patch provided by ghills. Class implementation +# was done by @bear. +# +# Issue #19: http://code.google.com/p/python-twitter/issues/detail?id=19 +# +# 2016-02-18 +# Updated example with code to demonstrate passing a status message through +# a shortener and then off to PostUpdate. Implemenation by @jeremylow from +# bug filed by @immanuelfactor +# +# Issue #298: https://github.com/bear/python-twitter/issues/298 -TinyURL is provided as the default and as an example. -''' +# ---------------------------------------------------------------------- +# This file demonstrates how to shorten all URLs contained within a Tweet +# by passing the tweet text to a shortener. In this case, we're using TinyURL +# since it does not require any real authentication for our purposes. If you +# are using a different service to shorten URLs, then you will need to modify +# the ShortenURL class to suit your needs. -import urllib +# Note that this example shortens all URLs contained within the Tweet text. +# To use this example, replace the W/X/Y/Zs with your keys obtained from +# Twitter, or uncomment the lines for getting an environment variable. If you +# are using a virtualenv on Linux, you can set environment variables in the +# ~/VIRTUALENVDIR/bin/activate script. - # Change History - # - # 2010-05-16 - # TinyURL example and the idea for this comes from a bug filed by - # acolorado with patch provided by ghills. Class implementation - # was done by bear. - # - # Issue 19 http://code.google.com/p/python-twitter/issues/detail?id=19 - # +# If you need assistance with obtaining keys from Twitter, see the instructions +# in doc/getting_started.rst. + + +import re +try: + from urllib.request import urlopen +except: + from urllib2 import urlopen + +from twitter import Api +from twitter.twitter_utils import URL_REGEXP class ShortenURL(object): - '''Helper class to make URL Shortener calls if/when required''' + """ A class that defines the default URL Shortener. + + TinyURL is provided as the default and as an example helper class to make + URL Shortener calls if/when required. """ + def __init__(self, userid=None, password=None): - '''Instantiate a new ShortenURL object - + """Instantiate a new ShortenURL object. TinyURL, which is used for this + example, does not require a userid or password, so you can try this + out without specifying either. + Args: userid: userid for any required authorization call [optional] password: password for any required authorization call [optional] - ''' - self.userid = userid + """ + self.userid = userid self.password = password def Shorten(self, - longURL): - '''Call TinyURL API and returned shortened URL result - + long_url): + """ Call TinyURL API and returned shortened URL result. + Args: - longURL: URL string to shorten - + long_url: URL string to shorten + Returns: The shortened URL as a string Note: - longURL is required and no checks are made to ensure completeness - ''' + long_url is required and no checks are made to ensure completeness + """ result = None - f = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % longURL) + f = urlopen("http://tinyurl.com/api-create.php?url={0}".format( + long_url)) try: result = f.read() finally: f.close() - return result + # The following check is required for py2/py3 compatibility, since + # urlopen on py3 returns a bytes-object, and urlopen on py2 returns a + # string. + if isinstance(result, bytes): + return result.decode('utf8') + else: + return result + + +def _get_api(): + # Either specify a set of keys here or use os.getenv('CONSUMER_KEY') style + # assignment: + + CONSUMER_KEY = 'WWWWWWWW' + # CONSUMER_KEY = os.getenv("CONSUMER_KEY", None) + CONSUMER_SECRET = 'XXXXXXXX' + # CONSUMER_SECRET = os.getenv("CONSUMER_SECRET", None) + ACCESS_TOKEN = 'YYYYYYYY' + # ACCESS_TOKEN = os.getenv("ACCESS_TOKEN", None) + ACCESS_TOKEN_SECRET = 'ZZZZZZZZ' + # ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET", None) + + return Api(CONSUMER_KEY, + CONSUMER_SECRET, + ACCESS_TOKEN, + ACCESS_TOKEN_SECRET) + + +def PostStatusWithShortenedURL(status): + shortener = ShortenURL() + api = _get_api() + + # Find all URLs contained within the status message. Value of ``urls`` will + # be a list. + urls = re.findall(URL_REGEXP, status) + + for url in urls: + status = status.replace(url, shortener.Shorten(url), 1) + + api.PostUpdate(status) + + +if __name__ == '__main__': + PostStatusWithShortenedURL("this is a test: http://www.example.com/tests") diff --git a/examples/streaming/track_users.py b/examples/streaming/track_users.py new file mode 100644 index 00000000..faa37565 --- /dev/null +++ b/examples/streaming/track_users.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python + +# Copyright 2007-2016 The Python-Twitter Developers + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ---------------------------------------------------------------------- + +# This file demonstrates how to track mentions of a specific set of users in +# english language and archive those mentions to a local file. The output +# file will contain one JSON string per line per Tweet. + +# To use this example, replace the W/X/Y/Zs with your keys obtained from +# Twitter, or uncomment the lines for getting an environment variable. If you +# are using a virtualenv on Linux, you can set environment variables in the +# ~/VIRTUALENVDIR/bin/activate script. + +# If you need assistance with obtaining keys from Twitter, see the instructions +# in doc/getting_started.rst. + +import os +import json + +from twitter import Api + +# Either specify a set of keys here or use os.getenv('CONSUMER_KEY') style +# assignment: + +CONSUMER_KEY = 'WWWWWWWW' +# CONSUMER_KEY = os.getenv("CONSUMER_KEY", None) +CONSUMER_SECRET = 'XXXXXXXX' +# CONSUMER_SECRET = os.getenv("CONSUMER_SECRET", None) +ACCESS_TOKEN = 'YYYYYYYY' +# ACCESS_TOKEN = os.getenv("ACCESS_TOKEN", None) +ACCESS_TOKEN_SECRET = 'ZZZZZZZZ' +# ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET", None) + +# Users to watch for should be a list. This will be joined by Twitter and the +# data returned will be for any tweet mentioning: +# @twitter *OR* @twitterapi *OR* @support. +USERS = ['@twitter', + '@twitterapi', + '@support'] + +# Languages to filter tweets by is a list. This will be joined by Twitter +# to return data mentioning tweets only in the english language. +LANGUAGES = ['en'] + +# Since we're going to be using a streaming endpoint, there is no need to worry +# about rate limits. +api = Api(CONSUMER_KEY, + CONSUMER_SECRET, + ACCESS_TOKEN, + ACCESS_TOKEN_SECRET) + + +def main(): + with open('output.txt', 'a') as f: + # api.GetStreamFilter will return a generator that yields one status + # message (i.e., Tweet) at a time as a JSON dictionary. + for line in api.GetStreamFilter(track=USERS, languages=LANGUAGES): + f.write(json.dumps(line)) + f.write('\n') + + +if __name__ == '__main__': + main() diff --git a/examples/tweet.py b/examples/tweet.py index 131b6e7b..ae76b7d0 100755 --- a/examples/tweet.py +++ b/examples/tweet.py @@ -1,16 +1,23 @@ -#!/usr/bin/python2.4 +#!/usr/bin/env python '''Post a message to twitter''' __author__ = 'dewitt@google.com' -import ConfigParser +from __future__ import print_function + +try: + import configparser +except ImportError as _: + import ConfigParser as configparser + import getopt import os import sys import twitter + USAGE = '''Usage: tweet [options] message This script posts a message to Twitter. @@ -30,7 +37,7 @@ variables TWEETUSERNAME and TWEETPASSWORD will then be checked for your consumer_key or consumer_secret, respectively. - If neither the command line flags nor the enviroment variables are + If neither the command line flags nor the environment variables are present, the .tweetrc file, if it exists, can be used to set the default consumer_key and consumer_secret. The file should contain the following three lines, replacing *consumer_key* with your consumer key, and @@ -46,96 +53,104 @@ ''' + def PrintUsageAndExit(): - print USAGE - sys.exit(2) + print(USAGE) + sys.exit(2) + def GetConsumerKeyEnv(): - return os.environ.get("TWEETUSERNAME", None) + return os.environ.get("TWEETUSERNAME", None) + def GetConsumerSecretEnv(): - return os.environ.get("TWEETPASSWORD", None) + return os.environ.get("TWEETPASSWORD", None) + def GetAccessKeyEnv(): - return os.environ.get("TWEETACCESSKEY", None) + return os.environ.get("TWEETACCESSKEY", None) + def GetAccessSecretEnv(): - return os.environ.get("TWEETACCESSSECRET", None) + return os.environ.get("TWEETACCESSSECRET", None) + class TweetRc(object): - def __init__(self): - self._config = None + def __init__(self): + self._config = None - def GetConsumerKey(self): - return self._GetOption('consumer_key') + def GetConsumerKey(self): + return self._GetOption('consumer_key') - def GetConsumerSecret(self): - return self._GetOption('consumer_secret') + def GetConsumerSecret(self): + return self._GetOption('consumer_secret') - def GetAccessKey(self): - return self._GetOption('access_key') + def GetAccessKey(self): + return self._GetOption('access_key') - def GetAccessSecret(self): - return self._GetOption('access_secret') + def GetAccessSecret(self): + return self._GetOption('access_secret') - def _GetOption(self, option): - try: - return self._GetConfig().get('Tweet', option) - except: - return None + def _GetOption(self, option): + try: + return self._GetConfig().get('Tweet', option) + except: + return None + + def _GetConfig(self): + if not self._config: + self._config = configparser.ConfigParser() + self._config.read(os.path.expanduser('~/.tweetrc')) + return self._config - def _GetConfig(self): - if not self._config: - self._config = ConfigParser.ConfigParser() - self._config.read(os.path.expanduser('~/.tweetrc')) - return self._config def main(): - try: - shortflags = 'h' - longflags = ['help', 'consumer-key=', 'consumer-secret=', - 'access-key=', 'access-secret=', 'encoding='] - opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) - except getopt.GetoptError: - PrintUsageAndExit() - consumer_keyflag = None - consumer_secretflag = None - access_keyflag = None - access_secretflag = None - encoding = None - for o, a in opts: - if o in ("-h", "--help"): - PrintUsageAndExit() - if o in ("--consumer-key"): - consumer_keyflag = a - if o in ("--consumer-secret"): - consumer_secretflag = a - if o in ("--access-key"): - access_keyflag = a - if o in ("--access-secret"): - access_secretflag = a - if o in ("--encoding"): - encoding = a - message = ' '.join(args) - if not message: - PrintUsageAndExit() - rc = TweetRc() - consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey() - consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret() - access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey() - access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret() - if not consumer_key or not consumer_secret or not access_key or not access_secret: - PrintUsageAndExit() - api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, - access_token_key=access_key, access_token_secret=access_secret, - input_encoding=encoding) - try: - status = api.PostUpdate(message) - except UnicodeDecodeError: - print "Your message could not be encoded. Perhaps it contains non-ASCII characters? " - print "Try explicitly specifying the encoding with the --encoding flag" - sys.exit(2) - print "%s just posted: %s" % (status.user.name, status.text) + try: + shortflags = 'h' + longflags = ['help', 'consumer-key=', 'consumer-secret=', + 'access-key=', 'access-secret=', 'encoding='] + opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) + except getopt.GetoptError: + PrintUsageAndExit() + consumer_keyflag = None + consumer_secretflag = None + access_keyflag = None + access_secretflag = None + encoding = None + for o, a in opts: + if o in ("-h", "--help"): + PrintUsageAndExit() + if o in ("--consumer-key"): + consumer_keyflag = a + if o in ("--consumer-secret"): + consumer_secretflag = a + if o in ("--access-key"): + access_keyflag = a + if o in ("--access-secret"): + access_secretflag = a + if o in ("--encoding"): + encoding = a + message = ' '.join(args) + if not message: + PrintUsageAndExit() + rc = TweetRc() + consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey() + consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret() + access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey() + access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret() + if not consumer_key or not consumer_secret or not access_key or not access_secret: + PrintUsageAndExit() + api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, + access_token_key=access_key, access_token_secret=access_secret, + input_encoding=encoding) + try: + status = api.PostUpdate(message) + except UnicodeDecodeError: + print("Your message could not be encoded. Perhaps it contains non-ASCII characters? ") + print("Try explicitly specifying the encoding with the --encoding flag") + sys.exit(2) + + print("{0} just posted: {1}".format(status.user.name, status.text)) if __name__ == "__main__": - main() + main() diff --git a/examples/twitter-to-xhtml.py b/examples/twitter-to-xhtml.py index 441d97ec..57b38470 100755 --- a/examples/twitter-to-xhtml.py +++ b/examples/twitter-to-xhtml.py @@ -1,69 +1,75 @@ -#!/usr/bin/python2.4 +#!/usr/bin/env python -'''Load the latest update for a Twitter user and leave it in an XHTML fragment''' +# Copyright 2007-2016 The Python-Twitter Developers +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -__author__ = 'dewitt@google.com' +# ------------------------------------------------------------------------ +# Load the latest update for a Twitter user and output it as an HTML fragment +# +from __future__ import print_function import codecs -import getopt import sys +import argparse + import twitter +from t import * + +__author__ = 'dewitt@google.com' + TEMPLATE = """ -