class SanchanOAuthHandler(): def __init__(self, config): self.config = config self.keys = self.config.OAuthKeys() self.oauth = OAuthHandler(self.keys['consumer_key'], self.keys['consumer_secret'], secure = True ) self.oauth.set_access_token(self.keys['access_token_key'], self.keys['access_token_secret']) def authenticate(self): return self.oauth def request(self): print "Authorize this app via this URL: " print self.oauth.get_authorization_url() pincode = raw_input('Then, input the proposed PIN: ') try: self.oauth.get_access_token(verifier=pincode) except error.TweepError, e: print e print "[EMERG] Authentication error!" sys.exit(1) print "Put these access keys into your config.yml:" print "access_token: " + self.oauth.access_token.key print "access_token_secret: " + self.oauth.access_token.secret sys.exit(0)
def start_api(): """-------------------------------------------------------------------------- Takes your individual developer tokens to connect to the Twitter API. :return: a successfully-initialized connection to Twitter --------------------------------------------------------------------------""" # Keys and tokens are unique access codes that vary for each person accessing Twitter's API. # You have to sign up for a developer account to get these - developer.twitter.com # (It's easy and free) api_key = '' api_secret_key = '' access_token = '' access_token_secret = '' auth = OAuthHandler(api_key, api_secret_key) # This is where you hack the mainframe auth.set_access_token(access_token, access_token_secret) try: auth.get_authorization_url() print("You're in! API connected.") except TweepError: print("You're not in! API did not connect.") # Twitter limits the amount of tweets you can download at once, so Tweepy will wait it out. return API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
class TestTweepyAuthentication(TestCase): def setUp(self): self.auth = OAuthHandler(apikeys.TWITTER_CONSUMER_KEY, apikeys.TWITTER_CONSUMER_SECRET) self.auth.set_access_token(apikeys.TWITTER_ACCESS_TOKEN, apikeys.TWITTER_ACCESS_KEY) self.invalid_auth = OAuthHandler("WRONG_CONSUMER_KEY", "WRONG_CONSUMER_SECRET") self.invalid_auth.set_access_token("WRONG_ACCESS_TOKEN", "WRONG_ACCESS_KEY") self.blank_auth = OAuthHandler("", "") self.blank_auth.set_access_token("", "") def test_tweepy_api_authentication_with_valid_fields(self): """ When valid set of authentication keys are passed, it gets back Tests the tweepy api for valid set of API key. """ self.assertIsNotNone(self.auth.get_authorization_url()) def test_tweepy_api_authentication_with_invalid_fields(self): """ Tests the tweepy api for invalid set of API key. """ with self.assertRaises(tweepy.TweepError): self.invalid_auth.get_authorization_url() def test_tweepy_api_authentication_with_blank_fields(self): """ Tests the tweepy api for set of blank fields. """ with self.assertRaises(tweepy.TweepError): self.blank_auth.get_authorization_url() def test_tweepy_api__with_valid_phrase(self): """ Tests the tweepy api with valid phrase. """ api = tweepy.API(self.auth) self.assertIsNotNone(api.search(q="word")) def test_tweepy_api_with_empty_string(self): """ Tweepy should give TweepError when query is an empty string. """ api = tweepy.API(self.auth) with self.assertRaises(tweepy.TweepError): api.search(q="") def test_tweepy_api_with_valid_phrase_but_invalid_authentication(self): """ Tweepy should give TweepError when given invalid set of API keys. """ api = tweepy.API(self.invalid_auth) with self.assertRaises(tweepy.TweepError): api.search(q="word")
def twitter_login(request): """ ログインを行う。 :param request: リクエストオブジェクト :type request: django.http.HttpRequest :return: 遷移先を示すレスポンスオブジェクト :rtype: django.http.HttpResponse """ # 認証URLを取得する oauth_handler = OAuthHandler( settings.CONSUMER_KEY, settings.CONSUMER_SECRET, request.build_absolute_uri(reverse(twitter_callback)) ) authorization_url = oauth_handler.get_authorization_url() # リクエストトークンをセッションに保存する request.session['request_token'] = oauth_handler.request_token # ログイン完了後のリダイレクト先URLをセッションに保存する if 'next' in request.GET: request.session['next'] = request.GET['next'] # 認証URLにリダイレクトする return HttpResponseRedirect(authorization_url)
def __oauth_login(self, next): '''This method redirects the user to the authenticating form on authentication server if the authentication code and the authentication token are not available to the application yet. Once the authentication code has been received this method is called to set the access token into the session by calling accessToken() ''' if not self.accessToken(): # setup the client auth = OAuthHandler( self.client_id , self.client_secret , callback=self.__redirect_uri(next) ) redirect_url = None try: redirect_url = auth.get_authorization_url() self.session.request_token = auth.request_token except tweepy.TweepError: print 'Error! Failed to get request token.' if redirect_url: HTTP = self.globals['HTTP'] raise HTTP(307, "You are not authenticated: you are being redirected to the <a href='" + redirect_url + "'> authentication server</a>", Location=redirect_url) return None
def _get_twitter_access(self, username): auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) url = auth.get_authorization_url() print 'Go here: %s and enter the corresponding PIN' % url pin = raw_input('PIN:') auth.get_access_token(pin) return (auth.access_token.key, auth.access_token.secret)
def report(request): twitter_auth = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET) authorization_url = twitter_auth.get_authorization_url() request.session['request_token'] = twitter_auth.request_token[ 'oauth_token'] if request.method == 'POST': form = ReportForm(request.POST) if form.is_valid(): block_option = form.cleaned_data['block_option'] in_value = escape(form.cleaned_data['twitter_accounts']) if len(in_value) > 3000 or in_value.count('\n') > 55: return render(request, "index.html", { "form": form, "info": "Input too long" }) request.session['form_value'] = in_value request.session['block_option'] = block_option else: return render(request, "index.html", { "form": form, "info": "Form is not valid" }) return redirect(authorization_url)
def run(): print 'Input your application info.' consumer_key = raw_input('Consumer Key: ') consumer_secret = raw_input('Consumer Secret: ') auth = OAuthHandler(consumer_key, consumer_secret) print "Visit the following url and allow TweetHandler to access." print '>>> %s' % auth.get_authorization_url() print '' vcode = raw_input('Enter verification code: ') token = auth.get_access_token(vcode) print 'OK. You can setup TweetHander with following code.' print """ ---- from tweethandler import TweetHandler import logging th = TweetHandler('%s', '%s', '%s', '%s') logger = logging.getLogger() logger.setLevel(logging.DEBUG) th.setLevel(logging.DEBUG) logger.addHandler(th) logger.info('Your log message') """ % (consumer_key, consumer_secret, token.key, token.secret)
def authorize(consumer_token, consumer_secret): auth = OAuthHandler(consumer_token, consumer_secret) try: redirect_url = auth.get_authorization_url() print 'URL: %s' % redirect_url except TweepError: print 'Error! Failed to get request token.' return auth
def testaccesstype(self): if not consumer_key or not consumer_secret: self.skipTest("Missing consumer key and/or secret") auth = OAuthHandler(consumer_key, consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
def login(): auth = OAuthHandler(app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET'], url_for('authorized', _external=True)) try: redirect_url = auth.get_authorization_url() session['twitter_oauth']= [auth.request_token.key, auth.request_token.secret] return redirect(redirect_url) except TweepError: print "Fail lol" return 'Something went wrong, panic!'
class Twit(object): def __init__(self,consumer_token, access_token=None): if not isinstance(consumer_token, Token): raise Exception("consumer_token is invalid type!") self.auth = OAuthHandler(consumer_token.key, consumer_token.secret) self.api = None if access_token != None and isinstance(access_token, Token): # ok self.auth.set_access_token(access_token.key, access_token.secret) self.api = self._get_api(self.auth) def _get_api(self, auth): return API(auth,retry_count=3,cache=tweepy.MemoryCache(timeout=60)) def get_auth_url(self): return self.auth.get_authorization_url() def get_access_token(self, pin): self.auth.get_access_token(pin) self.api = self._get_api(self.auth) return Token(self.auth.access_token.key, self.auth.access_token.secret) @classmethod def get_msg_length(cls, msg): """ https://dev.twitter.com/docs/api/1.1/get/help/configuration """ msg = re.sub(RegexHttpUrl, "0123456789012345678901", msg) msg = re.sub(RegexHttpsUrl, "01234567890123456789012", msg) return len(msg) @classmethod def validate_msg(cls, msg): """ Args: msg: str, 投稿するメッセージ Return: (is_valid:bool, reminder:int) """ max_msg_length = 140 is_valid = False msg_length = cls.get_msg_length(msg) reminder = 140 - msg_length if 0 < msg_length <= max_msg_length: is_valid = True return (is_valid, reminder) def post(self, msg): return self.api.update_status(status=msg) def verify_credentials(self, include_entities=True, skip_status=False): return self.api.verify_credentials(include_entities=include_entities, skip_status=skip_status) def get_user_timeline(self, screen_name, count=50): return self.api.user_timeline(screen_name=screen_name, count=count) def destroy_status(self, status_id): return self.api.destroy_status(id=status_id)
def oauth(): twitter = OAuthHandler(application.config['TWITTER_KEY'], application.config['TWITTER_SECRET']) try: url = twitter.get_authorization_url() session['request_token'] = twitter.request_token except: print('Request token error') url = url_for('index') return redirect(url)
class WTweetUser: def __init__(self): _CONSUMER_KEY = '9o4scrLHTFt7NzyVxD5Q' _CONSUMER_SECRET = 'xlrPmai1QgNTRQTf86inp1bzEFLgEXD7XuN5ZENKAU' self.__auth_handler = OAuthHandler(_CONSUMER_KEY, _CONSUMER_SECRET) self.__access_token = None def set_access_token(self, access_token): self.__access_token = self.__auth_handler.set_access_token(key=access_token['key'], secret=access_token['secret']) def get_auth_handler(self): return self.__auth_handler def logout(self): with loadfile('w') as f: f.truncate() f.close() print 'logout successful!' def login(self): try: auth_url = self.__auth_handler.get_authorization_url() print 'give me a pin code from url: {0}'.format(auth_url) verifier = raw_input('enter a pin code: ').strip() self.__auth_handler.get_access_token(verifier=verifier) access_token = { 'key': self.__auth_handler.access_token.key, 'secret': self.__auth_handler.access_token.secret } with loadfile('w+') as f: f.truncate() f.write(JSONEncoder().encode(access_token)) f.close() except TweepError as err: print err.__str__() return WTweetTimeline(self) def is_login(self): with loadfile('r') as f: cfg = f.readline() f.close() access_token = JSONDecoder().decode(cfg) if 'key' in access_token and 'secret' in access_token: self.set_access_token(access_token=access_token) return True else: return False def get_timeline(self): with loadfile('r') as f: cfg = f.readline() f.close() self.set_access_token(JSONDecoder().decode(cfg)) return WTweetTimeline(self)
def twitter_oauth_request(request): callback = reverse('twitter_oauth_verify') callback = request.build_absolute_uri(callback) handler = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, callback) redirect_url = handler.get_authorization_url(signin_with_twitter=True) request.session['request_token_key'] = handler.request_token.key request.session['request_token_secret'] = handler.request_token.secret return redirect(redirect_url)
def start_api( self, key_dict ): # must be provided by user - freely available @ developer.twitter.com consumer_key = key_dict['cons'] consumer_secret_key = key_dict['cons_sec'] access_token = key_dict['acc'] access_token_secret = key_dict['acc_sec'] auth = OAuthHandler(consumer_key, consumer_secret_key) auth.set_access_token(access_token, access_token_secret) try: auth.get_authorization_url() print("API connected.") except TweepError: print("ERROR: API did not connect") quit() return API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
def twitauth(): auth=OAuthHandler(consumer_token,consumer_secret,"http://127.0.0.1:8000/high_on_twitter/default/callback") auth_url=auth.get_authorization_url() print "auth_url",auth_url aa={} aa['key']=auth.request_token.key aa['secret']=auth.request_token.secret session.request_token=aa print "request-token,key,secret twitauth",auth.request_token.key,auth.request_token.secret #session.set('request_token', (auth.request_token.key,auth.request_token.secret)) redirect(auth_url) '''print auth_url
def auth(request): consumer_key = tweeter_credentials.CONSUMER_KEY consumer_secret = tweeter_credentials.CONSUMER_SECRET # start the OAuth process, set up a handler with our details oauth = OAuthHandler(consumer_key, consumer_secret) # direct the user to the authentication url # if user is logged-in and authorized then transparently goto the callback URL auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) # store the request token request.session['request_token'] = oauth.request_token return response
def auth(request): """ Perform authentication with Twitter """ # start the OAuth process, set up a handler with our details oauth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) # direct the user to the authentication url auth_url = oauth.get_authorization_url() response = HttpResponseRedirect(auth_url) # store the request token request.session['unauthed_token_twitterexp'] = (oauth.request_token.key, oauth.request_token.secret) return response
def testoauth(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = raw_input('PIN: ').strip() self.assert_(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assert_(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status('test %i' % random.randint(0, 1000)) api.destroy_status(s.id)
def testoauth(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = raw_input('PIN: ').strip() self.assert_(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assert_(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status('test %i' % random.randint(0, 1000)) api.destroy_status(s.id)
def get_auth_link_and_show_token(): auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.secure = True auth_url = auth.get_authorization_url() input( "Log in to https://twitter.com as the user you want to tweet as and hit enter." ) input("Visit %s in your browser and hit enter." % auth_url) pin = input("What is your PIN: ") token = auth.get_access_token(verifier=pin) print( "\nThese are your access token and secret.\nDO NOT SHARE THEM WITH ANYONE!\n" ) print("ACCESS_TOKEN\n%s\n" % token[0]) print("ACCESS_TOKEN_SECRET\n%s\n" % token[1])
def setup(): '''This function gives you all the keys for the Twitter-API. Look in the text below to costume it with your app. Or only run it to get all keys for the socialpy gateway. The app-token are from my test app. I'm not shore if it's a god idea to let them now you. But so you can easily run this scrip and have all the keys you need for my gateway.''' # create your SocialPy folder if it not exists check(create=True) # Go to https://dev.twitter.com and sign up for a developer account. Then # create an app. This app shouldn’t have a callback url. Look in your app # for the tokens and use them for the OAuthHandler consumer_token = 'kYdbvAGXIhWGHyNKdNTssfpzE' consumer_secret = 'MM2EVucINNxfFEB0akTenqConUnucj9FaS4hMX1F7wEw5WDvD1' auth = OAuthHandler(consumer_token, consumer_secret) # This will open your web browser and ask you to verify for the app. If you # agree, they show you a pin. If your app has a callback url, they would # redirect you to this url and didn't show you the pin. try: redirect_url = webbrowser.open(auth.get_authorization_url()) time.sleep(1) except TweepError: print('Error! Failed to get request token.') exit() pin = input('\nVerification pin number from twitter.com: ').strip() token = auth.get_access_token(verifier=pin) print('All the token:') print('ckey:', consumer_token) print('csecret:', consumer_secret) print('akey:', auth.access_token) print('asecret:', auth.access_token_secret) # create the Gateway and save the keys gateway = Gateway(keyfile=SOCIALPY_KEY_FILE) gateway['twitter'].setup(ckey=consumer_token, csecret=consumer_secret, akey=auth.access_token, asecret=auth.access_token_secret) gateway.save_to_file(SOCIALPY_KEY_FILE) print('save the keys in your SocialPy file')
def testoauth(self): if not consumer_key or not consumer_secret: self.skipTest("Missing consumer key and/or secret") auth = OAuthHandler(consumer_key, consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status(f'test {random.randint(0, 1000)}') api.destroy_status(s.id)
def get_auth(): auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) if not os.path.exists(CREDENTIALS_FILE): authorization_url = auth.get_authorization_url() webbrowser.open_new(authorization_url) pin = input('PIN: ') auth.get_access_token(pin) cred = { 'ACCESS_TOKEN': auth.access_token, 'ACCESS_SECRET': auth.access_token_secret } fp = open(CREDENTIALS_FILE, 'wb') pickle.dump(cred, fp) fp.close() else: fp = open(CREDENTIALS_FILE, 'rb') cred = pickle.load(fp) fp.close() auth.set_access_token(cred['ACCESS_TOKEN'], cred['ACCESS_SECRET']) return auth
def get_token(): # Get authorization information from secure file with open("etc/auth/auth.txt", "r") as authFile: consumerKey = authFile.readline().strip() consumerSecret = authFile.readline().strip() # Authenticate the twitter consumer key twitter_auth = OAuthHandler(consumerKey, consumerSecret) twitter_auth.secure = True authUrl = twitter_auth.get_authorization_url() # go to this URL to authorize print("PLase visit this link and authorize the app ==> " + authUrl) print ("Enter the Authorization PIN") # Write the access tokens to file pin = input().strip() # strip the new line character from pressing 'enter' token = twitter_auth.get_access_token(verifier=pin) with open("etc/auth/tokens.txt", "w") as accessTokenFile: accessTokenFile.write(token[0]+'\n') # '\n' indicates a newline char accessTokenFile.write(token[1]+'\n') return
def doOAuthDance(consumer_key, consumer_secret): # If we already have an access token saved, just use that if os.path.exists(ACCESS_TOKEN_PATH): accessFile = open(ACCESS_TOKEN_PATH, 'r') access_token_key = accessFile.readline().strip() access_token_secret = accessFile.readline().strip() accessFile.close() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token_key, access_token_secret) return auth auth = OAuthHandler(consumer_key, consumer_secret) try: redirect_url = auth.get_authorization_url() except TweepError: print ('Error! Failed to get request token.') return None print(('Get PIN from: %s' % (redirect_url))) webbrowser.open(redirect_url) verifier = input('Input Twitter verifier PIN:') try: auth.get_access_token(verifier) except: print ('Error! Failed to get access token.') return None # Save the access token for later use accessFile = open(ACCESS_TOKEN_PATH, 'wt') accessFile.write('%s\n%s' % (auth.access_token.key, auth.access_token.secret)) accessFile.close() return auth
import tweepy from tweepy import OAuthHandler from twitter_codes import consumer_secret, consumer_key, access_secret, access_token import pandas as pd from tqdm import tqdm auth = OAuthHandler(consumer_secret, consumer_key) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) try: redirect_url = auth.get_authorization_url(signin_with_twitter=True) except tweepy.TweepError: print('Error! Failed to get request token.') rest_names = ['@McDonalds', '@sonicdrivein', '@wingstop', '@Starbucks', '@shakeshack', '@redrobinburgers', '@Potbelly', '@dominos', '@DennysDiner', '@CrackerBarrel', '@ChipotleTweets', '@Wendys', '@dunkindonuts']
them now you. But so you can easily run this scrip and have all the keys you need for my gateway. ''' from tweepy import OAuthHandler, API, TweepError import webbrowser # Go to https://dev.twitter.com and sign up for a developer account. Then create # an app. This app shouldn’t have a callback url. Look in your app for the # tokens and use them for the OAuthHandler consumer_token = 'kYdbvAGXIhWGHyNKdNTssfpzE' consumer_secret = 'MM2EVucINNxfFEB0akTenqConUnucj9FaS4hMX1F7wEw5WDvD1' auth = OAuthHandler(consumer_token, consumer_secret) # This will open your web browser and ask you to verify for the app. If you # agree, they show you a pin. If your app has a callback url, they would # redirect you to this url and didn't show you the pin. try: redirect_url = webbrowser.open(auth.get_authorization_url()) except TweepError: print('Error! Failed to get request token.') exit() pin = input('Verification pin number from twitter.com: ').strip() token = auth.get_access_token(verifier=pin) print('All the token:') print('ckey:', consumer_token) print('csecret:', consumer_secret) print('akey:', auth.access_token) print('asecret:', auth.access_token_secret)
def testaccesstype(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = raw_input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
from tweepy import OAuthHandler from tweepy import TweepError from config import get_config from log_handler import get_logger logger = get_logger(__name__) CONSUMER_KEY = get_config().consumer_key CONSUMER_SECRET = get_config().consumer_secret auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) try: redirect_url = auth.get_authorization_url() print(f"Go here, get the code => {redirect_url}") verification_code = input("Verification Code: ") auth.request_token.update({"oauth_token_secret": verification_code}) auth.get_access_token(verification_code) print("---") print(f"Access Token => {auth.access_token}") print(f"Secret Token => {auth.access_token_secret}") print("---") except TweepError as e: print("Unable to continue...") logger.error(e)
from tweepy import OAuthHandler CONSUMER_KEY = 'place key here' CONSUMER_SECRET = 'place secret here' auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() auth.get_access_token(verifier) print("ACCESS_KEY = '%s'" % auth.access_token.key) print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
def testaccesstype(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = raw_input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
import tweepy import json from tweepy import AppAuthHandler from tweepy import OAuthHandler with open("private/oauth-config.json", "r") as config: oauth_config = (json.loads(config.read())) consumer_key = oauth_config.get('consumer-key') consumer_secret = oauth_config.get('consumer-secret') oauth = OAuthHandler(consumer_key, consumer_secret) try: redirect_url = oauth.get_authorization_url() except tweepy.TweepError: print('Error: failed to get the redirect URL.') access_token = oauth.get_access_token(verifier='enter pin here')