Giter VIP home page Giter VIP logo

python-twitter's Introduction

Python Twitter

A Python wrapper around the Twitter API.

By the Python-Twitter Developers

Downloads

Documentation Status

Circle CI

Codecov

Requirements Status

Dependency Status

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:

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.

python-twitter's People

Contributors

andkon avatar bear avatar chaitanya0411 avatar d2dcrc-wdp avatar danielthepope avatar daniilr avatar derpwanda avatar golopot avatar greedo avatar harrywy avatar ianozsvald avatar integersofk avatar jarobins avatar jeremylow avatar jonathan-s avatar kldykstra avatar larsweiler avatar mistersalmon avatar mkdadi avatar nxexox avatar pistachiopony avatar radzhome avatar rbpasker avatar sebastianw avatar sharkykh avatar sjml avatar trevorprater avatar tuftedocelot avatar vepiphyte avatar yu9824 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-twitter's Issues

Add language field in class Status

lang String Nullable.
When present, indicates a BCP 47 language identifier corresponding to the machine-detected language of the Tweet text, or "und" if no language could be detected.

Note: As of March 15, 2013, this field is available on REST but not Streaming. Keep an eye on the Calendar of API changes for changes. This documentation will be updated once the parameter is generally available.

I think it will be easy to add this filed to the class, and we should : )

GetFollowerIDs error

When GetFollowerIDs is used on somebody who has a lot of followers (say Justin Beiber) the program will crash:

Traceback (most recent call last):
File "twitter.py", line 11, in
users = api.GetFollowerIDs(screen_name='justinbieber')
File "/usr/local/lib/python2.7/dist-packages/twitter.py", line 3320, in GetFollowerIDs
total_count -= len(data['ids'])
TypeError: unsupported operand type(s) for -=: 'NoneType' and 'int'

File cache problem

File cache does not work, because the parameter oauth_nonce change in every request, creating a new cache file for all requests.

Retrieving media entities

Should ensure that each function call that goes to Twitter has the ability to set the parameters to include_entities.

For example, Get Mentions. I added include entities like shown:

def GetMentions(self,
since_id=None,
max_id=None,
page=None,
include_entities=None):

More importantly, in line 616, 'urls' needs to be changed to 'media' to actually retrieve the data. Urls doesn't return data. See https://dev.twitter.com/docs/tweet-entities

Here is my new line 616 and 617

616 if 'media' in data['entities']: ###changed 'urls' to 'media'
617 urls = [Url.NewFromJsonDict(u) for u in data['entities']['media']] #changed 'urls' to 'media'

Error running commands

Any idea why this is happening? Thanks! I'm trying to run basic commands as I just finished installing the api. Before this I imported twitter and set api=twitter.Api().

statuses = api.GetUserTimeline("Grumpy Cat")

Traceback (most recent call last):
File "<pyshell#10>", line 1, in
statuses = api.GetUserTimeline("Grumpy Cat")
File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 2721, in GetUserTimeline
data = self._ParseAndCheckTwitter(json)
File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 3875, in _ParseAndCheckTwitter
raise TwitterError("json decoding")
TwitterError: json decoding

statuses = api.GetUserTimeline(screen_name="Grumpy Cat")

Traceback (most recent call last):
File "<pyshell#11>", line 1, in
statuses = api.GetUserTimeline(screen_name="Grumpy Cat")
File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 2721, in GetUserTimeline
data = self._ParseAndCheckTwitter(json)
File "/usr/local/lib/python2.7/dist-packages/python_twitter-0.8.5-py2.7.egg/twitter.py", line 3875, in _ParseAndCheckTwitter
raise TwitterError("json decoding")
TwitterError: json decoding

returning Attribute error when tring to access publictimeline

Traceback (most recent call last):
File "C:\workspace\twitter\tt_tmp.py", line 9, in
statuses = api.GetPublicTimeline()
File "build\bdist.win32\egg\twitter.py", line 2301, in GetPublicTimeline
File "build\bdist.win32\egg\twitter.py", line 620, in NewFromJsonDict
AttributeError: 'unicode' object has no attribute 'get'

python-twitter 0.8.2, Python 2.7 on Win7 64bit.

GetUserTimeline works fine but GetPublicTimeline is returning this error. I guess Problem is in old api version.

The whole package breaks while running in virtualenv, due to cache issues

Hi there,

I have implemented the Twitter api to fetch some feeds. I am using Django cache to handle the cached feeds.

