EzDevInfo.com

twython

Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs. Newest 'twython' Questions - Stack Overflow

Twython search API with next_results

I'm a bit confused about the search API. Let's suppose I query for "foobar", the following code:

from twython import Twython
api = Twython(...)
r = api.search(q="foobar")

In this way I have 15 statuses and a "next_results" in r["metadata"]. Is there any way to bounce back those metadata to the Twython API and have the following status updates as well, or shall I get the next until_id by hand from the "next_results" and perform a brand new query?


Source: (StackOverflow)

Fetching tweets with hashtag from Twitter using Python

How do we find or fetch tweets on the basis of hash tag. i.e. I want to find tweets regarding on a certain subject? Is it possible in Python using Twython?

Thanks


Source: (StackOverflow)

Advertisements

How to get twitter followers using Twython?

I want to get a list of twitter followers/following of a particular user, when their screenname or user.id is specified. Can anyone please give the code snippet for it? Thanks.


Source: (StackOverflow)

Using Twython to send a tweet, twitter api error

I'm trying to make python send a tweet for me using Twython but for some reason everything I'm trying isn't working.

I've followed the Twython README but still unable to acheive what I want.

Below is my latest attempted code:

from twython import Twython, TwythonError

APP_KEY = "KEYHERE"
APP_SECRET = "SECRETHERE"

twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()

OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
    twitter.update_status(status='See how easy this was?')
except TwythonError as e:
    print e

On running the above code I get the following traceback error:

Twitter API returned a 401 (Unauthorized), Invalid or expired token

Does anyone know what I'm doing wrong and more importantly how do I fix this?

I dont have enough points for a bounty, but I would really appreciate the help!

Thanks in advance

edit

Traceback (most recent call last):
  File "C:\testtweet.py", line 20, in <module>
    final_step = twitter.get_authorized_tokens(oauth_verifier)
  File "C:\Python27\lib\site-packages\twython\api.py", line 313, in get_authorized_tokens
    raise TwythonError('Unable to decode authorized tokens.')
TwythonError: Unable to decode authorized tokens.

The above is the traceback recieved from the code supplied by @justhalf

Thanks SMNALLY


Source: (StackOverflow)

python-oauth2 with Twitter's oauth_callback

I'm using Twython as my Twitter API wrapper, and oauth2 to handle authentication. I'm trying to have a use login via twitter, and then redirecting him after the oauth dance to a dynamically generated oauth_callback. This, however, appears to be impossible to do with these libraries straight out of the box. My problem is that my oauth client (python-oauth2), doesnt support callback urls. I find this very strange because this is the default oauth client used by Twython -- why would they bother writing code to accomodate the use of a dynamic callback and then bundle the library with an oauth client that doesn't support callbacks? Line 54 is set to false, therefore my callback url is never included in the request token url, as required in the oAuth 1.0a specs.

I've tried modifying both Twython and oauth2, but I keep running into problems. I'd like to know if there is an alternative to python-oauth2 that supports oauth_callback, or maybe an alternative twitter library that would handle the oauth properly.


Source: (StackOverflow)

Twitter auth fails on Twython 2.3.4 with Error: 401, Failed to validate oauth signature and token

I just updated to Twython 2.3.4, but now my Twitter auth stops working. It fails on the ' auth_props = twitter.get_authentication_tokens()' line. Any idea what went wrong? Thanks in advance!

The python code to do Twitter auth using Twython is below:

def begin_auth(request):
    twitter = Twython(
        twitter_token = TWITTER_KEY,
        twitter_secret = TWITTER_SECRET,
        callback_url = request.build_absolute_uri(reverse('portnoy.views.thanks'))
    )
    # Request an authorization url to send the user to...
    auth_props = twitter.get_authentication_tokens()

I have the following error on the line above: TwythonAuthError: "Seems something couldn't be verified with your OAuth junk. Error: 401, Message: Failed to validate oauth signature and token"

    # Then send them over there, durh.
    request.session['request_token'] = auth_props
    return HttpResponseRedirect(auth_props['auth_url'])

def thanks(request, redirect_url='/'):
    c = RequestContext(request)
    # for permanent ones and store them...
    twitter = Twython(
        twitter_token = TWITTER_KEY,
        twitter_secret = TWITTER_SECRET,
        oauth_token = request.session['request_token']['oauth_token'],
        oauth_token_secret = request.session['request_token']['oauth_token_secret']
     )

    # Retrieve the tokens we want...
    authorized_tokens = twitter.get_authorized_tokens()
    request.session['request_tokens'] = authorized_tokens
    debug('thanks', request.session['request_tokens'])

    user = User.objects.filter(username=authorized_tokens['screen_name'])
    if user.exists():
        user = user[0]
        user.backend='django.contrib.auth.backends.ModelBackend'     
        auth.login(request,user)
    else:
        return render_to_response('twitter_register.html', c)   
    return HttpResponseRedirect(redirect_url)

