Example #1
0
  global rate_reset
  global remaining_hits
  pp.pprint(results)
  if remaining_hits <= 0:
    print "hit my limit!"
    return
  if time.gmtime() > rate_reset:
    rates = api.getRateLimitStatus()
    remaining_hits = rates['remaining_hits']
    rate_reset = rates['reset_time_in_seconds']
    print 'Rate limit: ' + str(remaining_hits)
  try:
    if results.has_key('event'):
      if results['event'] == 'follow':
        followed(results)
    elif results.has_key('entities'):
      if results['user']['id_str'] == current_user['id_str']:
        return
      if results['entities'].has_key('user_mentions'):
        for user_mention in results['entities']['user_mentions']:
          if user_mention['id_str'] == current_user['id_str']:
            mentioned(results)
            break
  except TwythonError:
    api.updateStatus(status='@seepel I encountered an error!')

try:
  api.stream({ 'endpoint' : 'https://userstream.twitter.com/1.1/user.json' }, on_results)
except TwythonError:
  api.updateStatus(status='@seepel I have crashed!')
Example #2
0
def search_with_tokens(tokens, queryType, params):
    #print "params = ", params
    #user = UserSocialAuth.objects.filter(user=request.user).get()
    # Set up a new Twython object with the OAuth keys

    #pprint(tokens)
    print "app_key = ", settings.TWITTER_CONSUMER_KEY
    print "app_secret = ", settings.TWITTER_CONSUMER_SECRET
    print "oauth_token = ", tokens['oauth_token']
    print "oauth_token_secret = ", tokens['oauth_token_secret']
    t = Twython(app_key=settings.TWITTER_CONSUMER_KEY,
        app_secret=settings.TWITTER_CONSUMER_SECRET,
        oauth_token=tokens['oauth_token'],
        oauth_token_secret=tokens['oauth_token_secret'])

    # Obtain Twitter results using user's OAuth key
    if queryType == "search":
        params = params.copy()
        pageID = params["pageID"]
        del params["pageID"]
        queryResults = t.search(**(params))

        # Use helper to update the tweet list of the page
        # Return an array of tweets to return to the client
        helper = Helper()
        # tweets = helper.updateWikiArticleTweet(pageID, queryResults) # Update the correct pageID
        helper.updateWikiArticleTweet(pageID, queryResults) # Update the correct pageID
        '''
        tweetsSerialization = []
        for tweet in tweets:
            tweetsSerialization.append({
                "id" : tweet.id,
                "text" : tweet.text,
                "source" : tweet.source,
                "profileImageUrl" : tweet.profileImageUrl,
                "createdAt" : tweet.createdAt
            })
        '''

        # Get the correct logger based on convention:
        # {APP}.{FILE}.{FUNCTION} = __name__.'.'.inspect.stack()[0][3]
        # Need to evaulate performance of 'inspect' library as print function name
        # is not supported by Python
        #print __name__+"."+inspect.stack()[0][3]
        logger = logging.getLogger(__name__+"."+inspect.stack()[0][3])
        # Fake infomation, to be updated later
        logger.info(json.dumps({
            "pageID": pageID, # Pass the correct pageID here
            "queryType": queryType,
            "query": queryResults["search_metadata"]["query"],
            "tweetsCount": queryResults["search_metadata"]["count"],
            "source": 'TwitterAPI',
        }))
        return HttpResponse(json.dumps(queryResults), content_type="application/json")

##    elif queryType == "articleSearch":
##        params1 = dict(params)
##        # TODO, swap this out later
##        params1["q"] = unicode(params["articleId"])
##        del params1["articleId"]
##        queryResults = t.search(**(params1))
    elif queryType == "followersID":
        queryResults = t.getFollowersIDs(**(params))
    elif queryType == "followersList":
        params = params.copy()
        screen_name = params["screen_name"]
        cursor = params["cursor"]
        queryResults = t.getFollowersList(**(params))
        # Save results
        helper = Helper()
        helper.getUserFollower(screen_name, queryResults)
    elif queryType == "friendsID":
        queryResults = t.getFriendsIDs(**(params))
    elif queryType == "friendshipLookup":
        queryResults = t.lookupFriendships(**(params))
    elif queryType == "stream":
        queryResults = t.stream(params, on_results)

    return HttpResponse(json.dumps(queryResults), content_type="application/json")
from twython import Twython


def on_results(results):
    """A callback to handle passed results. Wheeee.
        """

    print results


Twython.stream({"username": "******", "password": "******", "track": "python"}, on_results)