Though, python-twitter is breaking the server with a 500 error as follows:

OSError: [Errno 13] Permission denied: '/tmp/python.cache_nobody/8/2/a'

I'm not running the website as root and not willing to do so for obvious security reasons.

Is there a work around to this, or an option to disable caching altogether?

I will look forward to your response.

Guillaume

Does not work[times out] from behind an HTTP proxy

I've tried using it behind an HTTP proxy and it times out.
Here is the error log
File "bot.py", line 30, in <module> status = twitter.Api.GetStatus(api, tweets["results"][i]["id"]) File "build/bdist.linux-x86_64/egg/twitter.py", line 2743, in GetStatus File "build/bdist.linux-x86_64/egg/twitter.py", line 3930, in _FetchUrl File "/usr/lib/python2.7/urllib2.py", line 400, in open response = self._open(req, data) File "/usr/lib/python2.7/urllib2.py", line 418, in _open '_open', req) File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open return self.do_open(httplib.HTTPSConnection, req) File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open raise URLError(err) urllib2.URLError: <urlopen error [Errno 110] Connection timed out>

Api.UserLookUp() throws attribute error when corresponding screen_name is not found

I'm trying to do user-look up by screen_name, when I use a screen name that is not registered in twitter it throws attribute error. example trial goes below:

users = api.UsersLookup(screen_name=["dude_whats_up_is_your_name"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "twitter.py", line 3049, in UsersLookup
    return [User.NewFromJsonDict(u) for u in data]
  File "twitter.py", line 1340, in NewFromJsonDict
    return User(id=data.get('id', None),
AttributeError: 'unicode' object has no attribute 'get'

I'm not sure if this is a design decision or a issue, please close it if it's done deliberately, otherwise I think it helps.

api.GetUser throwing twitter api error

In version 1.0 of the api, I'm getting errors from twitter:

[{u'message': u'Sorry, that page does not exist', u'code': 34}]

Other api calls are working. I've authenticated before making the call.

Version 1.1 of Twitter API

Any plans on migrating this to use version 1.1 of the Twitter REST API?

Twitter API docs say:

Version 1 of the REST API is now deprecated and will cease
functioning in the coming months.

TypeError: __init__() got an unexpected keyword argument 'access_token_key'

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import twitter

class twitt():
    def __init__(self):
        consumer_key = '...'
        consumer_secret = '...'
        access_key = '...'
        access_secret = '...'

        encoding = 'iso-8859-15'

        self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding)

    def run(self):
        statuses = self.api.GetPublicTimeline()
        print statuses

h = twitt()
h.run()

This code doesn't work, it's taken directly from the readme and every example i find.
Then something about "get_access_token.py" and theres no reference to it!?

Error: TypeError: init() got an unexpected keyword argument 'access_token_key'

get_access_token.py attempts Web auth

In order to force OOB auth with the PIN, request_token needs a query string appended. This can also be specified as the default callback in the Twitter settings, but shouldn't be necessary.

REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob'

[PATCH] Fix include_rts

Last time I tried to submit a contribution via an external pull request it didn't turn to be as smooth as I thought it would (#57), so I just made a diff on master. I don't know if that is easier.

The patch includes two fixes:

  1. Replace "except:" with "except ValueError:" (except should never be used without a specific error)
  2. Fix include_rts: the default value is true, but currently, python-twitter never checks if it's set to false. This was fixed.

http://pastebin.com/raw.php?i=RLJhBCrk

Maximum character count check doesn't account for shortened URLs

In order to get maximum text packed into my tweets, I've started looking at the length of shortened URLs knowing that whatever URL I post will end up shorter. For now, I'm doing something like this:

# Get the current length of short URLs from Twitter
_short_url_length = 20
try:
    config = urllib2.urlopen(
        'https://api.twitter.com/1/help/configuration.json'
    ).read()
    _short_url_length = int(json.loads(config)['short_url_length'])
except:
    pass

Then if a URL is included in the tweet, I assume it's length is _short_url_length and check the length myself. (I did a nasty twitter.CHARACTER_COUNT = sys.maxint for the time being.) This needs some effort to work in the generic case, but I thought I would bring this up.

Make twitter.Api (1.1) functions that use cursor & count behave better

The functions (in API 1.1) that have a cursor and a count are currently wasting API calls because count is sent directly to the API. So a count = 1 would make an API call for every object that is retrieved. It would be better if count specifies the total sum of objects the function should return. In every cursor iteration we need to check if the total sum is reached and break out of the cursor loop.

Alternative: Don't iterate over the cursor and just return the objects and next_cursor variable.

Issue #1 fix at wrong place

You fixed this issue at the wrong place. As michaelmior said you have to update the "REQUEST_TOKEN_URL" @ line 57 and add "body='oauth_callback=oob' " to do a pin request.

same as issue #40

im getting the same error running python twitter_test.py
i am not sure how i should include the testdata directory as you've said
thanks

Version 1.1 of Twitter API, migration

Apologies if I am asking this in the wrong place but I am looking for a helping hand in upgrading a couple of python scripts to use the new Twitter API v1.1. The scripts that I have are working with v1 but they were developed by someone else that is no longer able to work on them because they are unwell.

In a nutshell what the scripts are designed to do is connect to https://stream.twitter.com/1/statuses/filter.json and check for tweets sent to specific @usernames, retrieve the tweet data and insert them into a MySQL database. Afterwards another script does some post-processing to move desired data into other tables and then clean up. There are a couple of other non-Twitter scripts that do some general MySQL housekeeping for stats etc.

I am sure this is quite trivial for some people but I'm stumbling around in the dark because I can't find a working example of doing something similar that uses v1.1. What I need to do is go through the scripts and replace the old JSON syntax with the new one.

For example v1...
messagelog = "tweet_id=%s:screen_name=%s:time_created=%s in twitter stream (tweet.py)" % (content['id_str'],content['user']['screen_name'],msgtime)

The scripts are only needed to fetch public tweets. I don't have to worry about any user logins or authentication issues. The original author has created a working method that ensures the scripts don't make too many API connections. Everything works fine and dandy in API v1 but needs minor tweaks for v1.1.

Please point me towards somewhere else to ask for help if this is the wrong place. I've already tried dev-twitter. Any help you can offer would be appreciated. Thank you.

regards James (QuotesUK)

Expanding the URL Class

It would be nice to expand the class URL to include more data. Right now, it returns the 'url', but it would be nice to also get the 'media_url_https' and maybe a few other variables. URL only returns the twitter page, if you want to download the actual file, you will need media_url_https

You can see all of the options here under 'entities' 'media'

https://dev.twitter.com/docs/tweet-entities

Why am I getting this error message? Running Xubuntu. I followed the steps in README.

EEEEEEEEEEEEEEEEEE........................

ERROR: testCreateFriendship (main.ApiTest)

Test the twitter.Api CreateFriendship method

Traceback (most recent call last):
File "twitter_test.py", line 496, in testCreateFriendship
user = self._api.CreateFriendship('dewitt')
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3350, in CreateFriendship
json = self._FetchUrl(url, post_data={'user': user})
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/friendship-create.json'

ERROR: testDestroyDirectMessage (main.ApiTest)

Test the twitter.Api DestroyDirectMessage method

Traceback (most recent call last):
File "twitter_test.py", line 488, in testDestroyDirectMessage
status = self._api.DestroyDirectMessage(3496342)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3335, in DestroyDirectMessage
json = self._FetchUrl(url, post_data={'id': id})
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/direct_message-destroy.json'

ERROR: testDestroyFriendship (main.ApiTest)

Test the twitter.Api DestroyFriendship method

Traceback (most recent call last):
File "twitter_test.py", line 504, in testDestroyFriendship
user = self._api.DestroyFriendship('dewitt')
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3365, in DestroyFriendship
json = self._FetchUrl(url, post_data={'user': user})
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/friendship-destroy.json'

ERROR: testDestroyStatus (main.ApiTest)

Test the twitter.Api DestroyStatus method

Traceback (most recent call last):
File "twitter_test.py", line 407, in testDestroyStatus
status = self._api.DestroyStatus(103208352)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2775, in DestroyStatus
json = self._FetchUrl(url, post_data={'id': id})
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/status-destroy.json'

ERROR: testGetDirectMessages (main.ApiTest)

Test the twitter.Api GetDirectMessages method

Traceback (most recent call last):
File "twitter_test.py", line 473, in testGetDirectMessages
statuses = self._api.GetDirectMessages(page=1)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3261, in GetDirectMessages
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/direct_messages.json'

ERROR: testGetFeatured (main.ApiTest)

Test the twitter.Api GetFeatured method

Traceback (most recent call last):
File "twitter_test.py", line 464, in testGetFeatured
users = self._api.GetFeatured()
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3158, in GetFeatured
json = self._FetchUrl(url)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/featured.json'

ERROR: testGetFollowers (main.ApiTest)

Test the twitter.Api GetFollowers method

Traceback (most recent call last):
File "twitter_test.py", line 455, in testGetFollowers
users = self._api.GetFollowers()
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3137, in GetFollowers
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/followers.json'

ERROR: testGetFriends (main.ApiTest)

Test the twitter.Api GetFriends method

Traceback (most recent call last):
File "twitter_test.py", line 447, in testGetFriends
users = self._api.GetFriends(cursor=123)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3052, in GetFriends
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/friends.json'

ERROR: testGetFriendsTimeline (main.ApiTest)

Test the twitter.Api GetFriendsTimeline method

Traceback (most recent call last):
File "twitter_test.py", line 390, in testGetFriendsTimeline
statuses = self._api.GetFriendsTimeline('kesuke')
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2601, in GetFriendsTimeline
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/friends_timeline-kesuke.json'

ERROR: testGetReplies (main.ApiTest)

Test the twitter.Api GetReplies method

Traceback (most recent call last):
File "twitter_test.py", line 433, in testGetReplies
statuses = self._api.GetReplies(page=1)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2955, in GetReplies
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/replies.json'

ERROR: testGetRetweetsOfMe (main.ApiTest)

Test the twitter.API GetRetweetsOfMe method

Traceback (most recent call last):
File "twitter_test.py", line 440, in testGetRetweetsOfMe
retweets = self._api.GetRetweetsOfMe()
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3025, in GetRetweetsOfMe
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/retweets_of_me.json'

ERROR: testGetStatus (main.ApiTest)

Test the twitter.Api GetStatus method

Traceback (most recent call last):
File "twitter_test.py", line 399, in testGetStatus
status = self._api.GetStatus(89512102)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2752, in GetStatus
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/show-89512102.json'

ERROR: testGetUser (main.ApiTest)

Test the twitter.Api GetUser method

Traceback (most recent call last):
File "twitter_test.py", line 512, in testGetUser
user = self._api.GetUser('dewitt')
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3225, in GetUser
json = self._FetchUrl(url)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/show-dewitt.json'

ERROR: testGetUserTimeline (main.ApiTest)

Test the twitter.Api GetUserTimeline method

Traceback (most recent call last):
File "twitter_test.py", line 381, in testGetUserTimeline
statuses = self._api.GetUserTimeline('kesuke', count=1)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2720, in GetUserTimeline
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/user_timeline-kesuke.json'

ERROR: testPostDirectMessage (main.ApiTest)

Test the twitter.Api PostDirectMessage method

Traceback (most recent call last):
File "twitter_test.py", line 480, in testPostDirectMessage
status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8'))
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3317, in PostDirectMessage
json = self._FetchUrl(url, post_data=data)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/direct_messages-new.json'

ERROR: testPostUpdate (main.ApiTest)

Test the twitter.Api PostUpdate method

Traceback (most recent call last):
File "twitter_test.py", line 414, in testPostUpdate
status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'))
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2837, in PostUpdate
json = self._FetchUrl(url, post_data=data)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/update.json'

ERROR: testPostUpdateLatLon (main.ApiTest)

Test the twitter.Api PostUpdate method, when used in conjunction with latitude and longitude

Traceback (most recent call last):
File "twitter_test.py", line 423, in testPostUpdateLatLon
status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'), latitude=54.2, longitude=-2)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2837, in PostUpdate
json = self._FetchUrl(url, post_data=data)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/update_latlong.json'

ERROR: testTwitterError (main.ApiTest)

Test that twitter responses containing an error message are wrapped.

Traceback (most recent call last):
File "twitter_test.py", line 370, in testTwitterError
statuses = self._api.GetUserTimeline()
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 2720, in GetUserTimeline
json = self._FetchUrl(url, parameters=parameters)
File "/home/steven/Downloads/python-twitter-0.8.5/twitter.py", line 3992, in _FetchUrl
response = opener.open(url, encoded_post_data)
File "twitter_test.py", line 581, in open
return self.handlersurl
File "twitter_test.py", line 614, in call
return self.fun(
(self.pending + args), *_kw)
File "twitter_test.py", line 525, in _OpenTestData
f = open(self._GetTestDataPath(filename))
IOError: [Errno 2] No such file or directory: '/home/steven/Downloads/python-twitter-0.8.5/testdata/public_timeline_error.json'


Ran 42 tests in 0.055s

FAILED (errors=18)
steven@math:~/Downloads/python-twitter-0.8.5$

python-twitter isn't compatible with google app engine

python-twitter uses local files (tempfile.gettempdir) for caching purposes.
due to the file access restriction in google app engine this library isn't compatible and can't be run in gae.

please find the restriction here: https://developers.google.com/appengine/docs/python/runtime#Pure_Python

I'd like to open a new branch which is gae-friendly. the idea is to re-implement the cache mechanism based on tempfile.TemporaryFile and prefixes. other issues with gaw might happen as well and to be treated in that branch.

before I do so, I'd like to have your opinion first please.

thanks in advance
Akiva

Error on Google AppEngine

With the latest pull of python-twitter and the latest appengine sdk, I get the exception below:

Traceback (most recent call last):
File "C:\google_appengine\google\appengine\runtime\wsgi.py", line 196, in Hand
le
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\google_appengine\google\appengine\runtime\wsgi.py", line 255, in _Loa
dHandler
handler = import(path[0])
File "C:\Users\tim\workbench\projects\tweet-to-effbee\tweettoeffbee.py", line
17, in
access_token_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
File "C:\Users\tim\workbench\projects\tweet-to-effbee\library\twitter.py", lin
e 2354, in init
self.SetCache(cache)
File "C:\Users\tim\workbench\projects\tweet-to-effbee\library\twitter.py", lin
e 4182, in SetCache
self._cache = _FileCache()
File "C:\Users\tim\workbench\projects\tweet-to-effbee\library\twitter.py", lin
e 4555, in init
self._InitializeRootDirectory(root_directory)
File "C:\Users\tim\workbench\projects\tweet-to-effbee\library\twitter.py", lin
e 4615, in _InitializeRootDirectory
root_directory = self._GetTmpCachePath()
File "C:\Users\tim\workbench\projects\tweet-to-effbee\library\twitter.py", lin
e 4611, in _GetTmpCachePath
return os.path.join(tempfile.gettempdir(), cache_directory)
File "C:\google_appengine\google\appengine\dist\tempfile.py", line 61, in Plac
eHolder
raise NotImplementedError("Only tempfile.TemporaryFile is available for use"
)
NotImplementedError: Only tempfile.TemporaryFile is available for use
INFO 2013-06-11 12:25:54,819 server.py:585] default: "GET / HTTP/1.1" 500 -

It works fine with command-line scripts.

Twitter search

I'm sure this isn't the right forum for this, but I haven't seen any others...

I'm trying to get my feet wet using the API, so I tried to do a basic search and I used the following code:

 tSearch = twitter.Twitter(domain='search.twitter.com')
 tSearch.search(q='Obama', rpp=1)

I've received the following error response:

 Traceback (most recent call last):
 File "interactive", line 1, in <module>
 File "/usr/local/lib/python2.7/dist-packages/twitter-1.9.4-py2.7.egg/twitter/api.py", line 204, in __call__
   return self._handle_response(req, uri, arg_data, _timeout)
 File "/usr/local/lib/python2.7/dist-packages/twitter-1.9.4-py2.7.egg/twitter/api.py", line 235, in _handle_response
 raise TwitterHTTPError(e, uri, self.format, arg_data)
 twitter.api.TwitterHTTPError: Twitter sent status 404 for URL: 1.1/search.json using parameters: (q=Obama&rpp=1)
 details: {"errors":[{"message":"Sorry, that page does not exist","code":34}]}

Not sure what to do since my browser was able to turn an answer. Thank you for your time and consideration.

GetPublicTimeline() ?

Possibly a noobish question here, but is the api.GetPublicTimeline() method that's discussed in the documentation actually included in python-twitter?

distribute bug

I have a mac 10.6 so the version of distribute was causing my pip and easy_install and other things not to work.
i fixed with this cmd:
curl http://python-distribute.org/distribute_setup.py | python

then i took the distribute out of requirements.txt

the first time i installed without virtualenv, but after my mac and i both freaked out, i will swear by virtualenv forever now :)