Source: (StackOverflow)

Using Twython to pull all (of Miley Cyrus') tweets?

I'm new to Python and Twython, but I'm working on a project where I want to use Twython to analyze all of Miley Cyrus' tweets. Currently there are 7,193, but Twython will only let me take 200 at a time...how can I scrape all of them? Is there there a way to scrape all of them using Twython or do I have to manually scrape the Twitter website? Ideally I would preserve access to all of the tweets' metadata so I could use it in my analysis (rather than just the text of all of the tweets). Suggestions for code?


Source: (StackOverflow)

Eclipse + PyDev: Eclipse telling me that this is an invalid import?

I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import.

How do I "tell" eclipse where twython is so that it will let me import and use it?


Source: (StackOverflow)

Twython updateStatus - Unauthorized: Invalid / expired Token

I'm trying to post a tweet using Twython from Django-powered site. However, the 'twitter.updateStatus(status=tweet_text)' line results in the following error:

TwythonError: u'Unauthorized: Authentication credentials were missing or incorrect. -- Invalid / expired Token'

I do have requests version 0.13.9, so this shouldn't be an issue:

>>>import pkg_resources
>>>pkg_resources.get_distribution("requests").version
'0.13.9'
>>>pkg_resources.get_distribution("twython").version
'2.3.4'

Any idea how to fix this? Thanks in advance!

Here's the python method itself:

def tweet_link(request, tweet_text):
    try:
        c = RequestContext(request)
        twitter = Twython(
            twitter_token = TWITTER_KEY,
            twitter_secret = TWITTER_SECRET,
            oauth_token = request.session['request_token']['oauth_token'],
            oauth_token_secret = request.session['request_token']['oauth_token_secret']
        )
        twitter.updateStatus(status=tweet_text)
    except Exception, e:
        print traceback.print_exc()
    return HttpResponse('')

Source: (StackOverflow)

Twython OAuth1 issues, 401 error using example code

I'm trying to setup a stream using the latest version of Twython with Python 2.7.3. I'm trying to reproduce the example in the streaming docs which depend on the OAuth1 docs. Using the following code yields 401 errors until I kill execution:

from twython import Twython
from twython import TwythonStreamer

class MyStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            print['text'].encode('utf-8')

    def on_error(self, status_code, data):
        print status_code


APP_KEY    = 'mupAeFE44nOU5IlCo4AO0g' # Consumer key in twitter app OAuth settings
APP_SECRET = 'NOTMYSECRET0zo1WbMAeSIzZgh1Hsj9CrlShonA'  # Consumer secret in OAuth settings

twitter = Twython(APP_KEY,APP_SECRET)
auth = twitter.get_authentication_tokens()

OAUTH_TOKEN        = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

stream = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track = 'twitter')

The values of 'OAUTH_TOKEN' and 'OAUTH_TOKEN_SECRET' end up set to unicode strings. I've set 'APP_KEY' and 'APP_SECRET' as above or as unicode strings both with the same results.

Following the advice in this reported issue I updated both requests and requests-oauthlib without luck.

I don't believe I'm having firewall issues. At this point, I've tried this code on three different boxes all in different locales all with the same results.

Not sure how to proceed at this point. All help appreciated.


Source: (StackOverflow)

Twitter API/Twython - show user to get user profile image

How to get user profile image using Twython?

I see show_user() method, but instantiating Twython with api key and secret + oauth token and secret, and calling this method returns 404: TwythonError: Twitter API returned a 404 (Not Found), Sorry, that page does not exist.

Calling same method from Twython instantiated w.o api/oauth keys returns 400: TwythonAuthError: Twitter API returned a 400 (Bad Request), Bad Authentication data.

I also tried to GET user info from https://api.twitter.com/1.1/users/show.json?screen_name=USERSCREENNAME, and got 400 as well.

I would appreciate a working example of authenticated request to twitter api 1.1 . Can't find it on twitter api reference.


Source: (StackOverflow)

Getting mentions and DMs through twitter stream API 1.1? (Using twython)

I'm using twython (twitter API library for python) to connect to the streaming API, but I seem to only get the public twitter stream possibly filtered by words. Isn't there a way to get a real-time stream of the authenticated user timeline or @mentions?

I've been looping through delayed calls to the REST API to get those mentions but twitter doesn't like me to make so many requests.

Twython documentation isn't helping me much about it, neither is the official twitter doc.

If there's another python library that can work better than twython for streaming (for Twitter API v1.1). I'd appreciate the suggestion... Thanks.


Source: (StackOverflow)

JSON or SimpleJSON and Python with Twython

