class TwythonAuthTestCase(unittest.TestCase): def setUp(self): self.api = Twython(app_key, app_secret) self.bad_api = Twython('BAD_APP_KEY', 'BAD_APP_SECRET') self.bad_api_invalid_tokens = Twython('BAD_APP_KEY', 'BAD_APP_SECRET', 'BAD_OT', 'BAD_OTS') self.oauth2_api = Twython(app_key, app_secret, oauth_version=2) self.oauth2_bad_api = Twython('BAD_APP_KEY', 'BAD_APP_SECRET', oauth_version=2) def test_get_authentication_tokens(self): """Test getting authentication tokens works""" self.api.get_authentication_tokens(callback_url='http://google.com/', force_login=True, screen_name=screen_name) def test_get_authentication_tokens_bad_tokens(self): """Test getting authentication tokens with bad tokens raises TwythonAuthError""" self.assertRaises(TwythonAuthError, self.bad_api.get_authentication_tokens, callback_url='http://google.com/') def test_get_authorized_tokens_bad_tokens(self): """Test getting final tokens fails with wrong tokens""" self.assertRaises(TwythonError, self.bad_api.get_authorized_tokens, 'BAD_OAUTH_VERIFIER') def test_get_authorized_tokens_invalid_or_expired_tokens(self): """Test getting final token fails when invalid or expired tokens have been passed""" self.assertRaises(TwythonError, self.bad_api_invalid_tokens.get_authorized_tokens, 'BAD_OAUTH_VERIFIER') def test_get_authentication_tokens_raises_error_when_oauth2(self): """Test when API is set for OAuth 2, get_authentication_tokens raises a TwythonError""" self.assertRaises(TwythonError, self.oauth2_api.get_authentication_tokens) def test_get_authorization_tokens_raises_error_when_oauth2(self): """Test when API is set for OAuth 2, get_authorized_tokens raises a TwythonError""" self.assertRaises(TwythonError, self.oauth2_api.get_authorized_tokens, 'BAD_OAUTH_VERIFIER') def test_obtain_access_token(self): """Test obtaining an Application Only OAuth 2 access token succeeds""" self.oauth2_api.obtain_access_token() def test_obtain_access_token_bad_tokens(self): """Test obtaining an Application Only OAuth 2 access token using bad app tokens fails""" self.assertRaises(TwythonAuthError, self.oauth2_bad_api.obtain_access_token) def test_obtain_access_token_raises_error_when_oauth1(self): """Test when API is set for OAuth 1, obtain_access_token raises a TwythonError""" self.assertRaises(TwythonError, self.api.obtain_access_token)
class TwythonAuthTestCase(unittest.TestCase): def setUp(self): self.api = Twython(app_key, app_secret) def test_get_authentication_tokens(self): '''Test getting authentication tokens works''' self.api.get_authentication_tokens(callback_url='http://google.com/', force_login=True, screen_name=screen_name)
def twitter_login(request): if request.method == 'GET': twitter = Twython(creds.APP_KEY, creds.APP_SECRET) if settings.DEBUG: auth = twitter.get_authentication_tokens( callback_url='http://127.0.0.1:8000/callback') else: auth = twitter.get_authentication_tokens( callback_url='http://203.101.227.25/callback') request.session['oauth_token'] = auth['oauth_token'] request.session['oauth_token_secret'] = auth['oauth_token_secret'] return render(request, 'login.html', {'twitter_url': auth['auth_url']})
def OnLaunchWeb(self, e): twitter = Twython(self.APP_KEY, self.APP_SECRET) auth = twitter.get_authentication_tokens() self.OAUTH_TOKEN = auth['oauth_token'] self.OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] self.url = auth["auth_url"] webbrowser.open(self.url, new=2) self.pinwindow = PinWindow(self) self.pinwindow.ShowModal() self.pin = self.pinwindow.pin if self.pin is not None: oauth_verifier = self.pin twitter = Twython(self.APP_KEY, self.APP_SECRET, self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) self.OAUTH_TOKEN = final_step['oauth_token'] self.OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] self.codes = [self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET] self.LoadScreenName() else: print("No pin provided")
def auth(request): # oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) # oauth.set_access_token("2374233954-7qXgGv8iNwm1OHfYDsSNCjFnkE16hLJagKhC4D8", "UFOwbDsong5QuzMflfiTykn6y4mf7ZXf0Bbt5DLf5xxCt") # api = tweepy.API(oauth, proxy = "proxy.dlsu.edu.ph:80") # public_tweets = api.user_timeline() # for tweet in public_tweets: # print (tweet.text) # twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, client_args = {'proxies': {'https': 'http://proxy.dlsu.edu.ph:80'}}) twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri( reverse('thesisdatagathering:twitter_callback')) auth_props = twitter.get_authentication_tokens(callback_url) # Then send them over there, durh. print(request.POST) request.session['request_token'] = auth_props if 'date' not in request.session: print("OHHHH NOOOOOOOOOO") request.session['date'] = (request.POST['bdmonth'] + " " + request.POST['bdday'] + ", " + request.POST['bdyear']) request.session['gender'] = request.POST['gender'] else: print("ORAAAAAAAAAAAAAYTSUUUUU") return HttpResponseRedirect(auth_props['auth_url'])
def get_authenticated_twitter(): try: with open("./data/credentials.txt", "r") as file: lines = file.readlines() FINAL_OAUTH_TOKEN = lines[0][:-1] FINAL_OAUTH_TOKEN_SECRET = lines[1] twitter = Twython(APP_KEY, APP_SECRET, FINAL_OAUTH_TOKEN, FINAL_OAUTH_TOKEN_SECRET) twitter.verify_credentials() return twitter except: twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] print(auth['auth_url']) oauth_verifier = input('Enter your pin:') twitter = Twython(APP_KEY, 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(APP_KEY, APP_SECRET, FINAL_OAUTH_TOKEN, FINAL_OAUTH_TOKEN_SECRET) twitter.verify_credentials() with open("./data/credentials.txt", "w") as file: file.write(FINAL_OAUTH_TOKEN + "\n" + FINAL_OAUTH_TOKEN_SECRET) return twitter
def twitter_auth(): _logout() twitter = Twython(app.config['TWITTER_KEY'], app.config['TWITTER_SECRET']) auth = twitter.get_authentication_tokens(callback_url=url_for("twitter_auth_callback", _external=True)) session['OAUTH_TOKEN'] = auth['oauth_token'] session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret'] return redirect(auth['auth_url'])
def create_tokens(objConfig, app_key, app_secret): """ Gets new auth tokens and writes them in 'config.ini' file """ twitter = Twython(app_key, app_secret) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] print "To get your PIN number please go to: " print auth['auth_url']+"\n" oauth_verifier = raw_input('Please enter your PIN number: ') 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'] try: twitter = Twython(app_key, app_secret, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) user = twitter.verify_credentials()['screen_name'] print "Login successful." print "Account: "+user # save oauth_tokens in file cfgfile = open("tokens.ini",'w') objConfig.add_section('user') objConfig.set('user','OAUTH_TOKEN', OAUTH_TOKEN) objConfig.set('user','OAUTH_TOKEN_SECRET', OAUTH_TOKEN_SECRET) objConfig.write(cfgfile) cfgfile.close() return twitter except TwythonError as e: print e
def get_url(): app_key = 'LvMwTBueTS3IsN7sLIoaIA' app_secret = '0cdq8IZwccRMBPrwH9odVoCUaeLSH4RSx9df4' access_token = '295398619-lSehg93ixJJ80M4DyOtwpSsmnFzP70Ld4bpRInXm' access_token_secret = 'BttSbnwFY14Ysa68d5Xxcy3ZKi8eUgevNLgxq9Xo' t = Twython(app_key=app_key, app_secret=app_secret, callback_url='http://127.0.0.1:5000/register') auth_props = t.get_authentication_tokens() oauth_token = auth_props['oauth_token'] print "Oauth_token:" + oauth_token oauth_token_secret = auth_props['oauth_token_secret'] #a = auth_props['oauth_verifier'] print 'Connect to Twitter via: %s' % auth_props['auth_url'] auth_url = auth_props['auth_url'] t = Twython(app_key=app_key, app_secret=app_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) #user_timeline = t.getUserTimeline(screen_name='nytimes') return auth_url
def login(request): twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) auth = twitter.get_authentication_tokens( callback_url='http://localhost:8000/thanks') request.session['oauth_token'] = auth['oauth_token'] request.session['oauth_token_secret'] = auth['oauth_token_secret'] return HttpResponseRedirect(auth['auth_url'])
def getRetweetCount(twe_id): index = 0 while (index < len(APP_KEYS)): APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] try: twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) result = twitter.show_status(id=twe_id) ''' #print result['user']['screen_name'] + " " + result['user']['description'] tweet['Usr_Screename'] = result['user']['screen_name'] tweet['Usr_Description'] = result['user']['description'] tweet['FavoriteCount'] = int(result['favorite_count']) ''' return int(result['retweet_count']) except Exception as e: if "429 (Too Many Requests)" in str(e): index += 1 print "App Exceeded: index = %d" % (index) pass elif "404 (Not Found)" in str(e): return -1 elif "403 (Forbidden)" in str(e): return -1 else: print e return ''
def getRetweetCount(twe_id): index=0 while (index <len(APP_KEYS)): APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] try: twitter = Twython (APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) result = twitter.show_status(id=twe_id) ''' #print result['user']['screen_name'] + " " + result['user']['description'] tweet['Usr_Screename'] = result['user']['screen_name'] tweet['Usr_Description'] = result['user']['description'] tweet['FavoriteCount'] = int(result['favorite_count']) ''' return int(result['retweet_count']) except Exception as e: if "429 (Too Many Requests)" in str(e): index += 1 print "App Exceeded: index = %d"%(index) pass elif "404 (Not Found)" in str(e): return -1 elif "403 (Forbidden)" in str(e): return -1 else: print e return ''
def login(): twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens( callback_url='http://localhost:5000/callback', screen_name='') session['oauth_token'] = auth['oauth_token'] session['oauth_token_secret'] = auth['oauth_token_secret'] return redirect(auth['auth_url'])
def retrieve_access_token (self): output.speak(_("Please wait while an access token is retrieved from Twitter."), True) httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), Handler) twitterDataOrig = str(self.config['oauth']['twitterData']) trans = maketrans("-_~", "+/=") twitterDataTrans = twitterDataOrig.translate(trans) twitterData = b64decode(twitterDataTrans) twitterData = literal_eval(twitterData) tw = Twython(twitterData[0], twitterData[1], auth_endpoint='authorize', client_args = {'verify': False}) try: auth = tw.get_authentication_tokens("http://127.0.0.1:8080") except Exception as e: logging.exception("Unable to get authentication tokens: %s" % str(e)) output.speak(_("Unable to get access token. Something went wrong, please call the developers.")) try: webbrowser.open_new_tab(auth['auth_url']) except Exception as e: logging.exception("Unable to open web browser: %s" % str(e)) global logged, verifier logged = False while logged == False: httpd.handle_request() self.auth_handler = Twython(twitterData[0], twitterData[1], auth['oauth_token'], auth['oauth_token_secret'], client_args = {'verify': False}) token = self.auth_handler.get_authorized_tokens(verifier) output.speak(_("Retrieved access token from Twitter."), True) httpd.server_close() data = [token['oauth_token'], token['oauth_token_secret']] eData = dumps(data) trans = maketrans("+/=", "-_~") eData = b64encode(eData) eData = eData.translate(trans) self.config['oauth']['userData'] = eData self.login() del (httpd, auth, tw, token, logged, verifier, twitterData, twitterDataOrig, data, edata, self.auth_handler)
def Authentication(): APP_KEY = 'b1WTyzKmLnG7KwnDcYpiQ' APP_SECRET = 'gzKci8Gys0i831zt7gPq3fEpG4qq9kgOINfbKhS8' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] webbrowser.open(auth['auth_url']) twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens( str(raw_input("Please enter the PIN: ")) ) #atm pin must be entered through the terminal OAUTH_TOKEN = final_step['oauth_token'] OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] print APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) return twitter
def user_timeline(screenname, index=0): APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] twitter = Twython (APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() #OAUTH_TOKEN = auth['oauth_token'] #OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] #print OAUTH_TOKEN twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #ACCESS_TOKEN = twitter.obtain_access_token() #print twitter.verify_credentials() #ACCESS_TOKEN = '701759705421639681-nutlNGruF7WZjq0kXZUTcKVbrnXs3vD' #twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN) response = twitter.get_user_timeline(screen_name = screenname, count= 200, exclude_replies = True, include_rt = False) L = [] for r in response: L.append(r['text']) ''' d = {} d['text'] = r['text'] d['screenname'] = r['user']['screen_name'] d['date'] = r['created_at'] L.append(d) ''' return L
def getTweets(hashtag): client = MongoClient('mongodb://*****:*****@' + IP_MONGO_SERVER + '/twitter') db = client['twitter'] collection = db[hashtag.encode("utf-8")+"tmp"] APP_KEY = '8iuErv802dm1q9YQnOrtrcgIG' APP_SECRET = 'dMnTqnQvUwOk0foTcSl0yDp8MDThsgdsgAD0W5Ox6qrOw3QnsY' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] try: results = twitter.search(q=hashtag,lang='es',count='100') except TwythonError as e: print(e) for tweet in results['statuses']: #print('Usuario @%s Fecha: %s' % (tweet['user']['screen_name'].encode('utf-8'), tweet['created_at'])) ultimo = tweet #print('Geo: ' + tweet['user']['location']) #print('Contenido: ' + tweet['text'].encode('utf-8'), '\n\n') collection.insert(tweet)
def connect_twitter(request): t = Twython(settings.TWITTER_APP_KEY, settings.TWITTER_APP_SECRET) auth_props = t.get_authentication_tokens( callback_url=settings.TWITTER_CALLBACK_URL) request.session['oauth_token'] = auth_props['oauth_token'] request.session['oauth_token_secret'] = auth_props['oauth_token_secret'] return redirect(auth_props['auth_url'])
def twitter_token(request): ## Tomamos el absolute path de donde esta corriendo callback = request.build_absolute_uri() if request.GET: auth = request.session['twitter_auth'] ttoken = auth['oauth_token'] tsecret = auth['oauth_token_secret'] verifier = request.GET['oauth_verifier'] twitter = Twython(settings.TW_KEY, settings.TW_SECRET, ttoken, tsecret) oauth = twitter.get_authorized_tokens(verifier) token = oauth['oauth_token'] secret = oauth['oauth_token_secret'] else: twitter = Twython(settings.TW_KEY, settings.TW_SECRET) ## Se arma la URL para autenticar auth = twitter.get_authentication_tokens(callback_url=callback) url = auth['auth_url'] request.session['twitter_auth'] = auth template = 'twitter_token.html' return render(request, template, locals())
def __oauth(Rate_id): """ twitter로부터 인증토큰을 받기 위한 함수 """ try: twitter = Twython(current_app.config['TWIT_APP_KEY'], current_app.config['TWIT_APP_SECRET']) callback_svr = current_app.config['TWIT_CALLBACK_SERVER'] auth = twitter.get_authentication_tokens( callback_url= callback_svr + \ url_for('.callback', Rate_id=Rate_id)) # 중간단계로 받은 임시 인증토큰은 최종인증을 위해 필요하므로 세션에 저장한다. session['OAUTH_TOKEN'] = auth['oauth_token'] session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret'] except TwythonError as e: Log.error("__oauth(): TwythonError , "+ str(e)) session['TWITTER_RESULT'] = str(e) return redirect(url_for('.show_all')) # 트위터의 사용자 권한 인증 URL로 페이지를 리다이렉트한다. return redirect(auth['auth_url'])
def twitter_search(twitter_id, index = 0): APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] twitter = Twython (APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() #OAUTH_TOKEN = auth['oauth_token'] #OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] #print OAUTH_TOKEN twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #ACCESS_TOKEN = twitter.obtain_access_token() #print twitter.verify_credentials() #ACCESS_TOKEN = '701759705421639681-nutlNGruF7WZjq0kXZUTcKVbrnXs3vD' #twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN) response = twitter.get_user_timeline(screen_name = twitter_id) # gets 20 results, by default L = [] for r in response: d = {} d['text'] = r['text'] d['screenname'] = r['user']['screen_name'] d['date'] = r['created_at'] L.append(d) return L
def main(request, num="1"): tweets = ['1111','22222','3333'] template_name = 'main_view.html' if request.POST: tweets.append("Tweetout - " + settings.TWITTER_CONSUMER_KEY) twitter = Twython(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET) auth = twitter.get_authentication_tokens(callback_url=settings.TWITTER_CALLBACK_URL) #callback_url='' #Not final tokens, save in session later OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] request.session['OAUTH_TOKEN'] = OAUTH_TOKEN request.session['OAUTH_TOKEN_SECRET'] = OAUTH_TOKEN_SECRET #redirect to this url URL = auth['auth_url'] print "********************" print OAUTH_TOKEN print OAUTH_TOKEN_SECRET if URL: return HttpResponseRedirect(URL) return render_to_response("main_view.html",{'tweets': tweets}, context_instance=RequestContext(request))
def retrieve_access_token (self): output.speak(_("Please wait while an access token is retrieved from Twitter."), True) httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), Handler) twitterDataOrig = str(self.config['oauth']['twitterData']) trans = maketrans("-_~", "+/=") twitterDataTrans = twitterDataOrig.translate(trans) twitterData = b64decode(twitterDataTrans) twitterData = literal_eval(twitterData) tw = Twython(twitterData[0], twitterData[1], auth_endpoint='authorize') try: auth = tw.get_authentication_tokens("http://127.0.0.1:8080") except SSLError: output.speak(_("Sorry, we can't connect to Twitter. You may want to adjust your firewall or antivirus software appropriately"), True) webbrowser.open_new_tab(auth['auth_url']) global logged, verifier logged = False while logged == False: httpd.handle_request() self.auth_handler = Twython(twitterData[0], twitterData[1], auth['oauth_token'], auth['oauth_token_secret']) token = self.auth_handler.get_authorized_tokens(verifier) output.speak(_("Retrieved access token from Twitter."), True) httpd.server_close() data = [token['oauth_token'], token['oauth_token_secret']] eData = dumps(data) trans = maketrans("+/=", "-_~") eData = b64encode(eData) eData = eData.translate(trans) self.config['oauth']['userData'] = eData self.login() del (httpd, auth, tw, token, logged, verifier, twitterData, twitterDataOrig, data, edata, self.auth_handler)
def __oauth(photolog_id): """ twitter로부터 인증토큰을 받기 위한 함수 """ try: twitter = Twython(current_app.config['TWIT_APP_KEY'], current_app.config['TWIT_APP_SECRET']) callback_svr = current_app.config['TWIT_CALLBACK_SERVER'] auth = twitter.get_authentication_tokens( callback_url= callback_svr + \ url_for('.callback', photolog_id=photolog_id)) # 중간단계로 받은 임시 인증토큰은 최종인증을 위해 필요하므로 세션에 저장한다. session['OAUTH_TOKEN'] = auth['oauth_token'] session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret'] except TwythonError as e: Log.error("__oauth(): TwythonError , "+ str(e)) session['TWITTER_RESULT'] = str(e) return redirect(url_for('.show_all')) # 트위터의 사용자 권한 인증 URL로 페이지를 리다이렉트한다. return redirect(auth['auth_url'])
def tweet_generated_song(parts, number): load_dotenv(find_dotenv()) if not (os.environ.get('TWITTER_AUTH_TOKEN') or os.environ.get('TWITTER_AUTH_SECRET')): twitter = Twython(os.environ.get('TWITTER_CONSUMER_KEY'), os.environ.get('TWITTER_CONSUMER_SECRET')) auth = twitter.get_authentication_tokens() verifier = input( 'Please visit {} for authorizing your twitter and type the ' 'verification code here: '.format(auth['auth_url'])) twitter = Twython(os.environ.get('TWITTER_CONSUMER_KEY'), os.environ.get('TWITTER_CONSUMER_SECRET'), auth['oauth_token'], auth['oauth_token_secret']) final_step = twitter.get_authorized_tokens(verifier) set_key(find_dotenv(), 'TWITTER_AUTH_TOKEN', final_step['oauth_token']) set_key(find_dotenv(), 'TWITTER_AUTH_SECRET', final_step['oauth_token_secret']) load_dotenv(find_dotenv()) twitter = Twython(os.environ.get('TWITTER_CONSUMER_KEY'), os.environ.get('TWITTER_CONSUMER_SECRET'), os.environ.get('TWITTER_AUTH_TOKEN'), os.environ.get('TWITTER_AUTH_SECRET')) with open(path('out.mp4'), 'rb') as video: response = twitter.upload_video(media=video, media_type='video/mp4', media_category='tweet_video', check_progress=True) twitter.update_status(status=update_header( 'Musikalisches Würfelspiel (K516f) No. #id#', number, parts), media_ids=[response['media_id_string']])
def Authentication(): APP_KEY = 'b1WTyzKmLnG7KwnDcYpiQ' APP_SECRET = 'gzKci8Gys0i831zt7gPq3fEpG4qq9kgOINfbKhS8' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth ['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] webbrowser.open(auth['auth_url']) twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(str(raw_input("Please enter the PIN: "))) #atm pin must be entered through the terminal OAUTH_TOKEN = final_step['oauth_token'] OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] print APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) return twitter
def authenticate(self, token_file): """ Authenticate with Twitter and save the OAUTH tokens""" keys = {} keys['app_key'] = input('Enter the App Consumer Key: ').strip() keys['app_secret'] = input('Enter the App Consumer Secret: ').strip() twitter = Twython(**keys) auth = twitter.get_authentication_tokens() keys['oauth_token'] = auth['oauth_token'] keys['oauth_token_secret'] = auth['oauth_token_secret'] auth_url = auth['auth_url'] print(f'\nVisit this url to authorize the application: {auth_url}\n') oauth_verifier = input('Enter the PIN code: ') twitter = Twython(**keys) auth = twitter.get_authorized_tokens(oauth_verifier) keys['oauth_token'] = auth['oauth_token'] keys['oauth_token_secret'] = auth['oauth_token_secret'] with open(token_file, 'w') as fp: json.dump(keys, fp) print(f'The authorized user tokens were saved to {token_file}')
def getAuthTokens(): f_authTokens = open(config.FILE_TMP_TOKENS, 'w') # get first auth twitter = Twython(config.APP_KEY, config.APP_SECRET) firstAuth = twitter.get_authentication_tokens() # get auth pin print 'auth url: ' + firstAuth['auth_url'] authPin = getpass('pin: ') # get second auth twitter = Twython( config.APP_KEY, config.APP_SECRET, firstAuth['oauth_token'], firstAuth['oauth_token_secret']) secondAuth = twitter.get_authorized_tokens(authPin) # save tokens to a file for key in secondAuth: line = key + '\t' + secondAuth[key] + '\n' f_authTokens.write(line) f_authTokens.close() return secondAuth
def config_twitter(config): if 'twitter' in config.keys(): replace = input("Twitter configuration already exists. Replace? (Y/n) ") if replace.lower() in ['n','no']: return config input("Create a new Twitter app at https://apps.twitter.com/app/new to post matching stories. For this step, you can be logged in as yourself or with the posting account, if they're different. Fill out Name, Description, and Website with values meaningful to you. These are not used in trackthenews config but may be publicly visible. Then click the \"Keys and Access Tokens\" tab. ") api_key = input("Enter the provided API key: ") api_secret = input("Enter the provided API secret: ") input("Now ensure you are logged in with the account that will do the posting. ") tw = Twython(api_key, api_secret) auth = tw.get_authentication_tokens() oauth_token = auth['oauth_token'] oauth_secret = auth['oauth_token_secret'] tw = Twython(api_key, api_secret, oauth_token, oauth_secret) pin = input("Enter the pin found at {} ".format(auth['auth_url'])) final_step = tw.get_authorized_tokens(pin) oauth_token = final_step['oauth_token'] oauth_secret = final_step['oauth_token_secret'] twitter = {'api_key': api_key, 'api_secret': api_secret, 'oauth_token': oauth_token, 'oauth_secret': oauth_secret} config['twitter'] = twitter return config
def twitter_search(twitter_id, index=0): APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() #OAUTH_TOKEN = auth['oauth_token'] #OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] #print OAUTH_TOKEN twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #ACCESS_TOKEN = twitter.obtain_access_token() #print twitter.verify_credentials() #ACCESS_TOKEN = '701759705421639681-nutlNGruF7WZjq0kXZUTcKVbrnXs3vD' #twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN) response = twitter.get_user_timeline(screen_name=twitter_id) # gets 20 results, by default L = [] for r in response: d = {} d['text'] = r['text'] d['screenname'] = r['user']['screen_name'] d['date'] = r['created_at'] L.append(d) return L
def oauth1(self): twitter = Twython(self.__APP_KEY, self.__APP_SECRET) #create twython object, v.1 auth = twitter.get_authentication_tokens() #get oauth v.1 tokens OAUTH_TOKEN = auth['oauth_token'] #pull out of auth OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] #pull out of auth with open('token2a.key','w') as f: #open file to store tokens key f.write(OAUTH_TOKEN) #write token to file f.write('\n') #newline to separate tokens f.write(OAUTH_TOKEN_SECRET) #write token secret to file print(auth['auth_url']) #print auth_url to screen #user must follow and allow access to complete authorization, see oauth doc oauth_verifier = input('Enter pin: ') #reinstantiate twitter as twython object (authorized) twitter = Twython(self.__APP_KEY, self.__APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_tokens = twitter.get_authorized_tokens(oauth_verifier) #final step fot = final_tokens['oauth_token'] #final oauth token fots = final_tokens['oauth_token_secret'] #final oauth secret token #final tokens can be saved and used repeatedly in new objects #twythonobj->authentication->verify->twythonobj2->authorization->storekeys with open('token2f.key','w') as r: r.write(fot) r.write('\n') r.write(fots)
def personalAuthentication(): allKeys = fileToList(TOKEN_FILE) if len(allKeys[0]) > 4: # we've already saved the personal token for key in authentication_keys.keys(): # The 4th item of the list of key data will be the key for a # personal account authentication_keys[key] = readToken(allKeys, key, 4) else: twitter = Twython(authentication_keys['APP_KEY'], authentication_keys['APP_SECRET']) auth = twitter.get_authentication_tokens() import webbrowser # Open a webpage with your twitter code webbrowser.open(auth['auth_url']) try: auth_pin = input("Please enter the code from twitter: ") except: # python 2.7 auth_pin = raw_input("Please enter the code from twitter: ") # These are temporary, part of the overall authentication process OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] twitter = Twython(authentication_keys['APP_KEY'], authentication_keys['APP_SECRET'], OAUTH_TOKEN, OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(auth_pin) authentication_keys['OAUTH_KEY'] = final_step['oauth_token'] authentication_keys['OAUTH_SECRET'] = final_step['oauth_token_secret'] writeKeys(authentication_keys, TOKEN_FILE)
def generate(request): context = RequestContext(request) if request.method == 'POST': form = BotTokenForm(request.POST) if form.is_valid(): global yellow yellow = Bot.objects.get(id=request.POST.get('user')) twitter = Twython(settings.API, settings.API_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri(reverse('grabber.views.thanks')) auth_props = twitter.get_authentication_tokens(callback_url) # Then send them over there, durh. request.session['request_token'] = auth_props return HttpResponseRedirect(auth_props['auth_url']) else: print form.errors else: form = BotTokenForm() return render_to_response('grabber/generate.html',{'form': form}, context)
def fetchTweets(self, initialDate, finalDate, keywordCollection): twitter = Twython(self._APP_KEY, self._APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] twitterFinal = Twython(self._APP_KEY, self._APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) sinceDate = initialDate.strftime("%Y-%m-%d") untilDate = finalDate.strftime("%Y-%m-%d") #query = keyword + ' since:' + initialDate.strftime("%Y/%m/%d") + ' until:' + finalDate.strftime("%Y/%m/%d") keyword = ' OR '.join(keywordCollection) keyword = urllib.parse.quote_plus(keyword) # print(keyword) query = keyword + ' since:' + sinceDate + ' until:' + untilDate try: search_results = twitter.search(q=query, count=100) except TwythonError as e: print(e) return search_results
def index(request): if 'oauth_verifier' in request.GET: #coming back from Twitter. oauth_verifier = request.GET['oauth_verifier'] t_api = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, request.session['OAUTH_TOKEN'], request.session['OAUTH_TOKEN_SECRET']) final_tokens = t_api.get_authorized_tokens(oauth_verifier) request.session['OAUTH_TOKEN'] = final_tokens['oauth_token'] request.session['OAUTH_TOKEN_SECRET'] = final_tokens[ 'oauth_token_secret'] return HttpResponseRedirect("/post") else: t_api = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) auth_props = t_api.get_authentication_tokens( callback_url=settings.TWITTER_CALLBACK) a_url = auth_props['auth_url'] request.session['OAUTH_TOKEN'] = auth_props['oauth_token'] request.session['OAUTH_TOKEN_SECRET'] = auth_props[ 'oauth_token_secret'] return render(request, 'index.html', locals(), context_instance=RequestContext(request))
def get_oauth_tokens(app_key, app_secret): """ Supply `app_key`, `app_secret` Requires user to signin and confirm oauth1 to create oauth1 tokens get oauth1 authentication tokens: (`oauth_token`, `oauth_token_secret`) cf https://twython.readthedocs.io/en/latest/usage/starting_out.html#oauth1 """ twitter = Twython(app_key, app_secret) auth = twitter.get_authentication_tokens() #callback_url='oob' oauth_token = auth['oauth_token'] oauth_token_secret = auth['oauth_token_secret'] twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret) oauth_verifier = input( "1. Sign-in on Twitter.com using URL:\n{auth_url}\n\n2.Enter your pin here:" .format(auth_url=auth['auth_url'])) final_step = twitter.get_authorized_tokens(oauth_verifier) final_oauth_token = final_step['oauth_token'] final_oauth_token_secret = final_step['oauth_token_secret'] # Here might wanna store them to DB to avoid user authentication at every run return (final_oauth_token, final_oauth_token_secret)
def create_auth_url(): twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET) auth = twitter.get_authentication_tokens(callback_url=CALLBACK_URL) session["oauth_token"] = auth["oauth_token"] session["oauth_secret"] = auth["oauth_token_secret"] redirect_url = auth["auth_url"] return redirect(redirect_url)
def get(self, request, *args, **kwargs): twitter = Twython(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET) auth = twitter.get_authentication_tokens('http://127.0.0.1:8000/twitter/callback') request.session['twitter_oauth_token'] = auth['oauth_token'] request.session['twitter_oauth_token_secret'] = auth['oauth_token_secret'] return HttpResponseRedirect(auth['auth_url'])
class Twitter: def __init__(self, app_key=TWITTER_APP_KEY, app_secret=TWITTER_APP_SECRET, oauth_token=None, oauth_token_secret=None): self.app_key = app_key self.app_secret = app_secret self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self.update_client() def update_client(self): self.client = Twython(self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret) def login(self): auth = self.client.get_authentication_tokens() self.oauth_token = auth['oauth_token'] self.oauth_token_secret = auth['oauth_token_secret'] return auth def confirm_login(self, oauth_verifier): self.update_client() login_res = self.client.get_authorized_tokens(oauth_verifier) self.oauth_token = login_res['oauth_token'] self.oauth_token_secret = login_res['oauth_token_secret'] self.update_client() return self.client.verify_credentials() def get_user_info(self): user_info = self.client.verify_credentials() return user_info
def twython_results(api_key: str, api_key_secret: str, query: dict) -> (pd.DataFrame): '''Accepts users credentials and approved query, executes a Twitter search for the query, and returns the results in a pd.DataFrame that is filtered for the designated features. ''' print('\n[*] Obtaining authorization...') twitter = Twython(api_key, api_key_secret) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] print('\n[*] Filtering results...') dict_ = {'user': [], 'date': [], 'text': [], 'favorite_count': []} for status in twitter.search(**query)['statuses']: dict_['user'].append(status['user']['screen_name']) dict_['date'].append(status['created_at']) dict_['text'].append(status['text']) dict_['favorite_count'].append(status['favorite_count']) results = pd.DataFrame(dict_) return results
def autentificar_usuario_twitter(request): ob_app=App.objects.get(provedor="Twitter") APP_KEY = ob_app.consumer_key APP_SECRET = ob_app.consumer_secret ob_cuenta_twitter=CuentaSocial.objects.get_or_none(user=request.user) twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens(callback_url='http://127.0.0.1:8000/api/oauth/callback_twitter') OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] if not ob_cuenta_twitter: new_cuenta_twitter = CuentaSocial(user=request.user,select=1,app=ob_app) new_cuenta_twitter.save() token_social = TokenSocial(cuenta=new_cuenta_twitter,token=OAUTH_TOKEN,token_secreto=OAUTH_TOKEN_SECRET) token_social.save() else : ob_token = TokenSocial.objects.get_or_none(cuenta=ob_cuenta_twitter) if ob_token : ob_token.token=OAUTH_TOKEN ob_token.token_secreto=OAUTH_TOKEN_SECRET ob_token.save() else: token_social = TokenSocial(cuenta=ob_cuenta_twitter,token=OAUTH_TOKEN,token_secreto=OAUTH_TOKEN_SECRET) token_social.save() return HttpResponseRedirect(auth['auth_url'])
def login(request): if request.GET.get('denied'): return redirect(request.GET.get('redir_to', '') or '/') if request.GET.get('oauth_verifier'): temp_token = request.session['oauth_token'] twitter_token = request.GET.get('oauth_token') if temp_token != twitter_token: return HttpResponseForbidden() oauth_verifier = request.GET['oauth_verifier'] twitter = Twython( settings.TWITTER_APP_KEY, settings.TWITTER_APP_SECRET, request.session['oauth_token'], request.session['oauth_token_secret'] ) final_auth = twitter.get_authorized_tokens(oauth_verifier) profile, new = TwitterProfile.objects.get_or_create( OAUTH_TOKEN=final_auth['oauth_token'], # final token OAUTH_TOKEN_SECRET=final_auth['oauth_token_secret'], # final token ) # if we updated the tokens, must refresh the instance try: profile.user except: profile = TwitterProfile.objects.get(OAUTH_TOKEN=final_auth['oauth_token']) profile.user.backend = 'django.contrib.auth.backends.ModelBackend' django_login(request, profile.user) if new and settings.__dict__['_wrapped'].__dict__.get( 'TWITTER_NEW_USER_URL', False ): return redirect( settings.TWITTER_NEW_USER_URL + "?redir_to=" + request.GET.get('redir_to', '') ) else: return redirect(request.GET.get('redir_to', '') or '/') twitter = Twython( settings.TWITTER_APP_KEY, settings.TWITTER_APP_SECRET, ) callback_url = ( settings.HOST + reverse('django_twitter_auth:login') + "?redir_to=" + request.META.get('HTTP_REFERER', '') ) auth = twitter.get_authentication_tokens( callback_url=callback_url ) request.session['oauth_token'] = auth['oauth_token'] request.session['oauth_token_secret'] = auth['oauth_token_secret'] return redirect(auth['auth_url'])
def get(self, request, *args, **kwargs): if not request.GET.get("oauth_token"): twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri( reverse('cms_login_twitter')) auth_props = twitter.get_authentication_tokens(callback_url) # Then send them over there, durh. request.session['request_token'] = auth_props return HttpResponseRedirect(auth_props['auth_url']) else: try: oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token'][ 'oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret) # Retrieve the tokens we want... authorized_tokens = twitter.get_authorized_tokens( request.GET['oauth_verifier']) twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, authorized_tokens['oauth_token'], authorized_tokens['oauth_token_secret']) user_data = twitter.verify_credentials() membro = None if Membro.objects.filter( twitter_id=authorized_tokens.get('user_id')).exists(): membro = Membro.objects.filter( twitter_id=authorized_tokens.get('user_id')).latest( 'pk') # Atualiza o Membro membro.twitter_oauth_token = authorized_tokens.get( 'oauth_token') membro.twitter_oauth_token_secret = authorized_tokens.get( 'oauth_token_secret') membro.save() elif Membro.objects.filter( nome=user_data.get('name')).exists(): membro = Membro.objects.filter( nome=user_data.get('name')).latest('pk') # Atualiza o Membro membro.twitter_id = authorized_tokens.get('user_id') membro.twitter_oauth_token = authorized_tokens.get( 'oauth_token') membro.twitter_oauth_token_secret = authorized_tokens.get( 'oauth_token_secret') membro.save() login_next(request, membro) except: messages.info(request, u'Erro na conexão com o Twitter.') return HttpResponseRedirect(reverse('cms_login'))
def begin_auth(request): twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) callback_url = request.build_absolute_uri(reverse('twython_django.views.thanks')) auth_props = twitter.get_authentication_tokens(callback_url) request.session['request_token'] = auth_props return HttpResponseRedirect(auth_props['auth_url'])
def twitter(request): twitter = Twython( KeySecretApp.app_key, KeySecretApp.app_secret ) auth_props = twitter.get_authentication_tokens( callback_url='http://tracktweet.herokuapp.com/done' ) oauth_token = auth_props['oauth_token'] oauth_token_secret = auth_props['oauth_token_secret'] return HttpResponseRedirect( auth_props['auth_url'] )
def login(): t = Twython(app_key=app_key, app_secret=app_secret, callback_url=callback_url) auth_props = t.get_authentication_tokens() session['request_token'] = (auth_props['oauth_token'], auth_props['oauth_token_secret']) return redirect(auth_props['auth_url'])
def twauth(request, redirect_url="/twaccess/"): twitter = Twython(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET) auth = twitter.get_authentication_tokens(callback_url='http://rhymingstat.us/twaccess/') OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] request.session['oauth_token'] = OAUTH_TOKEN request.session['oauth_token_secret'] = OAUTH_TOKEN_SECRET return HttpResponseRedirect(auth['auth_url'])
def __getAuthVerifier__(): twHandler = Twython(AuthApp.getAppKey(), AuthApp.getAppSecret()) twAuth = twHandler.get_authentication_tokens() sessionInfo = __SessionInfo__(twAuth['oauth_token'], twAuth['oauth_token_secret']) print('Please click the following URL to authorize this program:\n' + twAuth['auth_url']) oauthVerifier = input("Enter Verify Code:") sessionInfo.saveOauthVerifier(oauthVerifier) return sessionInfo
def get_followers_following(usr_id): index = 0 print "GETTING FOLLOWERS AND FOLLOWING: " + str(usr_id) friend_cursor = -1 follower_cursor = -1 APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] while (1==1): try: twitter = Twython (APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) friends = "" while (friend_cursor != 0): following = twitter.get_friends_ids(id = usr_id, cursor = friend_cursor) for ID in following['ids']: friends += str(ID) + " " friend_cursor = following["next_cursor"] friends = friends[:-1] if len(friends) == 0: friends = "null" follow = "" while (follower_cursor != 0): followers = twitter.get_followers_ids(id = usr_id,cursor= follower_cursor) for ID in followers['ids']: follow += str(ID) + " " follower_cursor = followers["next_cursor"] follow= follow[:-1] if len(follow) == 0: follow = "null" return (friends,follow) except Exception as e: print e if "429 (Too Many Requests)" in str(e): #global index index += 1 if index == len(APP_KEYS): index = 0 print "sleepy time - 15 minutes" print datetime.datetime.now() time.sleep(910) return get_followers_following(usr_id) elif "401 (Unauthorized)" in str(e): print "401 error" return ("null","null") elif "404 (Not Found)" in str(e): print "404 error" return ("null","null") else: print e return ("null","null")
def login(request): response = HttpResponse() context = {} context['not_logged_in'] = False context['user'] = '******' twitter = Twython(os.environ.get('consumer_key'), os.environ.get('consumer_secret')) auth_props = twitter.get_authentication_tokens(callback_url=request.build_absolute_uri(reverse('twitter_callback'))) request.session['request_token'] = auth_props return HttpResponseRedirect(auth_props['auth_url'])
def send_token(): global OAUTH_TOKEN global OAUTH_TOKEN_SECRET twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens(callback_url) OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] redirect_url= auth['auth_url'] return redirect(redirect_url)
def begin_auth(request): """ The view function that initiates the entire handshake. For the most part, this is 100% drag and drop. """ # Instantiate Twython with the first leg of our trip. APP_KEY = settings.TWITTER_KEY APP_SECRET = settings.TWITTER_SECRET twitter = Twython(APP_KEY, APP_SECRET) auth_props = twitter.get_authentication_tokens(callback_url=request.build_absolute_uri(reverse('twython_django_oauth.views.thanks'))) # Request an authorization url to send the user to... auth_props = twitter.get_authentication_tokens() # Then send them over there, durh. request.session['request_token'] = auth_props return HttpResponseRedirect(auth_props['auth_url'])
def get_info(): with open('tweet_dict') as file: twitterdata=json.load(file) index=0 num_checked = 0 rate_ex = 0 for tweet in twitterdata: if index >= 3: "Exceeded all app rate limits" break tweet_id = tweet['Tweet_ID'] APP_KEY = APP_KEYS[index] APP_SECRET = APP_SECRETS[index] OAUTH_TOKEN = OAUTH_TOKENS[index] OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index] if (tweet['Usr_Screename']== None or tweet['Usr_Description']== None): try: twitter = Twython (APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) result = twitter.show_status(id=tweet_id) print result['user']['screen_name'] + " " + result['user']['description'] tweet['Usr_Screename'] = result['user']['screen_name'] tweet['Usr_Description'] = result['user']['description'] num_checked += 1 except Exception as e: if "429 (Too Many Requests)" in str(e): index += 1 elif "404 (Not Found)" in str(e): print "404" tweet['Usr_Screename'] = "" tweet['Usr_Description'] = "" print "403" elif "403 (Forbidden)" in str(e): tweet['Usr_Screename'] = "" tweet['Usr_Description'] = "" else: print e rate_ex += 1 if (num_checked == 0 and rate_ex ==0): with open("tweet_dict_fully_checked",'w') as fout: json.dump(twitterdata,fout) else: with open('tweet_dict','w') as fout: json.dump(twitterdata,fout) time.sleep(900) get_info()
def statistics_authentication_twitterv01_oauth(request): controller = TwitterV01AuthenticationController.GetOrCreate() template_data = {'errors': [], 'controller': controller} app_key = [e for e in controller.config['elements'] if e['name'] == 'app_key'][0]['value'] app_secret = [e for e in controller.config['elements'] if e['name'] == 'app_secret'][0]['value'] # auth = tweepy.OAuthHandler(str(app_key), str(app_secret)) if 'pin' in request.POST: token = request.session.get('request_token', '') auth = Twython(app_key, app_secret, token[0], token[1]) # auth.set_request_token(token[0], token[1]) try: # auth.get_access_token(request.POST.get('pin')) auth_tokens = auth.get_authorized_tokens(request.POST.get('pin')) for element in controller.config['elements']: if element['name'] == 'oauth_token': # element['value'] = auth.access_token.key element['value'] = auth_tokens.get('oauth_token') if element['name'] == 'oauth_secret': # element['value'] = auth.access_token.secret element['value'] = auth_tokens.get('oauth_token_secret') controller.save() request.session.pop('request_token', '') return_data = { 'template': render_to_string( 'django_odc/modals/configure_twitterv01_authentication/twitterv01_authentication_confirm.html'), 'status': 'ok'} return HttpResponse(json.dumps(return_data), content_type='application/json') except Exception: template_data['errors'].append( 'There was an error using the PIN you supplied, please try authorising again.') else: auth = Twython(app_key, app_secret) try: # redirect_url = auth.get_authorization_url() auth_props = auth.get_authentication_tokens() # request.session['request_token'] = (auth.request_token.key, auth.request_token.secret) request.session['request_token'] = (auth_props.get('oauth_token'), auth_props.get('oauth_token_secret')) template_data['redirect_url'] = auth_props.get('auth_url') # except tweepy.TweepError: except Exception: template_data['errors'].append( 'There was a problem with the details you supplied, it could be that twitter is down but please ' 'check the application key and secret and try again.') return_data = { 'status': 'error', 'template': render_to_string( 'django_odc/modals/configure_twitterv01_authentication/twitterv01_authentication_config.html', template_data, context_instance=RequestContext(request))} return HttpResponse(json.dumps(return_data), content_type='application/json') template = render_to_string( 'django_odc/modals/configure_twitterv01_authentication/twitterv01_authentication_oauth.html', template_data, context_instance=RequestContext(request)) return_data = {'status': 'ok' if not template_data['errors'] else 'error', 'template': template} return HttpResponse(json.dumps(return_data), content_type='application/json')