hope this helps others.

GetFriends() rate limiting in 1.1

With the change in how rate limiting works, is there any way to pull a user's entire friendlist if it's a very large list?

e.g.
friendz = api.GetFriends(screen_name='podcast411')

will throw "[{u'message': u'Rate limit exceeded', u'code': 88}]"
without resolving (i.e., friendz will remain undefined)

Can we page through the list from GetFriends(), add (e.g. the .names) to a dictionary or list, and tell Python to sleep for 15 minutes when we hit the rate limit?

Some of this obviously needs to be handled in the app's/user's code, but it feels like something is missing from the Python Twitter def (or that I'm missing something).

API v1.1 and Direct Messages

So I updated everything for the python api as well as this github repository and I still get errors related to migrating to the new api. Here is the code for my simple direct message project using python-twitter: http://bpaste.net/show/108720/

Will I have to change the resource URL from the twitter developers website? Is direct messaging just disabled after the new change with the api?

1000 lines of very verbose code can be easily cleaned up

Most of the objects use getters and setters in a completely unnecessary way, adding literally 1000 lines of noise to the code.

(For an explanation of why they are unnecessary, see http://dirtsimple.org/2004/12/python-is-not-java.html )

Many other methods on the simple data objects have lots of duplication and could be simplified and shortened a lot by using some of Python's dynamic features, like introspection etc. (Especially AsDict, __eq__ etc.)

Would you merge these kind of changes if I submitted a pull request? Or after the move to API v1.1?

twitter_test doesn't pass all tests

Test the twitter.Api GetUser method ... ok
Test the twitter.Api GetUserTimeline method ... ok
Test the twitter.Api PostDirectMessage method ... ok
Test the twitter.Api PostUpdate method ... ok
Test that twitter responses containing an error message are wrapped. ... ok

======================================================================
ERROR: Test the twitter.Api GetFollowers method
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/git/python-twitter/twitter_test.py", line 446, in testGetFollowers
    users = self._api.GetFollowers(page=1)
TypeError: GetFollowers() got an unexpected keyword argument 'page'

Status from GetSearch does not return Coordinates.

I am trying to access a status coordinates without using up a lot of hits. Using the GetSearch and accessing the status information uses only a single hit, but I cannot access the geo coordinates. Pulling screen name and then accessing the status through the user returns geo coordinates.


import twitter, smtplib, string, os

api = twitter.Api()
keyword = "re: lic plate"

pagelist = [1]

for pg in pagelist:
twisearch = api.GetSearch(keyword, per_page=15, page=pg, lang="en")

for twi in twisearch:
user = twi.user.screen_name
userinfo = api.GetUser(user)
geo = userinfo.status.GetCoordinates()

UserStatusGeo returns values.

print geo

StatusGeo doesn ot return values

print twi.GetCoordinates()

{u'type': u'Point', u'coordinates': [0.15485670000000001, 52.238582899999997]}
None

GetRetweets returns Invalid or expired token, code: 89

When running:

api = twitter.Api(consumer_key=consumer_key,
                consumer_secret=consumer_secret,
                access_token_key=serverKey,
                access_token_secret=access_token_secret)

print api.getRetweets(264010795183120384)

I get the error:

  File "/home/guy/workspace/twitter.py", line 2977, in GetRetweets
    data = self._ParseAndCheckTwitter(json)
  File "/home/guy/workspace/twitter.py", line 3759, in _ParseAndCheckTwitter
    self._CheckForTwitterError(data)
  File "/home/guy/workspace/twitter.py", line 3784, in _CheckForTwitterError
    raise TwitterError(data['errors'])
twitter.TwitterError: [{u'message': u'Invalid or expired token', u'code': 89}]

According to twitter it means that request is outdated:
https://dev.twitter.com/docs/error-codes-responses

Get this using the git version from when this comment was posted.

Support for fetching a List's timeline

A request to add support for fetching a List's timeline. Something like this

api = twitter.Api()
list_timeline = api.GetListTimeline(user='palafo', list='breakingnews')

Where 'palafo' is the user and 'breakingnews' is the list.

Is something like this possible already?

Streaming API

Hi,

Will your library support Twitter Streaming API?

Cleanup twitter.Api functions

Currently the twitter.Api functions are inconsistent. Sometimes we check if the API is authenticated, sometimes we don't. Sometimes we check if the parameter is an integer/long, sometimes we don't. There are a lot of these and I think we would have to go trough every function (again) to fix them after the updates to API 1.1 are finished.

Make replies

Hi, i'm starting with this library. And I want to make a replies from a user. How can I do that? I only found the class PostUpdate

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.