I'm a newbie to Python and JSON as well. I installed twython to "speak" to the Twitter API. I use Python 2.7 on a mac.

I would like to get my mentions through the API. The program should identify the Twitter user who mentioned me.

I try:

t = Twython(...)
men = t.get_mentions_timeline()

The user is mentioned once, print men shows a lot of stuff like this:

[{u'contributors': None, u'truncated': False, u'text': .... u'Sun May 26 09:18:55 +0000 2013', u'in_reply_to_status_id_str': None, u'place': None}]

Somewhere in this stuff I see all the things I would like to extract from the response.

How can I extract the screen_name?

I'm quite confused with json.dumps or json.loads - shall I work with json or simplejson?


Source: (StackOverflow)

Possible to tweet using appkey/secret key from a different account via twython?

I have a twitter account with an App made, currently it's setup so students can tweet from our website and as such their tweets show "via SchoolAppNameHere" at the bottom of their tweets.

Is it possible to use Twython to use the Appkey and secret key and then get auth tokens from a completely different so when I was to run the bit of code below it would tweet from an account what didn't create the app...

from twython import Twython

APP_KEY = ''
APP_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test")

Any ideas would be much appreciated :)

Edit, Updated example/explanation below:

Let's say the following image's are from the account "stackoverflowapp" and the app called "Stackoverflow Test App":

http://i.imgur.com/8sIpak5.png http://i.imgur.com/e6CYt6e.png

Using the following bit of code would tweet from the account "stackoverflowapp" with the tweet "test" via the applicationg called "Stackoverflow Test App"

from twython import Twython

APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
OAUTH_TOKEN = 'Acc3ss_tok3N_123456789'
OAUTH_TOKEN_SECRET = 'aCCeSS_tOkEn_sEcrET_123456789'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test")

Let's say that the following image is from the account "useraccount1" and the app is called "testing123":

http://i.imgur.com/vYJLmfr.png

So now that I have the access tokens to login to the account "useraccount1", how can I tweet via the app called "Stackoverflow test app" which was created by the user: "stackoverflowapp" example of what I tried is below:

from twython import Twython

APP_KEY = 'coN_kEY_123456789'
APP_SECRET = 'cOn_sEcr3t_123456789'
OAUTH_TOKEN = 'Acc3ss_123456789'
OAUTH_TOKEN_SECRET = 'aCCeSS_sEcrET_123456789'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status="test update")

Unfortunately, I get the error:

TwythonAuthError: Twitter API returned a 401 (Unauthorized), Could not authenticate you

Source: (StackOverflow)

How to pass oauth_callback value to oauth/request_token with Twython

Twitter just recently made the following mandatory:

1) You must pass an oauth_callback value to oauth/request_token. It's not optional. Even if you have one already set on dev.twitter.com. If you're doing out of band OAuth, pass oauth_callback=oob.

2) You must pass along the oauth_verifier you either received from your executed callback or that you received hand-typed by your end user to oauth/access_token. Here is the twitter thread (https://dev.twitter.com/discussions/16443)

This has caused Twython get_authorized_tokens to throw this error:

Request: oauth/access_token

Error: Required oauth_verifier parameter not provided

I have two questions:

1. How do you pass the oauth_callback value to oauth/request_token with Twython?

2. How do you pass along the oauth_verifier?

I can get the oauth_verifier with request.GET['oauth_verifier'] from the callback url but I have no idea what to do from there using Twython. I've search everywhere but haven't found any answers so I decided to post this. This is my first post so please be kind ;)

Here is my code:

def register_twitter(request):
    # Instantiate Twython with the first leg of our trip.
    twitter = Twython(
        twitter_token = settings.TWITTER_KEY,
        twitter_secret = settings.TWITTER_SECRET,
        callback_url = request.build_absolute_uri(reverse('account.views.twitter_thanks'))
    )

    # Request an authorization url to send the user to
    auth_props = twitter.get_authentication_tokens()

    # Then send them over there
    request.session['request_token'] = auth_props
    return HttpResponseRedirect(auth_props['auth_url'])


def twitter_thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL):

    # Now that we've got the magic tokens back from Twitter, we need to exchange
    # for permanent ones and store them...
    twitter = Twython(
        twitter_token = settings.TWITTER_KEY,
        twitter_secret = settings.TWITTER_SECRET,
        oauth_token = request.session['request_token']['oauth_token'],
        oauth_token_secret = request.session['request_token']['oauth_token_secret'],
    )

    # Retrieve the tokens
    authorized_tokens = twitter.get_authorized_tokens()

    # Check if twitter user has a UserProfile
    try:
        profile = UserProfile.objects.get(twitter_username=authorized_tokens['screen_name'])
    except ObjectDoesNotExist:
        profile = None

Source: (StackOverflow)