def get(self): tweets = Tweet.query.order_by(Tweet.tweetId.asc()).limit(1).all() oldest = tweets[0] if len(tweets) > 0 else None twitter = Twython(s.CONSUMER_KEY, s.CONSUMER_SECRET, s.ACCESS_TOKEN, s.ACCESS_TOKEN_SECRET) data = [] try: if oldest: logging.info('\n\nOldest tweetId = {0}\n\n'.format(oldest.tweetId)) data = twitter.get_home_timeline(count=50, max_id=oldest.tweetId) else: data = twitter.get_home_timeline(count=200) except TwythonError as e: logging.error('{0}'.format(e)) else: logging.info(str(data)) for tweet in data: if len(tweet.get('entities').get('urls')) > 0: logging.info("\n\nFound urls!\n\n") process_link(tweet, s.USER_ID) else: logging.info("\n\nNo urls :(\n\n") return "OK"
class Termeet(object): def __init__(self): tokens = user_info[0]['keys'] try: self.api = Twython( consts.keys['API_KEY'], consts.keys['API_SECRET'], tokens['access_token'], tokens['access_token_secret'], ) except: log("Error") self.tl = [] def txtupdate(self, text): try: self.api.update_status(status=text) except twython.exceptions.TwythonError as e: print("Couldn't update status due to") print(e.msg) def gettimeline(self, n=20): if self.tl: newupdates = self.api.get_home_timeline(since_id=self.tl[0]['id']) else : newupdates = self.api.get_home_timeline(count=n) self.tl = newupdates + self.tl for (i,tw) in enumerate(self.tl[:n]): print(str(i).rjust(3)+pprinter.pptweet(tw)) def fav(self,tlnumber): try: twid = self.tl[tlnumber]['id'] except IndexError: print("no index") return self.api.create_favorite(id=twid) def mainloop(self): while True: body = None try: cmd = input(' > ') except EOFError as e: print() break if ' ' in cmd: body = cmd[cmd.find(' ')+1:] cmd = cmd[:cmd.find(' ')] print("#####{}#####".format(cmd)) if cmd == 'tw': self.txtupdate(body) elif cmd == 'ls': self.gettimeline(body) elif cmd == 'f': ids = body.split(' ') for i in ids: self.fav(int(i)) elif cmd == ':q': break
def get_timeline(self, testdata = False): if testdata: with open('timeline.tweets', 'r') as f: try: timeline = json.load(f) except: timeline = {} print("empty data file exception") f.close() return timeline accounts = self.get_accounts() tweets = {} i = 0 for account in accounts: if 'oauth_token' in accounts[account] and 'oauth_token_secret' in accounts[account]: api = Twython(config.APP_KEY, config.APP_SECRET, accounts[account]['oauth_token'], accounts[account]['oauth_token_secret']) tweetcount = 10; if self.since: timeline = api.get_home_timeline(count=tweetcount, since_id=self.since) else: timeline = api.get_home_timeline(count=tweetcount) for tweet in timeline: tweets.update({i:tweet}) i += 1 self.since = tweet['id'] return timeline
class Questions(object): def __init__(self, appKey, appKeySecret, accessToken, accessTokenSecret): self.questions = {} self.handle = Twython(app_key=appKey, app_secret=appKeySecret, oauth_token=accessToken, oauth_token_secret=accessTokenSecret) self.handle.get_home_timeline() print "Remaining API calls: ", self.handle.get_lastfunction_header('x-rate-limit-remaining') def getTweet(self, tweetId): status = self.handle.show_status(id=tweetId) tweetText = self.unescape(status['text']) tweetText = re.sub(r'([ \t]*[#]+[\w]+[ \t]*|[ \t]*[#]+[ \t]*|[ \t]+$|[ \t]*[@]\w+[ \t]*)', '', tweetText) return tweetText def exprValidator(self, tweetId): text = self.getTweet(tweetId) print "validation: " + text if text[-1] in ['>', '<']: text = text[:-1] elif text[-2] in ['>','<','=','!']: text = text[:-2] else: return False try: exec("r = " + text) if r == None: return False return True except: return False def refresh(self, channel): search = self.handle.search(q=channel, count=25) tweets = search['statuses'] for tweet in tweets: # Not a retweet if tweet['text'][:2] != 'RT' and self.exprValidator(tweet['id']): #db.addTweetToDB(channel, tweet['id']) # If channel exists if channel in self.questions: # If ID is not on the list if tweet['id'] not in self.questions[channel]: self.questions[channel].append(tweet['id']) # Channel doesn't exist, create it else: self.questions[channel] = [ tweet['id'] ] def unescape(self, text): text = text.replace("<", "<") text = text.replace(">", ">") text = text.replace("&", "&") return text
def user_timeline(request): """An example view with Twython/OAuth hooks/calls to fetch data about the user in question.""" user = request.user.twitterprofile twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, user.oauth_token, user.oauth_secret) user_tweets = twitter.get_home_timeline() return render_to_response('tweets.html', {'tweets': user_tweets})
def twitter_api(cls): config = cls.config() API_KEY = config['twitter'][0]['api_key'] API_SECRET_KEY = config['twitter'][0]['api_secret_key'] ACCESS_TOKEN = config['twitter'][0]['access_token'] ACCESS_TOKEN_SECRET = config['twitter'][0]['access_token_secret'] print(API_KEY, ACCESS_TOKEN_SECRET) twitter = Twython(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) twitter = twitter.get_home_timeline() if twitter != None: Database().delete_from('twitter_timeline', None, None) x = 0 while x < len(twitter): try: created = twitter[x]['created_at'] text = twitter[x]['text'] link = twitter[x]['user']['url'] name = twitter[x]['user']['screen_name'] img = twitter[x]['user']['profile_image_url'] Database().insert_into('twitter_timeline', created, text, link, name, img) x += 1 except Exception as err: print(err)
def get_tweets_per_user(self, user_id): user = User.query.get(user_id) if not user or not user.twitter_authorized: logger.info( 'User number {} did not authorize twitter (or does not exist) not fetching any tweets' .format(user_id)) return tweets = [] try: twitter_auth = TwitterAuth.query.filter_by(user_id=user_id).first() twitter = Twython(current_app.config['TWITTER_API_KEY'], current_app.config['TWITTER_API_SECRET'], twitter_auth.oauth_token, twitter_auth.oauth_token_secret) tweets = twitter.get_home_timeline(count=200, tweet_mode='extended') except: logger.error( 'There was an error fetching twitter timeline from user {}'. format(user_id)) posts_added = 0 commits_failed = 0 commits_succeeded = 0 for tweet in tweets: result = _add_post(user, tweet, 'twitter') posts_added += result['added_new'] commits_succeeded += result['success'] commits_failed += not result['success'] logger.info( 'Done getting tweets for user {}, total {} tweets added to db. {} commits succeeded. ' '{} commits failed.'.format(user_id, posts_added, commits_succeeded, commits_failed))
def tweet_tack(request): if not 'tack' in request.POST or not request.POST['tack']: errors.append('could not locate tack') this_tack=Tack.objects.get(pk=request.POST['tack']) this_user = this_tack.author APP_KEY = "f0wDo5a57mSLYIuaIU4nZA" APP_SECRET = "XKgYeEng2G1qhVNhH3xae4r5LbDzcGD0QzRQp7nc" twitter = Twython(APP_KEY, APP_SECRET ,this_user.oauth_token, this_user.oauth_secret) twitter.verify_credentials() twitter.get_home_timeline() if not this_tack.image: twitter.update_status(status=this_tack.description) else: photo = this_tack.image.file twitter.update_status_with_media(status=this_tack.description, media=photo) return render(request, 'tackd/corkboard_template.html', {})
def home(request): # Si ha iniciado sesion if 'oauth_token' in request.session: try: twitter = Twython(KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"]) except Exception, e: return render_to_response('error.html', context_instance=RequestContext(request)) user = request.session["user"] JSONuser = twitter.show_user(screen_name=user) request.session["profile_photo"] = JSONuser['profile_image_url_https'] profile_photo = request.session["profile_photo"] home_timeline = twitter.get_home_timeline() for item in home_timeline: item['text'] = TransformarTweet.convertirTweet(item['text']) request.session['max_id'] = home_timeline[len(home_timeline) - 1]['id'] request.session['ultimo_id'] = int(home_timeline[0]['id'] - 4) return render_to_response('home.html', { 'tweets': home_timeline, 'profile_photo': profile_photo, 'user': user }, context_instance=RequestContext(request))
def get_tweets_per_user(self, user_id): user = User.query.get(user_id) if not user or not user.twitter_authorized: logger.info('User number {} did not authorize twitter (or does not exist) not fetching any tweets'.format(user_id)) return tweets = [] try: twitter_auth = TwitterAuth.query.filter_by(user_id=user_id).first() twitter = Twython(current_app.config['TWITTER_API_KEY'],current_app.config['TWITTER_API_SECRET'], twitter_auth.oauth_token, twitter_auth.oauth_token_secret) tweets = twitter.get_home_timeline(count=200, tweet_mode='extended') except: logger.error('There was an error fetching twitter timeline from user {}'.format(user_id)) posts_added = 0 commits_failed = 0 commits_succeeded = 0 for tweet in tweets: result = _add_post(user, tweet, 'twitter') posts_added += result['added_new'] commits_succeeded += result['success'] commits_failed += not result['success'] logger.info('Done getting tweets for user {}, total {} tweets added to db. {} commits succeeded. ' '{} commits failed.'.format(user_id, posts_added, commits_succeeded, commits_failed))
def home_time_line(user): twitter = Twython(consumer_key, consumer_secret, user.oauth_token, user.oauth_token_secret) try: result = twitter.get_home_timeline(count=Config.tweet_count, tweet_mode='extended') return result except TwythonError as e: print(e.error_code) return False
def user_timeline(request): user = request.user.profile twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, user.oauth_token, user.oauth_secret) user_tweets = twitter.get_home_timeline() return render_to_response('tweets.html', {'tweets': user_tweets})
def wsTwitter_view(request): APP_KEY = 'IfZu2KyFrUENObWRRb4rEQ' APP_SECRET = 'ZOw3Y9BoMpiZaaoqaL1OH3tH3BNHr2YoBQ4IF2JYu4s' OAUTH_TOKEN = '56143706-DqNvSdocUyKQsSkk6vweW66vtv9ovSfRDECmfzdk' OAUTH_TOKEN_SECRET = 'xZ6sIyxeoKcxcV5OchdjTDXJLXhnzrfu6zf6bUzJg7c' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) tweets = twitter.get_home_timeline() return HttpResponse(tweets,mimetype='application/json')
def _main(self): APP_KEY = self._get_config_option("APP_KEY") APP_SECRET = self._get_config_option("APP_SECRET") OAUTH_TOKEN = self._get_config_option("OAUTH_TOKEN") OAUTH_TOKEN_SECRET = self._get_config_option("OAUTH_TOKEN_SECRET") screen_name = self._get_config_option("screen_name") count = self._get_config_option("count") twitter = Twython( APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET ) try: home_timeline = twitter.get_home_timeline(screenname=screen_name, count=count) except TwythonError as e: logging.error(e) sys.exit(1) for tweet in home_timeline: # strptime doesn't support timezone info, so we are using dateutils. date_object = parser.parse(tweet['created_at']) timestamp = OrgFormat.datetime(date_object) try: # Data is already Unicode, so don't try to re-encode it. output = tweet['text'] except: logging.error(sys.exc_info()[0]) print("Error: ", sys.exc_info()[0]) data_for_hashing = output + timestamp + output properties = OrgProperties(data_for_hashing=data_for_hashing) properties.add("name", tweet['user']['name']) properties.add("twitter_id", tweet['id']) properties.add("contributors", tweet['contributors']) properties.add("truncated", tweet['truncated']) properties.add("in_reply_to_status_id", tweet['in_reply_to_status_id']) properties.add("favorite_count", tweet['favorite_count']) properties.add("source", tweet['source']) properties.add("retweeted", tweet['retweeted']) properties.add("coordinates", tweet['coordinates']) properties.add("entities", tweet['entities']) self._writer.write_org_subitem(timestamp=timestamp, output = output, properties = properties)
def _main(self): APP_KEY = self._get_config_option("APP_KEY") APP_SECRET = self._get_config_option("APP_SECRET") OAUTH_TOKEN = self._get_config_option("OAUTH_TOKEN") OAUTH_TOKEN_SECRET = self._get_config_option("OAUTH_TOKEN_SECRET") screen_name = self._get_config_option("screen_name") count = self._get_config_option("count") twitter = Twython( APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET ) try: home_timeline = twitter.get_home_timeline(screenname=screen_name, count=count) except TwythonError as e: logging.error(e) sys.exit(1) for tweet in home_timeline: # strptime doesn't support timezone info, so we are using dateutils. date_object = parser.parse(tweet['created_at']) timestamp = OrgFormat.datetime(date_object) try: # Data is already Unicode, so don't try to re-encode it. output = tweet['text'] except: logging.error(sys.exc_info()[0]) print "Error: ", sys.exc_info()[0] data_for_hashing = output + timestamp + output properties = OrgProperties(data_for_hashing=data_for_hashing) properties.add("name", tweet['user']['name']) properties.add("twitter_id", tweet['id']) properties.add("contributors", tweet['contributors']) properties.add("truncated", tweet['truncated']) properties.add("in_reply_to_status_id", tweet['in_reply_to_status_id']) properties.add("favorite_count", tweet['favorite_count']) properties.add("source", tweet['source']) properties.add("retweeted", tweet['retweeted']) properties.add("coordinates", tweet['coordinates']) properties.add("entities", tweet['entities']) self._writer.write_org_subitem(timestamp=timestamp, output = output, properties = properties)
class TwitterRest: APP_KEY = '6S5z4JRsLlRCTxFQrEbtBA' APP_SECRET = 'QAFSQK18WaYX9c1PepZj46O0lRGyajfgTb1wJAdvW0' ACCESS_TOKEN = 'AAAAAAAAAAAAAAAAAAAAAIpzQgAAAAAANXi%2B%2FJxCxPyWTdkajpOYWTZXIXo%3Daf4rT7RalBFNFS7OWWYuUVsJSO13Qeu8ivWRTOPBU' OAUTH_TOKEN = '1370188885-an8iXcloxa3VxYy6aVGxi4r8jiVlrLaJPubEpYK' OAUTH_TOKEN_SECRET = 'tDQuev1CvFpHDIDmP1XbWx9WRfzFbUosp6Fn4Enut8' # access function def __init__(self): # self.twitter = Twython(self.APP_KEY, access_token=self.ACCESS_TOKEN) self.twitter = Twython(self.APP_KEY, self.APP_SECRET, self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET) def search(self, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=200) tweets_result = search_result['statuses'] return tweets_result def seachByLang(self, lg, qnt, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=qnt, lang=lg) tweets_result = search_result['statuses'] return tweets_result def seachByLangAndDate(self, language, date, qnt, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=qnt, lang=language, until=date) tweets_result = search_result['statuses'] return tweets_result def seachByLangA(self, language, date, qnt, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=qnt, lang=language, until=date) tweets_result = search_result['statuses'] return tweets_result def searchByGeo(self, local, distance, qnt, query): location, (lat, lon) = geo_location.getGeocode(local) print 'Local: %s - lat:%s - lon: %s' % (location, lat, lon) local_data = '%s,%s,%skm' % (lat, lon, distance) print local_data search_result = self.twitter.search(q=query, count=qnt, geocode=local_data) tweets_result = search_result['statuses'] return tweets_result def getTimeLine(self): return self.twitter.get_home_timeline(count='100')
def getHomeTimeline(count_to_get=800, overwrite=1): conn = sqlite3.connect(DBPath) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON;") if Util.__checkInterval__(UPDATE_INTERVAL, 'UPDATE'): if count_to_get > 800: count_to_get = 800 print('Authorizing application..') try: if not AuthApp.checkTokenExist(oauthMode=1): AuthApp.authApp() twHandler = Twython(AuthApp.getAppKey(), AuthApp.getAppSecret(), AuthApp.getOauthToken(), AuthApp.getOauthTokenSecret()) except TwythonError as e: print(e.args[0]) conn.close() return -1 min_id_get = MAX_STATUS_ID max_id_get = 0 total_count_get = 0 run = 1 sleep(5.1) while count_to_get > 0: print(count_to_get) print(min_id_get) if count_to_get // 200 > 0: this_count = 200 else: this_count = count_to_get % 200 try: resultsList = twHandler.get_home_timeline(max_id=min_id_get - 1, count=this_count) except TwythonError as e: print(e.args[0]) continue for results in resultsList: if run == 1: sleep(random.uniform(-0.4, 1.6) + 5.5) min_id_get, max_id_get, total_count_get, run = Crawler.db_write_tweet(results, twHandler, conn, cur, min_id_get, max_id_get, total_count_get, overwrite, update_user=True) count_to_get -= total_count_get sleep(random.uniform(-0.4, 1.6) + 5.5) conn.commit() Util.__updateLastTime__(conn, 'UPDATE') conn.close() return 0
class PokeyTwit(): def __init__(self): try: print "Initializing twitter bot" self.twitter = Twython(APP_KEY, APP_SECRET, OAUTH, OAUTH_SECRET) print "Verifying credentials" self.twitter.verify_credentials() while True: msg = self.get_message().rstrip() if len(msg) != 0 and len(msg) < 140: break print msg print "length: {}".format(len(msg)) self.twitter.update_status(status=msg) msg = '' self.exit_status = 0 except TwythonError: self.exit_status = 1 def get_timeline(self): try: self.timeline = self.twitter.get_home_timeline() except: raise def get_message(self): with open( resource_path(os.path.realpath(__file__), "resources/twit_lib.txt"), 'rb') as txt: twit_list = txt.readlines() line_stops = [] for idx, val in enumerate(twit_list): if val.rstrip() == '': line_stops.append(idx) row = random.randint(line_stops[0], len(line_stops)) msg = '' while twit_list[row].rstrip() != '': msg += twit_list[row] msg += ' ' row += 1 return msg
class PokeyTwit(): def __init__( self, lib_path=resource_path(resources.__file__,'twit_lib.txt'), conf_path='bots.cfg' ): self.lib_path = lib_path self.c = c = PokeyConfig(conf_path, PokeyConfig.encoded, True) try: print "Initializing twitter bot" self.twitter = Twython(c.APP_KEY, c.APP_SECRET, c.OAUTH, c.OAUTH_SECRET) print "Verifying credentials" self.twitter.verify_credentials() while True: msg = self.get_message().rstrip() if len(msg)!=0 and len(msg) < 140: break print msg print "length: {}".format(len(msg)) self.twitter.update_status(status=msg) msg='' self.exit_status=0 except TwythonError: self.exit_status=1 def get_timeline(self): try: self.timeline = self.twitter.get_home_timeline() except: raise def get_message(self): # If the lib_path is passed, use this path (does no path validation) if self.lib_path is None: # Otherwise, inspect the directory of the calling script and pull from that path self.lib_path = resource_path(inspect.stack()[-1][1],"twit_lib.txt") with open(self.lib_path, 'rb') as txt: twit_list = txt.readlines() msg = twit_list[random.randint(0,len(twit_list)-1)] return msg
def get_feed_twitter(): feed_name = 'Twitter' if debug: print 'TWITTER_APP_TOKEN:' + TWITTER_APP_TOKEN print 'TWITTER_APP_SECRET:' + TWITTER_APP_SECRET print 'TWITTER_ACCESS_TOKEN: ' + TWITTER_ACCESS_TOKEN print 'TWITTER_ACCESS_SECRET: ' + TWITTER_ACCESS_SECRET twitter = Twython(TWITTER_APP_TOKEN, TWITTER_APP_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET) searchResults = twitter.get_home_timeline() if debug: for item in searchResults: print item
def timelineback(request): if request.is_ajax(): twitter = Twython( KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"] ) home_timeline_back = twitter.get_home_timeline( max_id = request.session['max_id'] , count = 10 ) request.session['max_id'] = home_timeline_back[ len( home_timeline_back ) -1 ]['id'] #elimino la primera del home_timeline_back[0] return HttpResponse( json.dumps({'timeline': home_timeline_back}), content_type = 'application/json; charset=utf8') return HttpResponseRedirect('/')
def timeline(): t = Twython('92UbSi1YbvPI5umlJVV6xwL62', 'EMM846L8yfj3hP5T14mdxHKDII1rb9AV7whUUjwVy4X4ZTcx0c', '2257672447-BSkO8JVaFWzrPebefP3bCrY09AAh11Tq1yaX66c', 'BrgI4HvNpqs1tg7u1q0JBYuBH5uePGHW5i1GjRrhZxo8U') tl = t.get_home_timeline() json.dumps(tl) s = genson.Schema() s.add_object(tl) tweets = [] for i in range(0, len(tl)): # pprint(tl[i]['text']) tweets.append(tl[i]['text']) tweets_dict = {'tweets': tweets} return tweets_dict
def get_feed_twitter(): if debug: print 'Feed Name: Twitter' print 'TWITTER_APP_TOKEN:' + TWITTER_APP_TOKEN print 'TWITTER_APP_SECRET:' + TWITTER_APP_SECRET print 'TWITTER_ACCESS_TOKEN: ' + TWITTER_ACCESS_TOKEN print 'TWITTER_ACCESS_SECRET: ' + TWITTER_ACCESS_SECRET twitter = Twython(TWITTER_APP_TOKEN, TWITTER_APP_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET) streamResults = twitter.get_home_timeline() if debug: for item in streamResults: print json.dumps(item, indent=4, separators=[',', ':']) return streamResults
def get_tweets(request): if request.is_ajax(): t = Twython( KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"]) home_timeline = t.get_home_timeline( since_id = request.session['ultimo_id'] ) request.session['ultimo_id'] = int ( home_timeline[0]['id'] -4 ) #Validar si hay nuevos tweets if len(home_timeline) > 1: home_timeline.reverse() del home_timeline[0] else: home_timeline = '' return HttpResponse( json.dumps({'timeline': home_timeline}), content_type = 'application/json; charset=utf8') return HttpResponseRedirect('/')
def timelineback(request): if request.is_ajax(): twitter = Twython(KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"]) home_timeline_back = twitter.get_home_timeline( max_id=request.session['max_id'], count=10) request.session['max_id'] = home_timeline_back[len(home_timeline_back) - 1]['id'] #elimino la primera del home_timeline_back[0] return HttpResponse(json.dumps({'timeline': home_timeline_back}), content_type='application/json; charset=utf8') return HttpResponseRedirect('/')
class TwitterRest: APP_KEY = '6S5z4JRsLlRCTxFQrEbtBA' APP_SECRET = 'QAFSQK18WaYX9c1PepZj46O0lRGyajfgTb1wJAdvW0' ACCESS_TOKEN = 'AAAAAAAAAAAAAAAAAAAAAIpzQgAAAAAANXi%2B%2FJxCxPyWTdkajpOYWTZXIXo%3Daf4rT7RalBFNFS7OWWYuUVsJSO13Qeu8ivWRTOPBU' OAUTH_TOKEN = '1370188885-an8iXcloxa3VxYy6aVGxi4r8jiVlrLaJPubEpYK' OAUTH_TOKEN_SECRET = 'tDQuev1CvFpHDIDmP1XbWx9WRfzFbUosp6Fn4Enut8' # access function def __init__(self): # self.twitter = Twython(self.APP_KEY, access_token=self.ACCESS_TOKEN) self.twitter = Twython(self.APP_KEY, self.APP_SECRET, self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET) def search(self, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=200) tweets_result = search_result['statuses'] return tweets_result def seachByLang(self, lg, qnt, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=qnt, lang=lg) tweets_result = search_result['statuses'] return tweets_result def seachByLangAndDate(self, language, date, qnt, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=qnt, lang=language, until=date) tweets_result = search_result['statuses'] return tweets_result def seachByLangA(self, language, date, qnt, query): search_result = self.twitter.search(q=query.decode('utf-8'), count=qnt, lang=language, until=date) tweets_result = search_result['statuses'] return tweets_result def searchByGeo(self, local, distance, qnt, query): location, (lat, lon) = geo_location.getGeocode(local) print 'Local: %s - lat:%s - lon: %s' %(location, lat, lon) local_data = '%s,%s,%skm' %(lat, lon, distance) print local_data search_result = self.twitter.search(q=query, count=qnt, geocode=local_data) tweets_result = search_result['statuses'] return tweets_result def getTimeLine(self): return self.twitter.get_home_timeline(count='100')
def get_tweets(request): if request.is_ajax(): t = Twython(KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"]) home_timeline = t.get_home_timeline( since_id=request.session['ultimo_id']) request.session['ultimo_id'] = int(home_timeline[0]['id'] - 4) #Validar si hay nuevos tweets if len(home_timeline) > 1: home_timeline.reverse() del home_timeline[0] else: home_timeline = '' return HttpResponse(json.dumps({'timeline': home_timeline}), content_type='application/json; charset=utf8') return HttpResponseRedirect('/')
def home(request): # Si ha iniciado sesion if 'oauth_token' in request.session: try: twitter = Twython( KeySecretApp.app_key, KeySecretApp.app_secret, request.session["oauth_token"], request.session["oauth_token_secret"] ) except Exception, e: return render_to_response('error.html',context_instance=RequestContext(request)) user = request.session["user"] JSONuser = twitter.show_user( screen_name = user ) request.session["profile_photo"] = JSONuser['profile_image_url_https'] profile_photo = request.session["profile_photo"] home_timeline = twitter.get_home_timeline() for item in home_timeline: item['text'] = TransformarTweet.convertirTweet(item['text']) request.session['max_id'] = home_timeline[ len( home_timeline ) -1 ]['id'] request.session['ultimo_id'] = int ( home_timeline[0]['id'] - 4 ) return render_to_response('home.html',{'tweets':home_timeline , 'profile_photo':profile_photo ,'user':user}, context_instance=RequestContext(request))
class TwitPull(): def __init__(self): self.credentials = self.gen_credentials() self.twython_inst = Twython(self.credentials['CONSUMER_KEY'], self.credentials['CONSUMER_KEY_SECRET'], self.credentials['ACCESS_TOKEN'], self.credentials['ACCESS_TOKEN_SECRET']) tweet = self.twython_inst.get_home_timeline(count=10, exclude_replies=True) filtered_tweet = self.filter_tweet(tweet) print(filtered_tweet) time.sleep(5) def gen_credentials(self): with open("twitter_credentials.json", "r") as file: creds = json.load(file) return creds def filter_tweet(self, tweet): important_data = tweet.count() return important_data
def update_tweets(request): twitter_auth = request.user.social_auth.filter(provider='twitter')[0] oauth_token = twitter_auth.tokens['oauth_token'] oauth_secret = twitter_auth.tokens['oauth_token_secret'] twitter = Twython(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, oauth_token, oauth_secret) tweets = twitter.get_home_timeline(count=200) for tweet in tweets: if len(tweet['entities']['urls']) != 0: if not (Tweet.objects.filter(tweet_id=tweet['id'], user=request.user)): tweet_object = Tweet() tweet_object.tweet_id = tweet['id'] tweet_object.text = tweet['text'] tweet_object.source_url = tweet['entities']['urls'][0]['expanded_url'] tweet_object.display_url = tweet['entities']['urls'][0]['display_url'] tweet_object.host_url = urlparse.urlparse(tweet['entities']['urls'][0]['expanded_url']).hostname tweet_object.created_at = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')) tweet_object.tweeted_by = tweet['user']['screen_name'] tweet_object.user = request.user tweet_object.save()
def handler(event, context): """main function that pulls down tweets from the users primary timeline, extracts links, and tweets them to another twitter account""" twitter = Twython(creds['APP_KEY'], creds['APP_SECRET'], creds['OAUTH_TOKEN'], creds['OAUTH_TOKEN_SECRET']) tweets = twitter.get_home_timeline(count = 2000, tweet_mode = 'extended') print("found {} timeline tweets".format(len(tweets))) url = [] for t in tweets: article = extract_article(t) if article: url.append(article) # if the extracted link is another tweet, try finding an article in that tweet for u in url: if "https://twitter.com/" in u: try: tweet_id = [i for i in u.split('/') if i.isdigit()] tweet = twitter.show_status(id = tweet_id[0], tweet_mode = 'extended') article = extract_article(tweet) if article: url.append(article) except TwythonError: pass final_url = [u for u in url if "twitter.com" not in u] final_url = set(final_url) print("posted {} article tweets".format(len(final_url))) twitter_bot = Twython(creds['APP_KEYbot'], creds['APP_SECRETbot'], creds['OAUTH_TOKENbot'], creds['OAUTH_TOKEN_SECRETbot']) for t in final_url: try: twitter_bot.update_status(status = t) except TwythonError: pass
def get_tweets_per_user(self, user_id): # pylint: disable=unused-argument user = User.query.get(user_id) if not user or not user.twitter_authorized: # pylint: disable=line-too-long logger.info( 'User number {} did not authorize twitter (or does not exist) not fetching any tweets' .format(user_id)) return tweets = [] try: twitter_auth = TwitterAuth.query.filter_by(user_id=user_id).first() twitter = Twython(current_app.config['TWITTER_API_KEY'], current_app.config['TWITTER_API_SECRET'], twitter_auth.oauth_token, twitter_auth.oauth_token_secret) tweets = twitter.get_home_timeline(count=200, tweet_mode='extended') except: logger.error( 'There was an error fetching twitter timeline from user {}'.format( user_id)) # filter out protected posts tweets = [tweet for tweet in tweets if not tweet['user']['protected']] _add_posts(user_id, tweets, 'twitter')
class TwythonEndpointsTestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) # Timelines @unittest.skip('skipping non-updated test') def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() @unittest.skip('skipping non-updated test') def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) @unittest.skip('skipping non-updated test') def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() @unittest.skip('skipping non-updated test') def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets @unittest.skip('skipping non-updated test') def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) @unittest.skip('skipping non-updated test') def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') @unittest.skip('skipping non-updated test') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search @unittest.skip('skipping non-updated test') def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages @unittest.skip('skipping non-updated test') def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() @unittest.skip('skipping non-updated test') def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() @unittest.skip('skipping non-updated test') def test_send_get_and_destroy_direct_message(self): """Test sending, getting, then destory a direct message succeeds""" message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d! %s' % int(time.time())) self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) @unittest.skip('skipping non-updated test') def test_send_direct_message_to_non_follower(self): """Test sending a direct message to someone who doesn't follow you fails""" self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man! %s' % int(time.time())) # Friends & Followers @unittest.skip('skipping non-updated test') def test_get_user_ids_of_blocked_retweets(self): """Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds""" self.api.get_user_ids_of_blocked_retweets(stringify_ids=True) @unittest.skip('skipping non-updated test') def test_get_friends_ids(self): """Test returning ids of users the authenticated user and then a random user is following succeeds""" self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_ids(self): """Test returning ids of users the authenticated user and then a random user are followed by succeeds""" self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_lookup_friendships(self): """Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds""" self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') @unittest.skip('skipping non-updated test') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() @unittest.skip('skipping non-updated test') def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() @unittest.skip('skipping non-updated test') def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) @unittest.skip('skipping non-updated test') def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users @unittest.skip('skipping non-updated test') def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() @unittest.skip('skipping non-updated test') def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() @unittest.skip('skipping non-updated test') def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') @unittest.skip('skipping non-updated test') def test_update_delivery_service(self): """Test updating delivery settings fails because we don't have a mobile number on the account""" self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') @unittest.skip('skipping non-updated test') def test_update_profile(self): """Test updating profile succeeds""" self.api.update_profile(include_entities='true') @unittest.skip('skipping non-updated test') def test_update_profile_colors(self): """Test updating profile colors succeeds""" self.api.update_profile_colors(profile_background_color='3D3D3D') @unittest.skip('skipping non-updated test') def test_list_blocks(self): """Test listing users who are blocked by the authenticated user succeeds""" self.api.list_blocks() @unittest.skip('skipping non-updated test') def test_list_block_ids(self): """Test listing user ids who are blocked by the authenticated user succeeds""" self.api.list_block_ids() @unittest.skip('skipping non-updated test') def test_create_block(self): """Test blocking a user succeeds""" self.api.create_block(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_block(self): """Test unblocking a user succeeds""" self.api.destroy_block(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_lookup_user(self): """Test listing a number of user objects succeeds""" self.api.lookup_user(screen_name='twitter,justinbieber') @unittest.skip('skipping non-updated test') def test_show_user(self): """Test showing one user works""" self.api.show_user(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_search_users(self): """Test that searching for users succeeds""" self.api.search_users(q='Twitter API') @unittest.skip('skipping non-updated test') def test_get_contributees(self): """Test returning list of accounts the specified user can contribute to succeeds""" self.api.get_contributees(screen_name='TechCrunch') @unittest.skip('skipping non-updated test') def test_get_contributors(self): """Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account""" self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) @unittest.skip('skipping non-updated test') def test_remove_profile_banner(self): """Test removing profile banner succeeds""" self.api.remove_profile_banner() @unittest.skip('skipping non-updated test') def test_get_profile_banner_sizes(self): """Test getting list of profile banner sizes fails because we have not uploaded a profile banner""" self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users @unittest.skip('skipping non-updated test') def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') @unittest.skip('skipping non-updated test') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() @unittest.skip('skipping non-updated test') def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites @unittest.skip('skipping non-updated test') def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() @unittest.skip('skipping non-updated test') def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists @unittest.skip('skipping non-updated test') def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) @unittest.skip('skipping non-updated test') def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() @unittest.skip('skipping non-updated test') def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') @unittest.skip('skipping non-updated test') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches @unittest.skip('skipping non-updated test') def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() @unittest.skip('skipping non-updated test') def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo @unittest.skip('skipping non-updated test') def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') @unittest.skip('skipping non-updated test') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') @unittest.skip('skipping non-updated test') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') @unittest.skip('skipping non-updated test') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends @unittest.skip('skipping non-updated test') def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) @unittest.skip('skipping non-updated test') def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() @unittest.skip('skipping non-updated test') def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help @unittest.skip('skipping non-updated test') def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() @unittest.skip('skipping non-updated test') def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() @unittest.skip('skipping non-updated test') def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() @unittest.skip('skipping non-updated test') def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() @unittest.skip('skipping non-updated test') def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
#!/usr/bin/env python import sys import json from twython import Twython CONSUMER_KEY = 'u23rwH4IdLqZ1V7rGigrMA' CONSUMER_SECRET = 'KpmFN6cQcZqvzK10rhHjVIJZMM31Vm1aRDl6hFo38Q' ACCESS_KEY = '2393551369-KG8tx9DTI3j8XG10eSdsTjC7srzr5ScHhpryH2o' ACCESS_SECRET = '26lrduosBYj9vTteWL2iIzAUjcSRJxcq0PR91aq2EiNOj' api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) home = api.get_home_timeline() test = 0 for mention in home: user = mention['user']['screen_name'] text = mention['text'] test = text.find("Hi TAYLOR") if test > 0: print "Somebody loves me!" api.update_status(status="@" + user + " Hi " + user + "!")
consumer_secret = '*****************' access_token = '*****************' access_token_secret = '*****************' twitter = Twython(consumer_key, consumer_secret, access_token, access_token_secret) times = 0 my_set = set() while (times < 1): print "sleeping ^-^ " time.sleep(5) print "just woke up (0_0)" msp = twitter.get_home_timeline(count=300, exclude_replies=True, include_rts=False) for kk in msp: # pprint.pprint(kk) # print "\n\n-------\n\n" user_screen_name = kk['user']['screen_name'] if user_screen_name not in my_set: Tweet_text = str(kk['text']) Tweet_text = ' '.join( re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", Tweet_text).split()) analysis = TextBlob(Tweet_text) # senti: Neutral = 0, posit = +1, neg =-1 senti = 0
class TwythonAPITestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) def test_construct_api_url(self): """Test constructing a Twitter API url works as we expect""" url = 'https://api.twitter.com/1.1/search/tweets.json' constructed_url = self.api.construct_api_url(url, q='#twitter') self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter') def test_get(self): """Test Twython generic GET request works""" self.api.get('account/verify_credentials') def test_post(self): """Test Twython generic POST request works, with a full url and with just an endpoint""" update_url = 'https://api.twitter.com/1.1/statuses/update.json' status = self.api.post(update_url, params={'status': 'I love Twython!'}) self.api.post('statuses/destroy/%s' % status['id_str']) def test_get_lastfunction_header(self): """Test getting last specific header of the last API call works""" self.api.get('statuses/home_timeline') self.api.get_lastfunction_header('x-rate-limit-remaining') def test_get_lastfunction_header_not_present(self): """Test getting specific header that does not exist from the last call returns None""" self.api.get('statuses/home_timeline') header = self.api.get_lastfunction_header('does-not-exist') self.assertEqual(header, None) def test_get_lastfunction_header_no_last_api_call(self): """Test attempting to get a header when no API call was made raises a TwythonError""" self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made') def test_search_gen(self): """Test looping through the generator results works, at least once that is""" search = self.api.search_gen('twitter', count=1) counter = 0 while counter < 2: counter += 1 result = next(search) new_id_str = int(result['id_str']) if counter == 1: prev_id_str = new_id_str time.sleep(1) # Give time for another tweet to come into search if counter == 2: self.assertTrue(new_id_str > prev_id_str) def test_encode(self): """Test encoding UTF-8 works""" self.api.encode('Twython is awesome!') def test_html_for_tweet(self): """Test HTML for Tweet returns what we want""" tweet_text = self.api.html_for_tweet(test_tweet_object) self.assertEqual(test_tweet_html, tweet_text) def test_html_for_tweet_expanded_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, use_expanded_url=True) # Make sure full url is in HTML self.assertTrue('http://google.com' in tweet_text) def test_html_for_tweet_short_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, False) # Make sure HTML doesn't contain the display OR exapanded url self.assertTrue(not 'http://google.com' in tweet_text) self.assertTrue(not 'google.com' in tweet_text) def test_raise_error_on_bad_ssl_cert(self): """Test TwythonError is raised by a RequestException when an actual HTTP happens""" self.assertRaises(TwythonError, self.api.get, 'https://example.com') # Timelines def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get deleted :(') self.api.destroy_status(id=status['id_str']) def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() def test_send_get_and_destroy_direct_message(self): """Test sending, getting, then destory a direct message succeeds""" message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d! %s' % int(time.time())) self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) def test_send_direct_message_to_non_follower(self): """Test sending a direct message to someone who doesn't follow you fails""" self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man!') # Friends & Followers def test_get_user_ids_of_blocked_retweets(self): """Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds""" self.api.get_user_ids_of_blocked_retweets(stringify_ids=True) def test_get_friends_ids(self): """Test returning ids of users the authenticated user and then a random user is following succeeds""" self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') def test_get_followers_ids(self): """Test returning ids of users the authenticated user and then a random user are followed by succeeds""" self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') def test_lookup_friendships(self): """Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds""" self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') def test_update_delivery_service(self): """Test updating delivery settings fails because we don't have a mobile number on the account""" self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') def test_update_profile(self): """Test updating profile succeeds""" self.api.update_profile(include_entities='true') def test_update_profile_colors(self): """Test updating profile colors succeeds""" self.api.update_profile_colors(profile_background_color='3D3D3D') def test_list_blocks(self): """Test listing users who are blocked by the authenticated user succeeds""" self.api.list_blocks() def test_list_block_ids(self): """Test listing user ids who are blocked by the authenticated user succeeds""" self.api.list_block_ids() def test_create_block(self): """Test blocking a user succeeds""" self.api.create_block(screen_name='justinbieber') def test_destroy_block(self): """Test unblocking a user succeeds""" self.api.destroy_block(screen_name='justinbieber') def test_lookup_user(self): """Test listing a number of user objects succeeds""" self.api.lookup_user(screen_name='twitter,justinbieber') def test_show_user(self): """Test showing one user works""" self.api.show_user(screen_name='twitter') def test_search_users(self): """Test that searching for users succeeds""" self.api.search_users(q='Twitter API') def test_get_contributees(self): """Test returning list of accounts the specified user can contribute to succeeds""" self.api.get_contributees(screen_name='TechCrunch') def test_get_contributors(self): """Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account""" self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) def test_remove_profile_banner(self): """Test removing profile banner succeeds""" self.api.remove_profile_banner() def test_get_profile_banner_sizes(self): """Test getting list of profile banner sizes fails because we have not uploaded a profile banner""" self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(list_id=test_list_id) def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff') list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed') screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(list_id=test_list_id) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(list_id=test_list_id) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(list_id=test_list_id, screen_name=screen_name) self.api.unsubscribe_from_list(list_id=test_list_id) def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(list_id=test_list_id, screen_name='jack') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(list_id=test_list_id) def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(list_id=test_list_id) def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
class MainWindow(object): def __init__(self, c_key, c_secret, a_key, a_secret): self.win = curses.initscr() curses.noecho() curses.cbreak() locale.setlocale(locale.LC_ALL, "") self.max_y, self.max_x = self.win.getmaxyx() self.win.refresh() self.mwin = self.win.subwin(self.max_y-2, self.max_x, 0, 0) self.mwin.scrollok(True) self.cmdbar = self.win.subwin(1, self.max_x, self.max_y-1, 0) self.statbar = self.win.subwin(1, self.max_x, self.max_y-2, 0) self.statbar.bkgd("-") self.latest_id = 0 self.loaded_statuses = [] self.plugin = [] self.key_bind = {} self.add_plugin(default_plugin(self)) self.change_modename("Waiting") self.api = Twython(c_key, c_secret, a_key, a_secret) self.streamer = cmaletter_streamer(self, c_key, c_secret, a_key, a_secret) self.get_home_timeline(num = 40) def main(self): while 1: key = self.cmdbar.getkey() if key == "q": break if key in self.key_bind: name, func = self.key_bind[key] self.change_modename(name) func(self.mwin) self.change_modename("Waiting") curses.curs_set(0) self.show_timeline() curses.nocbreak() curses.echo() curses.endwin() def add_plugin(self, cls): self.plugin.append(cls) for name, func, bind in cls.cmd_list: self.key_bind[bind] = (name, func) def get_home_timeline(self, num=-1): if num == -1: statuses = self.api.get_home_timeline(since_id = self.latest_id) else: statuses = self.api.get_home_timeline(count = num) for status in statuses[::-1]: self.on_status(status) self.latest_id = status['id'] def get_loaded_status(self): return self.loaded_statuses def user_input(self): self.cmdbar.erase() self.cmdbar.refresh() curses.echo() input = self.cmdbar.getstr() curses.noecho() return input def fit_window(self): self.max_y, self.max_x = self.win.getmaxyx() self.mwin.resize(self.max_y-2, self.max_x) self.mwin.mvwin(0,0) self.statbar.resize(1,self.max_x) self.statbar.mvwin(self.max_y-2, 0) self.cmdbar.resize(1, self.max_x) self.cmdbar.mvwin(self.max_y-1, 0) self.win.refresh() def show_timeline(self, all=False): self.fit_window() self.mwin.erase() length = len(self.loaded_statuses) if all == True: show_range = range(length) else: show_range = range(max(0, length-self.max_y), length) for i in show_range: status = self.loaded_statuses[i] self.mwin.addstr("\n%s:%s" % (status['user']['screen_name'], status['text'])) self.mwin.refresh() def tweet(self, content, in_reply_to=None): if in_reply_to == None: self.api.update_status(status=content) else: self.api.update_status(status=content, in_reply_to_status_id=in_reply_to) def retweet(self, id): self.api.retweet(id=id) def create_favorite(self, id): self.api.create_favorite(id=id) def change_modename(self, name): self.modename = name self.statbar_refresh() def statbar_refresh(self): self.statbar.erase() self.statbar.addstr(" (%s)" % self.modename) self.statbar.refresh() def cmdbar_output(self, text): self.cmdbar.erase() self.cmdbar.addnstr(text, self.max_x) self.cmdbar.refresh() def on_status(self, status): self.mwin.addstr("%s: %s\n" % (status['user']['screen_name'], status['text'])) self.mwin.refresh() self.loaded_statuses.append(status)
# import twitter # api = twitter.Api() # # api = twitter.Api(consumer_key='O5Z1KINSBaDEQgTBB3FA', # consumer_secret='kf42pzVoDrmP4hoe9LNQW5t765J2zEspqdHQhotw', # access_token_key='2172397754-TrCNJSgVarJIMnYb6uLXFzfI76zI7m8cfy5zIvL', # access_token_secret='FNiDwwbgs0WiElgaJ2hVECnsyavUKIQ3IP7JNr4BkiOhx') # # print api.VerifyCredentials() # token = 'FNiDwwbgs0WiElgaJ2hVECnsyavUKIQ3IP7JNr4BkiOhx' # token_key = '2172397754-TrCNJSgVarJIMnYb6uLXFzfI76zI7m8cfy5zIvL' # con_secret = 'kf42pzVoDrmP4hoe9LNQW5t765J2zEspqdHQhotw' # con_secret_key = 'O5Z1KINSBaDEQgTBB3FA' # # # from twitter import Twitter # twitter = Twitter(auth=OAuth(token, token_key, con_secret, con_secret_key)) # twitter.statuses.public_timeline() from twython import Twython APP_KEY = 'O5Z1KINSBaDEQgTBB3FA' APP_SECRET = 'kf42pzVoDrmP4hoe9LNQW5t765J2zEspqdHQhotw' OAUTH_TOKEN = '2172397754-TrCNJSgVarJIMnYb6uLXFzfI76zI7m8cfy5zIvL' OAUTH_TOKEN_SECRET = 'FNiDwwbgs0WiElgaJ2hVECnsyavUKIQ3IP7JNr4BkiOhx' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) print twitter.get_home_timeline() print twitter.search(q='twitter') print twitter.search(q='twitter', result_type='popular')
"!countdown": bot.countdown, "!quit": bot.quit } moduleCalls[command](x) except Exception as ex: pass # trigger = file.read() twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) since = "1050347525364830208" while True: while True: limits = twitter.get_application_rate_limit_status() howmany = limits["resources"]["statuses"]["/statuses/home_timeline"][ "remaining"] if int(howmany) <= 0: break timewhen = limits["resources"]["statuses"]["/statuses/home_timeline"][ "reset"] wait = (int(timewhen) - int(datetime.now().strftime('%s'))) / howmany timeline = twitter.get_home_timeline(since_id=since) print("get_home_timeline calls remaining {} reset in {}".format( howmany, wait * howmany)) for tweet in reversed(timeline): since = tweet['id'] check(tweet) time.sleep(wait) timeleft = int(timewhen) - int(datetime.now().strftime('%s')) time.sleep(timeleft)
def getLatestStreamTwitter(self): appId = "Use your api key" appSecret = "Use your api key" twitter = Twython(appId,appSecret,self.accessToken,self.accessTokenSecret) return twitter.get_home_timeline(count=5)
import sys from twython import Twython, TwythonError CONSUMER_KEY = 'XXXXXXXXXXXXXXXXXX' CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXXXX' ACCESS_KEY = 'XXXXXXXXXXXXXXXXX' ACCESS_SECRET = 'XXXXXXXXXXXXXXXXXXX' twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) #Setting Twitter's search results as a variable #ADD result_type PARAMETER search_results = twitter.search(q='giveaway', count=2) #get timeline tweets and set as variable timeline_tweets = twitter.get_home_timeline(count=2) print(search_results) #retweet tweets from search_results try: for tweet in search_results["statuses"]: twitter.retweet(id = tweet["id_str"]) twitter.create_favorite(id = tweet["id_str"]) st=tweet["entities"]["user_mentions"] if st != []: twitter.create_friendship(screen_name=st[0]["screen_name"]) except TwythonError as e: print e #favorite(like) tweets from timeline(home feed)
from twython import Twython from pprint import pprint import time from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate twitter = Twython() APP_KEY = '' APP_SECRET = '' OAUTH_TOKEN = '' OAUTH_TOKEN_SECRET = '' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) timeline = twitter.get_home_timeline() lcd = Adafruit_CharLCDPlate() col = (lcd.RED, lcd.YELLOW, lcd.GREEN, lcd.TEAL, lcd.BLUE, lcd.VIOLET, lcd.ON) paused = False current = {'tweet': None, 'date': None, 'screen': None, 'name': None } btn = {'left': lcd.LEFT, 'up': lcd.UP, 'down': lcd.DOWN, 'right': lcd.RIGHT, 'select': lcd.SELECT} def WrapText(text): if 33 > len(text) < 16: toList = list(text)
TOKEN_SECRET = '1c3Uaxttd9KrhtPJiyjgJSbzfzaysAQKvVM0P1NVUJkuu' # Conexión a twitter twitter = Twython(APP_KEY, APP_SECRET, TOKEN, TOKEN_SECRET) # 1 - Guardar a un fichero la lista de ids de tweets print print "Home timeline" print "=============" print print "La home timeline son los tweets míos y de los que sigo" print tweets = twitter.get_home_timeline() for tweet in tweets: print "%d -> %s" % (tweet['id'], tweet['text']) print print "User timeline" print "=============" print print "La user timeline son los tweets míos" print tweets = twitter.get_user_timeline() for tweet in tweets: print "%d -> %s" % (tweet['id'], tweet['text'])
auth_props = t.get_authentication_tokens( callback_url='http://localhost.com/login_twitter.html') oauth_token = '90926098-ha8yQlvDrtI92odzBcVlBehmxGpZdrOQqLOJAFs4E' oauth_token_secret = '2n8hPIA9yF6J20G9ZjWAcDLAnKarvSYbYyjV8EDw' oauth_verifier = '' try: t = Twython(app_key, app_secret, oauth_token, oauth_token_secret) followers = t.get_followers_ids() for follower_id in followers['ids']: print follower_id tweets = t.get_home_timeline() for tweet in tweets: print 'Name: %s \n' % (tweet['user']['name'].encode('utf-8')) print 'Tweet: %s \n' % (tweet['text'].encode('utf-8')) mentions = t.get_mentions_timeline() for mention in mentions: print 'Name: %s \n' % (mention['user']['name'].encode('utf-8')) print 'Mention: %s \n' % (mention['text'].encode('utf-8')) except TwythonAuthError as e: print e except TwythonError as er: print er
class TwitterImageDownloader(object): """Twitterから画像をダウンロードする""" def __init__(self): super(TwitterImageDownloader, self).__init__() self.twitter =Twython(app_key=CK, app_secret=CS, oauth_token=ATK, oauth_token_secret=ATS) def read_ids(self): ids_all = [line.replace('@', '') for line in SCREEN_NAMES.splitlines() if line] ids = sorted(list(set(ids_all))) return ids def get_timeline(self, screen_name): max_id = '' url_list = [] for i in xrange(NUM_PAGES): try: print 'getting timeline : @', screen_name, (i+1), 'page' #tw_result = (self.twitter.get_user_timeline(screen_name=screen_name, count=TWEET_PER_PAGE, max_id=max_id) if max_id else self.twitter.get_user_timeline(screen_name=screen_name, count=TWEET_PER_PAGE)) tw_result = (self.twitter.get_home_timeline(count=TWEET_PER_PAGE, max_id=max_id) if max_id else self.twitter.get_home_timeline(count=TWEET_PER_PAGE)) time.sleep(5) except Exception as e: print "timeline get error ", e break else: for result in tw_result: if 'media' in result['entities']: media = result['extended_entities']['media'] for url in media: url_list.append(url['media_url']) max_id = result['id'] if len(tw_result) < TWEET_PER_PAGE: break return url_list def create_folder(self, save_dir): try: os.mkdir(save_dir) except Exception as e: print 'cannot make dir', e file_list = os.listdir(save_dir) return file_list def get_file(self, url, file_list, save_dir): file_name = url[url.rfind('/')+1:] url_large = '%s:large'%(url) if not file_name in file_list: save_path = os.path.join(save_dir, file_name) try: print "download", url_large url_req = urllib2.urlopen(url_large) except Exception as e: print "url open error", url_large, e else: print "saving", save_path img_read = url_req.read() img = open(save_path, 'wb') img.write(img_read) img.close() time.sleep(1) else: print "file already exists", file_name def download(self): screen_name_list = self.read_ids() num_users = len(screen_name_list) for i, screen_name in enumerate(screen_name_list): save_dir = os.path.join(IMAGES_DIR, screen_name) file_list = self.create_folder(save_dir) url_list = self.get_timeline(screen_name) num_urls = len(url_list) for j, url in enumerate(url_list): self.get_file(url, file_list, save_dir) print "%d / %d users, %d / %d pictures"%((i+1), num_users, (j+1), num_urls)
def thanks(request): file = open('temp_token', 'r') profile = [] for line in file: profile.append(line) # profile_tokens = [e.oauth_token for e in TwitterUser.objects.all()] # profile_secrets = [e.oauth_secret for e in TwitterUser.objects.all()] # print ("profile",profile[0]) OAUTH_TOKEN = profile[0] OAUTH_TOKEN_SECRET = profile[1] # print ("TOKEN and SECRET",OAUTH_TOKEN,OAUTH_TOKEN_SECRET) oauth_verifier = request.GET['oauth_verifier'] twitter_ = Twython(settings.APP_KEY, settings.APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter_.get_authorized_tokens(oauth_verifier) FINAL_OAUTH_TOKEN = final_step['oauth_token'] FINAL_OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] twitter_ = Twython(settings.APP_KEY, settings.APP_SECRET, FINAL_OAUTH_TOKEN, FINAL_OAUTH_TOKEN_SECRET) new_twitter = twitter.Api( settings.APP_KEY, settings.APP_SECRET, FINAL_OAUTH_TOKEN, FINAL_OAUTH_TOKEN_SECRET, sleep_on_rate_limit=True) #shifting api for advanced access user = twitter_.verify_credentials() data = json.dumps(twitter_.get_home_timeline()) l_data = json.loads(data) check_user = TwitterUser.objects.filter(user_id=user['id']) user_found = 1 try: pro_token_data = TwitterUser.objects.get(user_id=user['id']) pro_token_data = { 'oauth_token': pro_token_data.oauth_token, 'oauth_token_secret': pro_token_data.oauth_token_secret } except: user_found = 0 # # print ("Pro token",pro_token_data['oauth_token']) # print "Count of check_user",check_user.count() if check_user.count() == 0 or user_found: user_profile = TwitterUser() if not user_found: user_profile.user_id = user['id'] #change user id if no user found user_profile.user_name = user['screen_name'] user_profile.oauth_token = FINAL_OAUTH_TOKEN user_profile.oauth_secret = FINAL_OAUTH_TOKEN_SECRET print("SEE THIS", user['id'], user['screen_name']) user_profile.save() for i in range(len(l_data)): user_tweets = UserTweet() # user_tweets.json_data = l_data user_tweets.since_id = l_data[i]['id'] user_tweets.user_id_id = user['id'] user_tweets.created_at = l_data[i]['created_at'] user_tweets.favorite_count = l_data[i]['favorite_count'] user_tweets.text = l_data[i]['text'] urls = l_data[i]['entities']['urls'] url_s = '' if urls: url_s += urls[0]['url'] for u in range(1, len(urls)): try: url_s = url_s + ',' + urls[u]['url'] except Exception as err: print("Exception while getting urls fix please", err) print('URLS', url_s) user_tweets.urls = url_s user_tweets.screen_name_tweet = l_data[i]['user'][ 'screen_name'] user_tweets.save() try: cron_task.createThread(twitter_, user['id']) except: print("Error in creating cron_task") else: if pro_token_data[ 'oauth_token'] != FINAL_OAUTH_TOKEN and pro_token_data[ 'oauth_secret'] != FINAL_OAUTH_TOKEN_SECRET: user_profile.oauth_secret = FINAL_OAUTH_TOKEN_SECRET user_profile.oauth_token = FINAL_OAUTH_TOKEN user_profile.save() try: cron_task.createThread(twitter_, user['id']) except: print("Error in creating cron_task") # # return HttpResponse('<h5>thanks '+user['screen_name']+' for signing up!</h5>') request.session['user_name'] = user['screen_name'] request.session['user_id'] = user['id'] # request.session['user_name'] = 'm_s_e_m_n' # request.session['user_id'] = 864336222784593920 return redirect('/feeder')
def getTimeline(self, user_name): tuser = TwitterUser.objects.get(user_name=user_name) twython = Twython(self.appObj.consumer_key, self.appObj.consumer_secret, tuser.auth, tuser.auth_secret) return twython.get_home_timeline()
from twython import Twython APP_KEY = 'jByrnJjBK1qwXbAs5IIXlGc7Q' APP_SECRET = 'ASQsvQnu0KGpPFakTDKbezy8dzYy9YEHGtGxy2ocgww2HGe322' OAUTH_TOKEN = '747471719342841856-ID2YX5V3iM4suIxyIWMZSmfVnnlwjcZ' OAUTH_TOKEN_SECRET = 'hyL409iSVq8LWLUNDqwQdIBiySm1fHYOucYXsIhub62cs' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) twitter.verify_credentials() twitter.get_home_timeline() # t = twitter.search(q='herramienta') results = twitter.cursor(twitter.search, q='herramienta', count=10) for result in results: print(result['text']) # print(t) # ACCESS_TOKEN = twitter.obtain_access_token()
# for meaning in definitions: # print(meaning.text.strip()) if definitions: print('The Definition - {}'.format(definitions[0].text.strip())) else: print('Definition not found on web:(\n') # This connects to my twitter account and brings the tweets t = Twython('92UbSi1YbvPI5umlJVV6xwL62', 'EMM846L8yfj3hP5T14mdxHKDII1rb9AV7whUUjwVy4X4ZTcx0c', '2257672447-BSkO8JVaFWzrPebefP3bCrY09AAh11Tq1yaX66c', 'BrgI4HvNpqs1tg7u1q0JBYuBH5uePGHW5i1GjRrhZxo8U') tl = t.get_home_timeline() json.dumps(tl) s = genson.Schema() s.add_object(tl) tweets = [] def timeline(): for i in range(0, len(tl)): # pprint(tl[i]['text']) tweets.append(tl[i]['text']) tweets_dict = {'tweets': tweets} return tweets_dict # This function is to load all the dictionary word and
quotePage = requests.get('https://www.brainyquote.com/quotes_of_the_day.html') quotePage.raise_for_status() quotePageSoup = bs4.BeautifulSoup(quotePage.text, "html.parser") AllQuotes = quotePageSoup.find_all('div', class_='mbl_qtbox qotd-qbox boxy bqQt' ) #class_='bqcpx' class name was changed. randomQuote = AllQuotes[randint(0, 5)].getText() printFrom = int( randomQuote.index("Day") + 5 ) #A bug appeared, first it sliced one character too many, now one character too little. Maybe in a while 5 needs to be changed back to 4. I want to edit the output so I can add some hashtags(twitter only allows 140 characters per tweet). randomQuote = randomQuote[printFrom:] randomQuote = randomQuote.strip( ) #don't know why, but they added whitespace at the end of the quote. This fixes that. ExistingTweets = api.get_home_timeline(count=9) #Here we check if the quote hasn't been tweeted already. while True: already_tweeted = False for tweets in ExistingTweets: if randomQuote[:15] == tweets['text'][:15]: already_tweeted = True break if already_tweeted: randomQuote = AllQuotes[randint(0, 5)].getText() printFrom = int(randomQuote.index("Day") + 5) #Don't forget to change this slicing as well! randomQuote = randomQuote[printFrom:] else: break
from twython import Twython import configparser config = configparser.RawConfigParser() config.read('enter.tw') APP_KEY = config.get('MINEKRAFT', 'API_KEY') APP_SECRET = config.get('MINEKRAFT', 'API_SECRET') OAUTH_TOKEN = config.get('MINEKRAFT', 'ACCESS_KEY') OAUTH_TOKEN_SECRET = config.get('MINEKRAFT', 'ACCESS_SECRET') tw = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) vec = tw.get_home_timeline() for i in vec: print(i)
if randNum == 0 or randNum == 1 or randNum == 2 or randNum == 3: return " " elif randNum == 4: return " Story Mode " else: randNum = getRandomInt(8) if randNum == 0 or randNum == 1 or randNum == 2 or randNum == 3: return ": Story Mode " elif randNum == 4 or randNum == 5 or randNum == 6: return ": Season 1 " elif randNum == 7 or randNum == 8: return ": The Game " twit = Twython(MY_CONSUMER_KEY, MY_CONSUMER_SECRET, MY_ACCESS_TOKEN_KEY, MY_ACCESS_TOKEN_SECRET) listOfTweets = twit.get_home_timeline(screen_name="ttgbrainstormer",count=200) while True: title = getTitle() title = title.strip() title = title.replace("\n","") if ":" in title: titty_tweet = title + getWord(True) + "- A Telltale Games Series" else: titty_tweet = title + getWord(False) + "- A Telltale Games Series" if titty_tweet not in listOfTweets: break
from twython import Twython APP_KEY = '' APP_SECRET = '' OAUTH_TOKEN = '' OAUTH_TOKEN_SECRET = '' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) # Example 1 tweet = twitter.get_home_timeline()[1] print("Tweet text: ", tweet["text"]) print("Tweet created at: ", tweet["created_at"]) print("Tweeted by: ", tweet["entities"]["user_mentions"][0]["name"]) print("Re Tweeted?: ", tweet["retweet_count"]) # Example 2 twitter.update_status(status='Python import antigravity https://xkcd.com/353/')
print(auth['auth_url']) oauth_verifier = request.GET['oauth_verifier'] twitter = Twython(config.api_key, config.api_secret, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) OAUTH_TOKEN = final_step['oauth_token'] OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] twitter = Twython(config.api_key, config.api_secret, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) print(twitter.get_home_timeline()) sample_analyze_sentiment(twitter.get_home_timeline()) """SPOTIFY API""" endpoint_url = "https://api.spotify.com/v1/recommendations?" limit = 20 energy = magnitude / 5.5 valence = (sentiment + 1) / 2 query = f'{endpoint_url}limit={limit}&energy={energy}&valence={valence}' response = requests.get(query, headers={ "Content-Type": "application/json", "Authorization": "87ff7cfc91704fa8aa827830b0a60544"
class TwythonAPITestCase(unittest.TestCase): def setUp(self): self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret) # Timelines def test_get_mentions_timeline(self): '''Test returning mentions timeline for authenticated user succeeds''' self.api.get_mentions_timeline() def test_get_user_timeline(self): '''Test returning timeline for authenticated user and random user succeeds''' self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): '''Test returning a protected user timeline who you are following succeeds''' self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): '''Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError''' self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_get_home_timeline(self): '''Test returning home timeline for authenticated user succeeds''' self.api.get_home_timeline() # Tweets def test_get_retweets(self): '''Test getting retweets of a specific tweet succeeds''' self.api.get_retweets(id=test_tweet_id) def test_show_status(self): '''Test returning a single status details succeeds''' self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): '''Test updating and deleting a status succeeds''' status = self.api.update_status(status='Test post just to get deleted :(') self.api.destroy_status(id=status['id_str']) def test_retweet(self): '''Test retweeting a status succeeds''' retweet = self.api.retweet(id='99530515043983360') self.api.destroy_status(id=retweet['id_str']) def test_retweet_twice(self): '''Test that trying to retweet a tweet twice raises a TwythonError''' retweet = self.api.retweet(id='99530515043983360') self.assertRaises(TwythonError, self.api.retweet, id='99530515043983360') # Then clean up self.api.destroy_status(id=retweet['id_str']) def test_get_oembed_tweet(self): '''Test getting info to embed tweet on Third Party site succeeds''' self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): '''Test getting ids for people who retweeted a tweet succeeds''' self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): '''Test searching tweets succeeds''' self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): '''Test getting the authenticated users direct messages succeeds''' self.api.get_direct_messages() def test_get_sent_messages(self): '''Test getting the authenticated users direct messages they've sent succeeds''' self.api.get_sent_messages() def test_send_get_and_destroy_direct_message(self): '''Test sending, getting, then destory a direct message succeeds''' message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d!') self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) def test_send_direct_message_to_non_follower(self): '''Test sending a direct message to someone who doesn't follow you fails''' self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man!') # Friends & Followers def test_get_user_ids_of_blocked_retweets(self): '''Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds''' self.api.get_user_ids_of_blocked_retweets(stringify_ids='true') def test_get_friends_ids(self): '''Test returning ids of users the authenticated user and then a random user is following succeeds''' self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') def test_get_followers_ids(self): '''Test returning ids of users the authenticated user and then a random user are followed by succeeds''' self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') def test_lookup_friendships(self): '''Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds''' self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') def test_get_incoming_friendship_ids(self): '''Test returning incoming friendship ids succeeds''' self.api.get_incoming_friendship_ids() def test_get_outgoing_friendship_ids(self): '''Test returning outgoing friendship ids succeeds''' self.api.get_outgoing_friendship_ids() def test_create_friendship(self): '''Test creating a friendship succeeds''' self.api.create_friendship(screen_name='justinbieber') def test_destroy_friendship(self): '''Test destroying a friendship succeeds''' self.api.destroy_friendship(screen_name='justinbieber') def test_update_friendship(self): '''Test updating friendships succeeds''' self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets='false') def test_show_friendships(self): '''Test showing specific friendship succeeds''' self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): '''Test getting list of users authenticated user then random user is following succeeds''' self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): '''Test getting list of users authenticated user then random user are followed by succeeds''' self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): '''Test getting the authenticated user account settings succeeds''' self.api.get_account_settings() def test_verify_credentials(self): '''Test representation of the authenticated user call succeeds''' self.api.verify_credentials() def test_update_account_settings(self): '''Test updating a user account settings succeeds''' self.api.update_account_settings(lang='en') def test_update_delivery_service(self): '''Test updating delivery settings fails because we don't have a mobile number on the account''' self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') def test_update_profile(self): '''Test updating profile succeeds''' self.api.update_profile(include_entities='true') def test_update_profile_colors(self): '''Test updating profile colors succeeds''' self.api.update_profile_colors(profile_background_color='3D3D3D') def test_list_blocks(self): '''Test listing users who are blocked by the authenticated user succeeds''' self.api.list_blocks() def test_list_block_ids(self): '''Test listing user ids who are blocked by the authenticated user succeeds''' self.api.list_block_ids() def test_create_block(self): '''Test blocking a user succeeds''' self.api.create_block(screen_name='justinbieber') def test_destroy_block(self): '''Test unblocking a user succeeds''' self.api.destroy_block(screen_name='justinbieber') def test_lookup_user(self): '''Test listing a number of user objects succeeds''' self.api.lookup_user(screen_name='twitter,justinbieber') def test_show_user(self): '''Test showing one user works''' self.api.show_user(screen_name='twitter') def test_search_users(self): '''Test that searching for users succeeds''' self.api.search_users(q='Twitter API') def test_get_contributees(self): '''Test returning list of accounts the specified user can contribute to succeeds''' self.api.get_contributees(screen_name='TechCrunch') def test_get_contributors(self): '''Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account''' self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) def test_remove_profile_banner(self): '''Test removing profile banner succeeds''' self.api.remove_profile_banner() def test_get_profile_banner_sizes(self): '''Test getting list of profile banner sizes fails because we have not uploaded a profile banner''' self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users def test_get_user_suggestions_by_slug(self): '''Test getting user suggestions by slug succeeds''' self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): '''Test getting user suggestions succeeds''' self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): '''Test getting status of suggested users succeeds''' self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): '''Test getting list of favorites for the authenticated user succeeds''' self.api.get_favorites() def test_create_and_destroy_favorite(self): '''Test creating and destroying a favorite on a tweet succeeds''' self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): '''Test show lists for specified user''' self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): '''Test timeline of tweets authored by members of the specified list succeeds''' self.api.get_list_statuses(list_id=test_list_id) def test_create_update_destroy_list_add_remove_list_members(self): '''Test create a list, adding and removing members then deleting the list succeeds''' the_list = self.api.create_list(name='Stuff') list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed') # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name='johncena,xbox') self.api.delete_list_members(list_id=list_id, screen_name='johncena,xbox') # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_memberships(self): '''Test list of lists the authenticated user is a member of succeeds''' self.api.get_list_memberships() def test_get_list_subscribers(self): '''Test list of subscribers of a specific list succeeds''' self.api.get_list_subscribers(list_id=test_list_id) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): '''Test subscribing, is a list sub and unsubbing to list succeeds''' self.api.subscribe_to_list(list_id=test_list_id) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(list_id=test_list_id, screen_name=screen_name) self.api.unsubscribe_from_list(list_id=test_list_id) def test_is_list_member(self): '''Test returning if specified user is member of a list succeeds''' # Returns 404 if not list member self.api.is_list_member(list_id=test_list_id, screen_name='jack') def test_get_list_members(self): '''Test listing members of the specified list succeeds''' self.api.get_list_members(list_id=test_list_id) def test_get_specific_list(self): '''Test getting specific list succeeds''' self.api.get_specific_list(list_id=test_list_id) def test_get_list_subscriptions(self): '''Test collection of the lists the specified user is subscribed to succeeds''' self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): '''Test collection of lists the specified user owns succeeds''' self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): '''Test getting list of saved searches for authenticated user succeeds''' self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): '''Test getting list of saved searches for authenticated user succeeds''' saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): '''Test getting info about a geo location succeeds''' self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): '''Test reversing geocode succeeds''' self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): '''Test search for places that can be attached to a statuses/update succeeds''' self.api.search_geo(query='Toronto') def test_get_similar_places(self): '''Test locates places near the given coordinates which are similar in name succeeds''' self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): '''Test getting the top 10 trending topics for a specific WOEID succeeds''' self.api.get_place_trends(id=1) def test_get_available_trends(self): '''Test returning locations that Twitter has trending topic information for succeeds''' self.api.get_available_trends() def test_get_closest_trends(self): '''Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds''' self.api.get_closest_trends(lat='37', long='-122')
def get_home_time_line(oauth_token, oauth_token_secret, user_id, count=5, trim_user=True): twitter = Twython(consumer_key, consumer_secret, oauth_token, oauth_token_secret) result = twitter.get_home_timeline(user_id=user_id, count=count, trim_user=trim_user) return result
class TwyAPI(object): def __init__(self, request): self.request = request @view_config(route_name='callback', renderer='json') def callback(self): oauth_verifier = self.request.GET['oauth_verifier'] OAUTH_TOKEN = self.request.cookies['oauth_token'] OAUTH_TOKEN_SECRET = self.request.cookies['oauth_token_secret'] twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) OAUTH_TOKEN = final_step['oauth_token'] OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] # set cookies and redirect response = HTTPFound(location='https://twittpane-dev.freegate.co') response.set_cookie('oauth_token', OAUTH_TOKEN, max_age=86400) response.set_cookie('oauth_token_secret', OAUTH_TOKEN_SECRET, max_age=86400) return response @view_config(route_name='home', renderer='templates/home.jinja2') def home(self): if self.validate_auth() == False: self.auth() return {'project': 'twittpane'} @view_config(route_name='auth') def auth(self): self.twitter = Twython(APP_KEY, APP_SECRET) auth = self.twitter.get_authentication_tokens(callback_url=CALLBACK_URL) OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] auth_url = auth['auth_url'] # set cookies and redirect response = HTTPFound(location=auth_url) response.set_cookie('oauth_token', OAUTH_TOKEN, max_age=86400) response.set_cookie('oauth_token_secret', OAUTH_TOKEN_SECRET, max_age=86400) return response @view_config(route_name='validate_auth') def validate_auth(self): if 'oauth_token' in self.request.cookies and 'oauth_token_secret' in self.request.cookies: OAUTH_TOKEN = self.request.cookies['oauth_token'] OAUTH_TOKEN_SECRET = self.request.cookies['oauth_token_secret'] self.twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) return True else: return False @view_config(route_name='verify_credentials') def verify_credentials(self): if not hasattr(self, 'twitter'): if not self.validate_auth(): return None try: return self.twitter.verify_credentials() except TwythonError as e: return {"verify_credentials": e} @view_config(route_name='get_saved_searches') def get_saved_searches(self): if not hasattr(self, 'twitter'): if self.validate_auth() == False: return None try: return self.twitter.get_saved_searches() except TwythonError as e: return {"get_saved_searches": e} @view_config(route_name='create_saved_search') def create_saved_search(self): if not hasattr(self, 'twitter'): if self.validate_auth() == False: return None try: params = self.request.GET.dict_of_lists() return self.twitter.create_saved_search(**params) except TwythonError as e: return {"create_saved_search": e} @view_config(route_name='destroy_saved_search') def destroy_saved_search(self): if not hasattr(self, 'twitter'): if self.validate_auth() == False: return None try: #id_str = self.request.params['id'] params = {'id': self.request.params['id']} print(params) return self.twitter.destroy_saved_search(**params) except TwythonError as e: return {"destroy_saved_search": e} @view_config(route_name='search') def search(self): if not hasattr(self, 'twitter'): if self.validate_auth() == False: return None try: params = self.request.GET.dict_of_lists() return self.twitter.search(**params) except TwythonError as e: return {"search": e} @view_config(route_name='get_home_timeline') def get_home_timeline(self): if not hasattr(self, 'twitter'): if self.validate_auth() == False: return None try: params = self.request.GET.dict_of_lists() return self.twitter.get_home_timeline(**params) except TwythonError as e: return {"get_home_timeline": e}