def __init__(self, bot): config = ConfigParser.RawConfigParser() config.read(os.path.dirname(__file__) + os.sep + bot + os.sep + "omni.cfg") consumer_key = config.get(bot, 'consumer_key') consumer_secret = config.get(bot, 'consumer_secret') oauth = config.get(bot, 'oauth') oauth_filename = os.path.dirname(__file__) + os.sep + bot + os.sep + oauth oauth_token, oauth_token_secret = read_token_file(oauth_filename) self.handle = config.get(bot, 'handle') self.corpus = os.path.dirname(__file__) + os.sep + bot + os.sep + config.get(bot, 'corpus') self.method = config.get(bot, 'tweet_method') self.twitter = Twitter(domain='search.twitter.com') self.twitter.uriparts = () self.poster = Twitter( auth=OAuth( oauth_token, oauth_token_secret, consumer_key, consumer_secret ), secure=True, api_version='1.1', domain='api.twitter.com')
def oauth_helper(request): oauth_verifier = request.GET.get('oauth_verifier') # Pick back up credentials from ipynb_oauth_dance oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE) _twitter = twitter.Twitter( auth=twitter.OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), format='', api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens( _twitter.oauth.access_token(oauth_verifier=oauth_verifier, oauth_token=oauth_token, oauth_consumer_key=CONSUMER_KEY)) # Save tokens to TwitterUser model tuser, created = TwitterUser.objects.get_or_create( OAUTH_TOKEN = oauth_token, OAUTH_TOKEN_SECRET = oauth_token_secret ) django_login(request, tuser.user) return HttpResponseRedirect(request.build_absolute_uri(REDIRECT_URL_AFTER_AUTH))
def oauth_helper(): oauth_verifier = request.args.get('oauth_verifier') # Pick back up credentials from ipynb_oauth_dance oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE) _twitter = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), format='', api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens( _twitter.oauth.access_token(oauth_verifier=oauth_verifier)) # This web server only needs to service one request, so shut it down shutdown_after_request = request.environ.get('werkzeug.server.shutdown') shutdown_after_request() # Write out the final credentials that can be picked up after the blocking # call to webserver.run() below. write_token_file(OAUTH_FILE, oauth_token, oauth_token_secret) return "%s %s written to %s" % (oauth_token, oauth_token_secret, OAUTH_FILE)
def login(): config = ConfigParser.ConfigParser() config.readfp(open("twitter.config","rb")) # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = config.get('account', 'appname') CONSUMER_KEY = config.get('account', 'consumerkey') CONSUMER_SECRET = config.get('account', 'consumersecret') ACCESS_TOKEN = config.get('account', 'accesstoken') ACCESS_TOKEN_SECRET = config.get('account', 'accesstokensecret') TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: if ACCESS_TOKEN != None and ACCESS_TOKEN_SECRET != None: oauth_token = ACCESS_TOKEN oauth_token_secret = ACCESS_TOKEN_SECRET else: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def get_twitter(debug=False): # This is secret and key of my app "ibread" # this is set up on twitter.com CONSUMER_KEY = "NXdiUFv7ZqhO5Ojr8GocA" CONSUMER_SECRET = "CMRgb7BHpHLlcZ0NqHF06pWbFtv1zPqV98KTaFxV2YQ" #oauth_filename = os.environ.get('HOME', '') + os.sep + '.my_twitter_oauth' oauth_filename = sys.path[0] + os.sep + 'my_twitter_oauth' if debug: print oauth_filename # if did not found the auth file, create one if not os.path.exists(oauth_filename): oauth_dance("ibread", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) if debug: print oauth_token, oauth_token_secret tw = Twitter( auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1', domain='api.twitter.com') return tw
def login_and_get_twitter(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token CREDENTIALS_FILE = './twitter_credentials.txt' TOKEN_FILE = './twitter_token.oauth' # in the current directory # try: (app_name, consumer_key, consumer_secret) = read_credentials_file(CREDENTIALS_FILE) # except IOError: # print(TOKEN_FILE + " not found") try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) logging.info('read token from file success') except IOError as e: logging.info('read token from file failed, requesting new token') (oauth_token, oauth_token_secret) = oauth_dance(app_name, consumer_key, consumer_secret) write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret) return twitter.Twitter(domain='api.twitter.com', api_version='1.1', auth=twitter.oauth.OAuth(oauth_token, oauth_token_secret, consumer_key, consumer_secret))
def from_oauth_file(cls, filepath=None): """Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser window to authenticate you. Once successfully run, even just one time, you will have a credential file at ~/.twitter_oauth. This factory function reuses your credential file to get a `Twitter` object. (Really, this code is just lifted from the `twitter.cmdline` module to minimize OAuth dancing.) """ if filepath is None: # Use default OAuth filepath from `twitter` command-line program. home = os.environ.get('HOME', os.environ.get('USERPROFILE', '')) filepath = os.path.join(home, '.twitter_oauth') oauth_token, oauth_token_secret = read_token_file(filepath) twitter = cls( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version='1.1', domain='api.twitter.com') return twitter
def oauth_url_dance(consumer_key, consumer_secret, callback_url, oauth_verifier, pre_verify_token_filename, verified_token_filename): # Verification happens in two stages... # 1) If we haven't done a pre-verification yet... Then we get credentials from Twitter # that will be used to sign our redirect to them, find the redirect, and instruct the Javascript # that called us to do the redirect. if not os.path.exists(CREDS_PRE_VERIFIY): twitter = Twitter(auth=OAuth('', '', consumer_key, consumer_secret), format='', api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens( twitter.oauth.request_token(oauth_callback=callback_url)) write_token_file(pre_verify_token_filename, oauth_token, oauth_token_secret) oauth_url = 'https://api.twitter.com/oauth/authorize?' + urllib.urlencode( {'oauth_token': oauth_token}) return oauth_url # 2) We've done pre-verification, hopefully the user has authed us in Twitter # and we've been redirected to. Check we are and ask for the permanent tokens. oauth_token, oauth_token_secret = read_token_file(CREDS_PRE_VERIFIY) twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, consumer_key, consumer_secret), format='', api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens( twitter.oauth.access_token(oauth_verifier=oauth_verifier)) write_token_file(verified_token_filename, oauth_token, oauth_token_secret) return oauth_token, oauth_token_secret
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = '' CONSUMER_KEY = '2JRLM23QHyLyBABuqg4tqQ' CONSUMER_SECRET = 'avpoP356DDKbHtTRiicjKBC01yXqfaI8QCgfZebmjA' TOKEN_FILE = 'auth/twitter.oauth' ''' consumer_key = '2JRLM23QHyLyBABuqg4tqQ' consumer_secret = 'avpoP356DDKbHtTRiicjKBC01yXqfaI8QCgfZebmjA' access_token = '20692466-4kkQfaO8V0e2cVBDzfYg4EkFdQO9u0CNZLoP8Xma5' access_token_secret = '0bUGan28R0Dt2f0NIIjA2AcCkNUelANx674aWUH9Oj08f' ''' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('auth'): os.mkdir('auth') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def __init__(self, connection): self.logger = logging.getLogger(self.__name) self.dbconnection = connection.dbconnection self.output_channel = "#%s" % connection.config.get( "lowflyingrocks", "channel") # OAUTH_FILENAME = os.environ.get( # 'HOME', # '') + os.sep + '.lampstand_oauth' OAUTH_FILENAME = connection.config.get("twitter", "oauth_cache") CONSUMER_KEY = connection.config.get("twitter", "consumer_key") CONSUMER_SECRET = connection.config.get("twitter", "consumer_secret") try: if not os.path.exists(OAUTH_FILENAME): oauth_dance( "Lampstand", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME) self.oauth_token, self.oauth_token_secret = read_token_file( OAUTH_FILENAME) self.twitter = Twitter( auth=OAuth( self.oauth_token, self.oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, domain='api.twitter.com') except: self.twitter = False
def get_twitter_tools(oauthfile): #--- register oauth tokens ------------------------------------------- try: oauth_token, oauth_token_secret = read_token_file(oauthfile) except IOError: print 'OAuth file {} not found'.format(oauthfile) response = raw_input( 'Do you want to initiate a new oauth dance (y or n)? ') if not (len(response) > 0 and response[0].upper() == 'Y'): oauth_token = oauth_token_secret = '' else: oauth_token, oauth_token_secret = oauth_dance( 'Brilliant App', CONSUMER_KEY, CONSUMER_SECRET, token_filename=oauthfile) #--- t1 = Twitter Search API, t2 = Twitter REST API ------------------ t1 = Twitter(domain='search.twitter.com') t2 = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1', domain='api.twitter.com') return t1, t2
def localinit(self): OAUTH_FILENAME = self.connection.config.get("twitter", "oauth_cache") CONSUMER_KEY = self.connection.config.get("twitter", "consumer_key") CONSUMER_SECRET = self.connection.config.get( "twitter", "consumer_secret") try: if not os.path.exists(OAUTH_FILENAME): oauth_dance( "Lampstand", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME) self.oauth_token, self.oauth_token_secret = read_token_file( OAUTH_FILENAME) self.twitter = Twitter( auth=OAuth( self.oauth_token, self.oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, domain='api.twitter.com') except: pass
def oauth_url_dance( consumer_key, consumer_secret, callback_url, oauth_verifier, pre_verify_token_filename, verified_token_filename ): # Verification happens in two stages... # 1) If we haven't done a pre-verification yet... Then we get credentials # from Twitter that will be used to sign our redirect to them, find the # redirect, and instruct the Javascript that called us to do the redirect. if not os.path.exists(CREDS_PRE_VERIFIY): twitter = Twitter(auth=OAuth("", "", consumer_key, consumer_secret), format="", api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens(twitter.oauth.request_token(oauth_callback=callback_url)) write_token_file(pre_verify_token_filename, oauth_token, oauth_token_secret) oauth_url = "https://api.twitter.com/oauth/authorize?" + urllib.urlencode({"oauth_token": oauth_token}) return oauth_url # 2) We've done pre-verification, hopefully the user has authed us in # Twitter and we've been redirected to. Check we are and ask for the # permanent tokens. oauth_token, oauth_token_secret = read_token_file(CREDS_PRE_VERIFIY) twitter = Twitter( auth=OAuth(oauth_token, oauth_token_secret, consumer_key, consumer_secret), format="", api_version=None ) oauth_token, oauth_token_secret = parse_oauth_tokens(twitter.oauth.access_token(oauth_verifier=oauth_verifier)) write_token_file(verified_token_filename, oauth_token, oauth_token_secret) return oauth_token, oauth_token_secret
def from_oauth_file(cls, filepath=None): """Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser window to authenticate you. Once successfully run, even just one time, you will have a credential file at ~/.twitter_oauth. This factory function reuses your credential file to get a `Twitter` object. (Really, this code is just lifted from the `twitter.cmdline` module to minimize OAuth dancing.) """ if filepath is None: # Use default OAuth filepath from `twitter` command-line program. home = os.environ.get("HOME", os.environ.get("USERPROFILE", "")) filepath = os.path.join(home, ".twitter_oauth") oauth_token, oauth_token_secret = read_token_file(filepath) twitter = cls( auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version="1.1", domain="api.twitter.com", ) return twitter
def oauth_login_ecig( app_name=APP_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token_file="out/twitter.ecig.oauth" ): try: (access_token, access_token_secret) = read_token_file(token_file) except IOError, e: print >>sys.stderr, "Cannot get tokens"
def oauthToken(oauth_filename=os.sep.join( [os.getenv('HOME'), ".twitter_oauth"])): if (not os.path.exists(oauth_filename)): oauth_dance("the Command-Line Tool", CLIENT_KEY, CLIENT_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) return twitter.OAuth(oauth_token, oauth_token_secret, CLIENT_KEY, CLIENT_SECRET)
def main(): oauth_filename = os.environ.get('HOME', '') + os.sep + '.twitter_oauth' oauth_filename = os.path.expanduser(oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET) twitter = Twitter( auth=auth, secure=True, api_version='1', domain='api.twitter.com' ) try: tweets = pickle.load(open('tweets.pickle')) except: tweets = [] print "Horay! I've got %s tweets from the file!" % len(tweets) # используем nltk featuresets = [(get_features(tweet), tweet['good']) for tweet in tweets] total = len(featuresets) train_set, test_set = featuresets[total/2:], featuresets[:total/2] classifier = nltk.NaiveBayesClassifier.train(train_set) #tree_classifier = nltk.DecisionTreeClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) classifier.show_most_informative_features(10) #print nltk.classify.accuracy(tree_classifier, test_set) if MILK: # используем milk learner = milk.defaultclassifier() get_milk_keys(get_features(tweet) for tweet in tweets) features = [get_milk_features(tweet) for tweet in tweets] labels = [tweet['good'] for tweet in tweets] model = learner.train(features, labels) ids = set(tweet['id'] for tweet in tweets) tweet_iter = twitter.statuses.friends_timeline(count=COUNT) for tweet in tweet_iter: if tweet.get('text') and tweet['id'] not in ids: print '%s: %s' % (tweet['user']['name'], tweet['text']) print '[nltk] I think, this tweet is interesting with probability', classifier.prob_classify(get_features(tweet)).prob(True) if MILK: print '[milk] I think, this tweet is interesting with probability', model.apply(get_milk_features(tweet)) good = raw_input('Interesting or not?\n(y/n): ') in ('y', 'Y', 'G', 'g') tweet['good'] = good tweets.append(tweet) pickle.dump(tweets, open('tweets.pickle', 'w'))
def oauth_login(app_name=APP_NAME,consumer_key=CONSUMER_KEY,consumer_secret=CONSUMER_SECRET,token_file='out/twitter_oauth'): try: (oauth_token, oauth_token_secret) = read_token_file(token_file) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance('deathcape', consumer_key, consumer_secret) if not os.path.isdir('out'): os.mkdir('out') write_token_file(token_file,oatuh_token,oauth_token_secret) print >> sys.stderr, "OAuth Success. Token file stored to", token_file
def oauth_login( app_name=APP_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token_file="/home/hadoop/proj/social_media/py/out/twitter.oauth", ): try: (access_token, access_token_secret) = read_token_file(token_file) except IOError, e: print >> sys.stderr, "Cannot get tokens"
def get_twitter_stream(): try: (oauth_token, oauth_token_secret)= read_token_file(token_file) except IOError, e: (oauth_token, oauth_token_secret)=oauth_dance (app_name, consumer_key, consumer_secret) if not os.path.isdir(token_path): os.mkdir(token_path) write_token_file(token_file, oauth_token, oauth_token_secret)
def main(): oauth_filename = os.environ.get('HOME', '') + os.sep + '.twitter_oauth' oauth_filename = os.path.expanduser(oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET) twitter = Twitter(auth=auth, secure=True, api_version='1', domain='api.twitter.com') try: tweets = pickle.load(open('tweets.pickle')) except: tweets = [] print "Horay! I've got %s tweets from the file!" % len(tweets) # используем nltk featuresets = [(get_features(tweet), tweet['good']) for tweet in tweets] total = len(featuresets) train_set, test_set = featuresets[total / 2:], featuresets[:total / 2] classifier = nltk.NaiveBayesClassifier.train(train_set) #tree_classifier = nltk.DecisionTreeClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) classifier.show_most_informative_features(10) #print nltk.classify.accuracy(tree_classifier, test_set) if MILK: # используем milk learner = milk.defaultclassifier() get_milk_keys(get_features(tweet) for tweet in tweets) features = [get_milk_features(tweet) for tweet in tweets] labels = [tweet['good'] for tweet in tweets] model = learner.train(features, labels) ids = set(tweet['id'] for tweet in tweets) tweet_iter = twitter.statuses.friends_timeline(count=COUNT) for tweet in tweet_iter: if tweet.get('text') and tweet['id'] not in ids: print '%s: %s' % (tweet['user']['name'], tweet['text']) print '[nltk] I think, this tweet is interesting with probability', classifier.prob_classify( get_features(tweet)).prob(True) if MILK: print '[milk] I think, this tweet is interesting with probability', model.apply( get_milk_features(tweet)) good = raw_input('Interesting or not?\n(y/n): ') in ('y', 'Y', 'G', 'g') tweet['good'] = good tweets.append(tweet) pickle.dump(tweets, open('tweets.pickle', 'w'))
def authen(): """ Authenticate with Twitter OAuth """ # When using rainbow stream you must authorize. twitter_credential = os.environ.get( 'HOME', os.environ.get('USERPROFILE', '')) + os.sep + '.rainbow_oauth' if not os.path.exists(twitter_credential): oauth_dance("Rainbow Stream", CONSUMER_KEY, CONSUMER_SECRET, twitter_credential) oauth_token, oauth_token_secret = read_token_file(twitter_credential) return OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)
def __init__(self, connection): self.channelMatch = [ re.compile( '%s: Shorten that( URL)?' % connection.nickname, re.IGNORECASE), # 0 re.compile( '%s: Shorten (.*?)\'s? (link|url)' % connection.nickname, re.IGNORECASE), # 1 re.compile( '%s: Shorten this (link|url): (.*)$' % connection.nickname, re.IGNORECASE), # 2 re.compile('.*https?\:\/\/', re.IGNORECASE)] # 3 self.dbconnection = connection.dbconnection self.bitly = bitly_api.Connection( connection.config.get( "bitly", "username"), connection.config.get( "bitly", "apikey")) self.yt_service = gdata.youtube.service.YouTubeService() self.yt_service.ssl = True self.lastlink = {} OAUTH_FILENAME = os.environ.get( 'HOME', '') + os.sep + '.lampstand_oauth' CONSUMER_KEY = connection.config.get("twitter", "consumer_key") CONSUMER_SECRET = connection.config.get("twitter", "consumer_secret") if not os.path.exists(OAUTH_FILENAME): oauth_dance( "Lampstand", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME) self.oauth_token, self.oauth_token_secret = read_token_file( OAUTH_FILENAME) self.twitter = Twitter( auth=OAuth( self.oauth_token, self.oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, domain='api.twitter.com')
def do_tool_oauth(): if not os.path.exists(CREDS_VERIFIED): if len(sys.argv) < 3: result = "need-oauth" else: (callback_url, oauth_verifier) = (sys.argv[1], sys.argv[2]) result = oauth_url_dance(CONSUMER_KEY, CONSUMER_SECRET, callback_url, oauth_verifier, CREDS_PRE_VERIFIY, CREDS_VERIFIED) # a string means a URL for a redirect (otherwise we get a tuple back with auth tokens in) if type(result) == str: set_status_and_exit('auth-redirect', 'error', 'Permission needed from Twitter', { 'url': result } ) oauth_token, oauth_token_secret = read_token_file(CREDS_VERIFIED) tw = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)) return tw
def create_oauth(oauthfile, consumer_key, consumer_secret): """ Creates and OAuth object using the tokens from the oauthfile and the consumer_key and consumer_secret. If the file doesn't exists we prompt the user to initiate the oauth dance, and save the token and token secret in the oauthfile """ try: token, token_secret = read_token_file(oauthfile) except IOError: token, token_secret = do_oauth_dance(oauthfile, consumer_key, consumer_secret) return OAuth(token, token_secret, consumer_key, consumer_secret)
def oauth_login(app_name="", consumer_key="", consumer_secret="", token_file="out/twitter.oauth"): try: (access_token, access_token_secret) = read_token_file(token_file) except: (access_token, access_token_secret) = oauth_dance(app_name, consumer_key, consumer_secret) if not os.path.isdir('out'): os.mkdir('out') write_token_file(token_file, access_token, access_token_secret) print >> sys.stderr, "OAuth Success. Token file stored to", token_file return twitter.Twitter(domain='api.twitter.com', api_version='1', auth=twitter.oauth.OAuth(access_token, access_token_secret, consumer_key, consumer_secret))
def __init__(self, consumer_uri, token_uri): # TODO: deal with storing in a database self.consumer_key, self.consumer_secret = load_consumer_from_file(consumer_uri) if not os.path.exists(token_uri): raise EasyTwitterError(u"Run %s.__init__ manually to authorize this application" % __package__) self.token_key, self.token_secret = oauth.read_token_file(token_uri) self.twitter = Twitter( auth=oauth.OAuth(self.token_key, self.token_secret, self.consumer_key, self.consumer_secret), secure=True, api_version='1', domain='api.twitter.com')
def get_twitter(need_auth=False): if need_auth: oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME) auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET) else: auth = None twitter = Twitter(auth=auth, secure=True, api_version='1', domain='api.twitter.com') return twitter
def main() : ''' main needs a description... ''' import codecs import datetime import os.path import traceback options = doOptions() olsonName = getOlsonName() if None is not olsonName : from pytz import timezone global _timeZone _timeZone = timezone( olsonName ) oauthFile = tweePath( options, 'auth' ) # should add code to handle the handshake... # from twitter.oauth_dance import oauth_dance # oauth_dance( "the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET, options['oauth_filename']) oauth_token, oauth_token_secret = read_token_file( oauthFile ) if options.saveLog : options.outFile = codecs.open( options.outFilePath, mode='a', encoding='utf8' ) twitter = Twitter( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET ), api_version='1.1', ) printText( '-=-=' * 10, options ) printText( 'Starting @ %s\n' % datetime.datetime.utcnow(), options ) myLists = twitter.lists.list() for aList in myLists : if options.list == aList[ 'slug' ] : options.listId = aList[ 'id' ] setattr( options, 'screen_name', twitter.account.verify_credentials()[ 'screen_name' ] ) try : run( twitter, options ) except KeyboardInterrupt : pass except : traceback.print_exc() if None != options.outFile : if not options.outFile.closed : options.outFile.close()
def oauth_helper(): oauth_verifier = request.args.get("oauth_verifier") # Pick back up credentials from ipynb_oauth_dance oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE) _twitter = twitter.Twitter( auth=twitter.OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), format="", api_version=None ) oauth_token, oauth_token_secret = parse_oauth_tokens(_twitter.oauth.access_token(oauth_verifier=oauth_verifier)) # This web server only needs to service one request, so shut it down shutdown_after_request = request.environ.get("werkzeug.server.shutdown") shutdown_after_request() # Write out the final credentials that can be picked up after the following # blocking call to webserver.run(). write_token_file(OAUTH_FILE, oauth_token, oauth_token_secret) return "%s %s written to %s" % (oauth_token, oauth_token_secret, OAUTH_FILE)
def oauth_login( app_name=APP_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token_file="out/twitter.oauth" ): try: (access_token, access_token_secret) = read_token_file(token_file) except IOError, e: (access_token, access_token_secret) = oauth_dance(app_name, consumer_key, consumer_secret) if not os.path.isdir("out"): os.mkdir("out") write_token_file(token_file, access_token, access_token_secret) print >>sys.stderr, "OAuth Success. Token file stored to", token_file
def oauth_login(app_name="Analyzing_Twitter", consumer_key="1H3NUrvWq1OGuQVh9420Spvld", consumer_secret="3YmiaPqyiuN00TNlHCKSgLLqfvrFr088nKT7qaukrtZXmZrx9R", token_file=''): try: (access_token, access_token_secret) = read_token_file(token_file) except IOError as e: (access_token, access_token_secret) = oauth_dance(app_name, consumer_key,consumer_secret) if not os.path.isdir('out'): os.mkdir('out') write_token_file(token_file, access_token, access_token_secret) print (sys.stderr, "OAuth Success. Token file stored to", token_file) return twitter.Twitter(auth=twitter.oauth.OAuth(access_token, access_token_secret, consumer_key, consumer_secret))
def oauth_login(app_name=APP_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token_file='auth/twitter.oauth'): # try to read the token file try: (access_token, access_token_secret) = read_token_file(token_file) except IOError, e: # if it fails, create the token and write it to disk (access_token, access_token_secret) = oauth_dance(app_name, consumer_key, consumer_secret) if not os.path.isdir('auth'): os.mkdir('auth') write_token_file(token_file, access_token, access_token_secret) print >> sys.stderr, "OAuth Success. Token file stored to", token_file
def __init__(self): """If the user is not authorized yet, do the OAuth dance and save the credentials in her home folder for future incovations. Then read the credentials and return the authorized Twitter API object.""" if not os.path.exists(OAUTH_FILENAME): oauth_dance("@swissbolli's Monday Twitter Backup", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME ) oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME) self.api = Twitter( auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), retry=5 ) user = self.api.account.settings(_method='GET') self.screen_name = user['screen_name']
def main(): args = parse_arguments() # When using twitter stream you must authorize. oauth_filename = os.path.join(os.getenv("HOME", ""), ".twitter-stream-archiver_oauth") if not os.path.exists(oauth_filename): oauth_dance("Twitter-Stream-Archiver", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET) # These arguments are optional: stream_args = dict( timeout=args.timeout, block=not args.no_block, heartbeat_timeout=args.heartbeat_timeout) query_args = dict() if args.track_keywords: query_args['track'] = args.track_keywords if args.track_users: query_args['follow'] = args.track_users if args.track_locations: query_args['locations'] = args.track_locations stream = TwitterStream(auth=auth, **stream_args) if query_args: tweet_iter = stream.statuses.filter(**query_args) else: tweet_iter = stream.statuses.sample() # Iterate over the sample stream. for tweet in tweet_iter: # You must test that your tweet has text. It might be a delete # or data message. if tweet is None: sys.stderr.write("-- None --\n") elif tweet is Timeout: sys.stderr.write("-- Timeout --\n") elif tweet is HeartbeatTimeout: sys.stderr.write("-- Heartbeat Timeout --\n") elif tweet is Hangup: sys.stderr.write("-- Hangup --\n") elif tweet.get('text'): sys.stdout.write(json.dumps(tweet)) sys.stdout.write('\n') sys.stdout.flush() else: sys.stderr.write("-- Some data: " + str(tweet) + "\n")
def post_client(): oauth_filename = os.environ.get('HOME', '') + os.sep + '.twitter_oauth' oauth_token, oauth_token_secret = read_token_file(oauth_filename) return Twitter( auth=OAuth( oauth_token, oauth_token_secret, secret.TWITTER_CONSUMER_KEY, secret.TWITTER_CONSUMER_SECRET ), secure=True, api_version='1.1', domain='api.twitter.com' )
def login(): APP_NAME = 'Learning Python - Mining' CONSUMER_KEY = consumer_key CONSUMER_SECRET = consumer_secret TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def oauth_login(app_name='', consumer_key='', consumer_secret='', token_file='out/twitter.oauth'): try: (access_token, access_token_secret) = read_token_file(token_file) except IOError, e: (access_token, access_token_secret) = oauth_dance(app_name, consumer_key, consumer_secret) if not os.path.isdir('out'): os.mkdir('out') write_token_file(token_file, access_token, access_token_secret) print >> sys.stderr, "OAuth Success. Token file stored to", token_file
def postTweet(self): """Simple method to post a tweet""" oauth_token, oauth_secret = read_token_file(self.MY_TWITTER_CREDS) try: if self.check_graphical.checkState() == 2: t_up = Twitter(domain='upload.twitter.com', auth=OAuth(oauth_token, oauth_secret, self.CONSUMER_KEY, self.CONSUMER_SECRET)) with open(self.DATA_PATH + "/graphical_abstracts/{}".format(self.graphical), "rb") as image: imagedata = image.read() id_img = t_up.media.upload(media=imagedata)["media_id_string"] else: self.l.debug("No image, check box not checked") id_img = None except AttributeError: self.l.debug("No image, no check box at all") id_img = None twitter = Twitter(auth=OAuth(oauth_token, oauth_secret, self.CONSUMER_KEY, self.CONSUMER_SECRET)) text = self.text_tweet.toPlainText() + " #ChemBrows" if id_img is None: try: twitter.statuses.update(status=text) except Exception as e: QtWidgets.QMessageBox.critical(self, "Twitter error", "ChemBrows could not tweet that.\nYour tweet is probably too long: {} chara.".format(len(text)), QtWidgets.QMessageBox.Ok, defaultButton=QtWidgets.QMessageBox.Ok) self.l.error('postTweet: {}'.format(e), exc_info=True) else: try: twitter.statuses.update(status=text, media_ids=id_img) except Exception as e: QtWidgets.QMessageBox.critical(self, "Twitter error", "ChemBrows could not tweet that.\nYour tweet is probably too long: {} chara.".format(len(text)), QtWidgets.QMessageBox.Ok, defaultButton=QtWidgets.QMessageBox.Ok) self.l.error("postTweet: {}".format(e), exc_info=True) self.close()
def login(): APP_NAME = '' CONSUMER_KEY = '' CONSUMER_SECRET = '' TOKEN_FILE = ' ' try: (oauth_token, oauth_token_secret) = read_token_file('auth/twitter.oauth') except IOError, e : (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('auth'): os.mkdir('auth') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def login(): #loging to twitter application APP_NAME = "Finance_Harvest" CONSUMER_KEY = "Bkvk7JFZmzaVpLjGAWBtxQ" CONSUMER_SECRET = "y9tugnYJeU8aMNW44o6hwWHC3QVktCYtW3RDm3Mdk" TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: print e.errno, e.strerror (oauth_token, oauth_token_secret) = oauth_dance( APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = "ContatoSalvo" CONSUMER_KEY = "WwE7cxlLi7FsmyWRKSx17A" CONSUMER_SECRET = "2YQk2bW98LxcKRCUOicnWWg1tZUukSFwMZqX1MLxT3k" TOKEN_FILE = "out/twitter.oauth" try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir("out"): os.mkdir("out") write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def login(): #loging to twitter application APP_NAME = "Finance_Harvest" CONSUMER_KEY = "Bkvk7JFZmzaVpLjGAWBtxQ" CONSUMER_SECRET = "y9tugnYJeU8aMNW44o6hwWHC3QVktCYtW3RDm3Mdk" TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: print e.errno, e.strerror (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def twitterAuth(config, OAUTH_TWITTER): HOME = os.environ.get('HOME', '') twitter_user = config.get("twitter", "username") OAUTH_FILENAME = HOME + os.sep + '.lifesteam_oauth_' + twitter_user CONSUMER_KEY = config.get("twitter", "consumer_key") CONSUMER_SECRET = config.get("twitter", "consumer_secret") if not os.path.exists(OAUTH_FILENAME): oauth_dance("Lifestream", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME) oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME) return Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1.1', domain='api.twitter.com')
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = 'SocialWebJuanPavez' CONSUMER_KEY = 'XTtlNpLJRamXyuJOvX1g' CONSUMER_SECRET = 'O8oHQ3Yn2KCIUDnlMv7MmbKOZP82qpY43ITMh5kQmE' TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def __init__(self, consumer_uri, token_uri): # TODO: deal with storing in a database self.consumer_key, self.consumer_secret = load_consumer_from_file( consumer_uri) if not os.path.exists(token_uri): raise EasyTwitterError( u"Run %s.__init__ manually to authorize this application" % __package__) self.token_key, self.token_secret = oauth.read_token_file(token_uri) self.twitter = Twitter(auth=oauth.OAuth(self.token_key, self.token_secret, self.consumer_key, self.consumer_secret), secure=True, api_version='1', domain='api.twitter.com')
def do_tool_oauth(): if not os.path.exists(CREDS_VERIFIED): if len(sys.argv) < 3: result = "need-oauth" else: (callback_url, oauth_verifier) = (sys.argv[1], sys.argv[2]) result = oauth_url_dance(CONSUMER_KEY, CONSUMER_SECRET, callback_url, oauth_verifier, CREDS_PRE_VERIFIY, CREDS_VERIFIED) # a string means a URL for a redirect (otherwise we get a tuple back with auth tokens in) if type(result) == str: set_status_and_exit('auth-redirect', 'error', 'Permission needed from Twitter', {'url': result}) oauth_token, oauth_token_secret = read_token_file(CREDS_VERIFIED) tw = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)) return tw
def twittersetup(): if not os.path.isfile('../auth/twitter_app.dat'): try: appfile = open('../auth/twitter_app.dat', 'w') appfile.write("#App name\n") appname = raw_input("Enter twitter app name: ") appfile.write(appname + '\n') appfile.write("#Consumer key\n") appconsumer = raw_input("Enter twitter app consumer key: ") appfile.write(appconsumer + '\n') appfile.write("#Consumer Secret\n") appsecret = raw_input("Enter twitter app secret key: ") appfile.write(appsecret + '\n') except: appfile.close() print "There was an issue creating the twitter app auth data!!" exit() finally: appfile.flush() os.fsync(appfile) appfile.close() try: tappfile = open('../auth/' + 'twitter_app.dat', 'r') tappline = tappfile.readlines() APP_NAME = tappline[1].rstrip() CONSUMER_KEY = tappline[3].rstrip() CONSUMER_SECRET = tappline[5].rstrip() tappfile.close() except: exit("Could not read app data file for twitter") #file that Oauth data is stored TOKEN_FILE = '../auth/' + 'token.txt' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) print e.errno print e write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def twitter_authorize(): """ Authorize the application to access the user's profile using twitter's API v1.1's Authentication Model (oAuth dance) If the application is being authorized for the first time, the access key & secret are saved into a file and with every other execution of the script, the access token & secret are read from the oauth file. :returns twitter_api """ debug_print("EXEC twitter_authorize method :") debug_print(" Authorizing...") debug_print(" Checking operating system : %s ; for file's path " % platform.system()) # Read the access token from a file try: oauth_token, oauth_token_secret = read_token_file(twitter_OAUTH_FILE) except IOError, e: # failed to open file debug_print(" %s" % e.message) logger.error(e.message)
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = 'Photography' CONSUMER_KEY = 'fFRVfkuoNyafZglDwDGKpWF1o' CONSUMER_SECRET = 'lRMw1avbxoKF13eJ0CeF9WYC6jqMga4310mz6O3uyBQdOUDYkC' TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = '' CONSUMER_KEY = '' CONSUMER_SECRET = '' TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = 'bigrams' CONSUMER_KEY = 'pqVYCCTqqDq3WSrwuAaesw' CONSUMER_SECRET = 'kvG6OTTvYt6j1rXS34083u9vS0skTSbOCsVImGRWU' TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def login(app_name=APP_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token_file='out/twitter.oauth'): try: (access_token, access_token_secret) = read_token_file(token_file) except IOError as e: (access_token, access_token_secret) = oauth_dance(app_name, consumer_key, consumer_secret) if not os.path.isdir('out'): os.mkdir('out') write_token_file(token_file, access_token, access_token_secret) print ( sys.stderr, "OAuth Success. Token file stored to", token_file) return twitter.Twitter(auth=twitter.oauth.OAuth(access_token, access_token_secret, consumer_key, consumer_secret))
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = '' CONSUMER_KEY = 'SKxOLVcsxlPN68V3g2hAA' CONSUMER_SECRET = 'jBc0MUUNebHiIEkkraM7IruUyoSY2OZZyZ7eW6qqYw' TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
def oauth_login(): # After the webserver.run() blocking call, start the oauth dance that will ultimately # cause Twitter to redirect a request back to it. Once that request is serviced, the web # server will shutdown, and program flow will resume with the OAUTH_FILE containing the # necessary credentials Timer(1, lambda: ipynb_oauth_dance()).start() #webserver.run(host='0.0.0.0') print "2" # The values that are read from this file are written out at # the end of /oauth_helper OAUTH_TOKEN, OAUTH_TOKEN_SECRET = read_token_file(OAUTH_FILE) # XXX: Go to http://twitter.com/apps/new to create an app and get values # for these credentials that you'll need to provide in place of these # empty string values that are defined as placeholders. # See https://dev.twitter.com/docs/auth/oauth for more information # on Twitter's OAuth implementation. auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET) twitter_api = twitter.Twitter(auth=auth) return twitter_api
def login(): # Go to http://twitter.com/apps/new to create an app and get these items # See also http://dev.twitter.com/pages/oauth_single_token APP_NAME = 'Experiment1' CONSUMER_KEY = 'UkmiRFjbevouUfXh36sVg' CONSUMER_SECRET = '7bMMc3nBhHI7JjIMep3Xf7Dkl6w8ImIH7WsskgogY' TOKEN_FILE = 'out/twitter.oauth' try: (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE) except IOError, e: (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET) if not os.path.isdir('out'): os.mkdir('out') write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)