Python tweepy.OAuthHandler() Examples

The following are 30 code examples of tweepy.OAuthHandler(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tweepy , or try the search function .
Example #1
Source File: rhodiola.py    From rhodiola with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_all_tweets(screen_name):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)
    alltweets = []  
    new_tweets = api.user_timeline(screen_name = screen_name,count=200, include_rts=False,tweet_mode = 'extended')
    alltweets.extend(new_tweets)
    oldest = alltweets[-1].id - 1
    while len(new_tweets) > 0:
      new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest, include_rts=False,tweet_mode = 'extended')
      alltweets.extend(new_tweets)
      oldest = alltweets[-1].id - 1
      print "Downloaded %s tweets.." % (len(alltweets))
    outtweets = ""
    for tweet in alltweets:
        if tweet.full_text.encode("utf-8").startswith('@'):
            pass
        else:
            outtweets += (tweet.full_text.encode("utf-8").split('https://t.co')[0])
    return outtweets 
Example #2
Source File: monitor.py    From premeStock with MIT License 6 votes vote down vote up
def sendTweet(item,color,link, size):
    # line 102
    auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
    auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
    api = tweepy.API(auth)

    tweet = item+"\n"
    tweet += color+'\n'
    tweet += size.title()+'\n'
    tweet += link+'\n'
    tweet += "Restock!"+'\n'
    tweet += str(datetime.utcnow().strftime('%H:%M:%S.%f')[:-3])

    try:
        api.update_status(tweet)
        print(tweet)
    except:
        print("Error sending tweet!") 
Example #3
Source File: read_tweepy.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def get(self):
        resp = self.get_args()
        rqst = self.request
        verifier = rqst.get('oauth_verifier')

        this_app = AppOpenLSH.get_or_insert('KeyOpenLSH')
        auth = tweepy.OAuthHandler(this_app.twitter_consumer_key, this_app.twitter_consumer_secret)
        auth.set_request_token(self.session['request_token_key'], self.session['request_token_secret'])

        try:
            auth.get_access_token(verifier)
            self.session['auth.access_token.key'] = auth.access_token.key
            self.session['auth.access_token.secret'] = auth.access_token.secret

            this_app.twitter_access_token(auth.access_token.key, auth.access_token.secret)
            self.session['tw_logged_in'] = True
            self.session['tweets'] = []

            frameinfo = getframeinfo(currentframe())
            logging.debug('file %s, line %s auth %s %s', frameinfo.filename, frameinfo.lineno+1, auth.access_token.key, auth.access_token.secret)
        except tweepy.TweepError:
            logging.error('Error! Failed to get access token.')
        
        self.redirect('/') 
Example #4
Source File: twitter.py    From pajbot with MIT License 6 votes vote down vote up
def __init__(self, bot):
        self.bot = bot

        self.twitter_client = None
        self.listener = None

        if self.bot:
            self.bot.socket_manager.add_handler("twitter.follow", self.on_twitter_follow)
            self.bot.socket_manager.add_handler("twitter.unfollow", self.on_twitter_unfollow)

        if "twitter" not in bot.config:
            return

        twitter_config = bot.config["twitter"]
        self.use_twitter_stream = "streaming" in twitter_config and twitter_config["streaming"] == "1"

        try:
            self.twitter_auth = tweepy.OAuthHandler(twitter_config["consumer_key"], twitter_config["consumer_secret"])
            self.twitter_auth.set_access_token(twitter_config["access_token"], twitter_config["access_token_secret"])

            self.twitter_client = tweepy.API(self.twitter_auth)
        except:
            log.exception("Twitter authentication failed.")
            self.twitter_client = None 
Example #5
Source File: twitter_client.py    From TwitterPiBot with MIT License 6 votes vote down vote up
def initialize():

	output = TwitterStreamListener()

	# setup Twitter API connection details
	twitter_auth = OAuthHandler( TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET )
	twitter_auth.set_access_token( TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET )
	
	# connect to Twitter Streaming API
	twitter_stream = Stream( twitter_auth, output )

	# filter tweets using track, follow and/or location parameters
	# https://dev.twitter.com/streaming/reference/post/statuses/filter
	twitter_stream.filter(track=[ TWITTER_HASHTAG ])


# def cleanup():
# 	twitter_stream.disconnect() 
Example #6
Source File: social.py    From THM-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
def last_tweet(self, ctx):
        # Secret twitter API key.
        creds = [cred.replace("\n", "") for cred in open(file_twitter_cred, "r")]

        # Auth & get.
        auth = tweepy.OAuthHandler(creds[0], creds[1])
        auth.set_access_token(creds[2], creds[3])
        api = tweepy.API(auth)
        tryhackme_tweets = api.user_timeline(
            screen_name='RealTryHackMe', count=20, include_rts=False)

        # Sends first found tweet. (and not reply.)
        for tweet in tryhackme_tweets:
            if not tweet.in_reply_to_screen_name:
                await ctx.send("https://twitter.com/RealTryHackMe/status/" + str(tweet.id))
                break 
Example #7
Source File: tweet_streaming_large.py    From t-hoarder with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,  app_keys_file,user_keys_file):
    self.matrix={}
    self.app_keys_file = app_keys_file
    self.user_keys_file = user_keys_file
    app_keys=[]
    user_keys=[]
    f = open(self.app_keys_file, 'rU')
    for line in f: 
      app_keys.append(line[:-1])
#    print app_keys
    f.close()
    f = open( self.user_keys_file, 'rU')
    for line in f: 
      user_keys.append(line[:-1])
    f.close()
    try: 
      self.auth = tweepy.OAuthHandler(app_keys[0],app_keys[1])
      self.auth.secure = True
      self.auth.set_access_token(user_keys[0], user_keys[1])
    except:
      print 'Error in oauth autentication, user key ', user_keys_file_num
      exit(83)
    return 
Example #8
Source File: goals_populator.py    From goals.zone with GNU General Public License v3.0 6 votes vote down vote up
def send_tweet(match, videogoal, videogoal_mirror, event_filter):
    try:
        tweets = Tweet.objects.filter(event_type=event_filter)
        for tw in tweets:
            to_send = check_conditions(match, tw) and \
                      check_link_regex(tw, videogoal, videogoal_mirror, event_filter) and \
                      check_author(tw, videogoal, videogoal_mirror, event_filter)
            if not to_send:
                return
            try:
                message = format_event_message(match, videogoal, videogoal_mirror, tw.message)
                auth = tweepy.OAuthHandler(tw.consumer_key, tw.consumer_secret)
                auth.set_access_token(tw.access_token_key, tw.access_token_secret)
                api = tweepy.API(auth)
                result = api.update_status(status=message)
                print(result)
            except Exception as ex:
                print("Error sending twitter single message", str(ex))
                send_monitoring_message("*Twitter message not sent!*\n" + str(ex))
    except Exception as ex:
        print("Error sending twitter messages: " + str(ex)) 
Example #9
Source File: bot.py    From DeepClassificationBot with MIT License 6 votes vote down vote up
def main(args):
    if args.debug:
        logger.setLevel(logging.DEBUG)

    auth = tweepy.OAuthHandler(args.consumer_key, args.consumer_secret)
    auth.set_access_token(args.access_token, args.access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    screen_name = api.me().screen_name

    if args.classifier == 'mock':
        classifier = classifiers.MockClassifier()
    elif args.classifier == 'local':
        classifier = classifiers.URLClassifier(classifiers.ImageClassifier(args.dataset_path, INPUT_SHAPE))
    elif args.classifier == 'remote':
        classifier = classifiers.RemoteClassifier(args.remote_endpoint)

    stream = tweepy.Stream(auth=auth, listener=ReplyToTweet(screen_name, classifier, api, args.silent))
    logger.info('Listening as {}'.format(screen_name))
    stream.userstream(track=[screen_name]) 
Example #10
Source File: twitah.py    From stocklook with MIT License 6 votes vote down vote up
def auth(self):
        """
        tweepy.OAuthHandler generated on demand using environment (or user injected)
        variables that have been loaded into global dictionary stocklook.config.config
        :return:
        """
        if self._auth is None:
            tokens = (consumer_key, consumer_secret,
                      access_token, access_token_secret)
            if not all(tokens):
                raise KeyError("Unable to authorize twitter "
                               "as there is a missing token. "
                               "Please make sure the following "
                               "environment variables are set:\n\t"
                               "1) {}: {}\n\t"
                               "2) {}: {}\n\t"
                               "3) {}: {}\n\t"
                               "4) {}: {}\n\t".format(
                                TWITTER_APP_KEY, consumer_key,
                                TWITTER_APP_SECRET, consumer_secret,
                                TWITTER_CLIENT_KEY, access_token,
                                TWITTER_CLIENT_SECRET, access_token_secret))
            self._auth = OAuthHandler(consumer_key, consumer_secret)
            self._auth.set_access_token(access_token, access_token_secret)
        return self._auth 
Example #11
Source File: test_basic_stream.py    From twitter-monitor with MIT License 6 votes vote down vote up
def test_get_tweepy_auth(self):
        twitter_api_key = b'ak'
        twitter_api_secret = b'as'
        twitter_access_token = 'at'
        twitter_access_token_secret = 'ats'
        result = basic_stream.get_tweepy_auth(twitter_api_key,
                                              twitter_api_secret,
                                              twitter_access_token,
                                              twitter_access_token_secret)

        self.assertTrue(isinstance(result, tweepy.OAuthHandler))

        self.assertEqual(result.consumer_key, twitter_api_key)
        self.assertEqual(result.consumer_secret, twitter_api_secret)
        self.assertEqual(result.access_token, twitter_access_token)
        self.assertEqual(result.access_token_secret, twitter_access_token_secret) 
Example #12
Source File: reddit_twitter_bot.py    From reddit-twitter-bot with GNU General Public License v3.0 6 votes vote down vote up
def tweeter(post_dict, post_ids):
    ''' Tweets all of the selected reddit posts. '''
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth)

    for post, post_id in zip(post_dict, post_ids):
        img_path = post_dict[post]['img_path']

        extra_text = ' ' + post_dict[post]['link'] + TWEET_SUFFIX
        extra_text_len = 1 + T_CO_LINKS_LEN + len(TWEET_SUFFIX)
        if img_path:  # Image counts as a link
            extra_text_len += T_CO_LINKS_LEN
        post_text = strip_title(post, TWEET_MAX_LEN - extra_text_len) + extra_text
        print('[bot] Posting this link on Twitter')
        print(post_text)
        if img_path:
            print('[bot] With image ' + img_path)
            api.update_with_media(filename=img_path, status=post_text)
        else:
            api.update_status(status=post_text)
        log_tweet(post_id)
        time.sleep(DELAY_BETWEEN_TWEETS) 
Example #13
Source File: parser.py    From twitter_media_downloader with Apache License 2.0 6 votes vote down vote up
def get_medias(auth, user_id, include_retweets, image_size, since, since_id, until, until_id, likes):
    """Get all medias for a given Twitter user."""
    auth = tweepy.OAuthHandler(auth['consumer_token'], auth['consumer_secret'])
    api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

    results = {
        'tweets': 0,
        'retweets': 0,
        'media': []
    }
    capi = api.favorites if likes else api.user_timeline
    for tweet in tweepy.Cursor(capi, id=user_id, include_rts=include_retweets, include_entities=True, tweet_mode='extended', since_id=since_id, max_id=until_id).items():
        if since is not None and tweet.created_at < since:
            break
        if until is not None and tweet.created_at > until:
            continue
        parse_tweet(tweet, include_retweets, image_size, results)

    print('Medias for user {0}'.format(user_id))
    print('- Tweets: {0}'.format(results['tweets']))
    print('- Retweets: {0}'.format(results['retweets']))
    print('- Parsed: {0}'.format(len(results['media'])))

    return results 
Example #14
Source File: twitter.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, id, params):
		super(Twitter, self).__init__(id, params)

		try:
			self.consumer_key = params["consumer_key"]
			self.consumer_secret = params["consumer_secret"]
			self.access_token = params["access_token"]
			self.access_token_secret = params["access_token_secret"]
			self.recipients = [rec.strip() for rec in params["recipients"].split(",")]
		except KeyError as ke:
			logging.error("Twitter: Error while trying to initialize notifier, it seems there is a config parameter missing: %s" % ke)
			self.corrupted = True
			return

		try:
			auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)
			auth.set_access_token(self.access_token, self.access_token_secret)

			self.api = tweepy.API(auth)
		except Exception as e:
			logging.error("Twitter: Error while trying to initialize notifier: %s" % e)
			self.corrupted = True
			return
			
		logging.info("Twitter: Notifier initialized") 
Example #15
Source File: twitterxl.py    From pyxll-examples with The Unlicense 5 votes vote down vote up
def __init__(self, phrases):
        """Use static method 'get_listener' instead of constructing directly"""
        _log.info("Creating listener for [%s]" % ", ".join(phrases))
        self.__phrases = phrases
        self.__subscriptions = set()
        self.__tweets = [None] * self.__max_size

        # listen for tweets in a background thread using the 'async' keyword
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        self.__stream = Stream(auth, listener=self)
        self.__stream.filter(track=phrases, async=True)
        self.__connected = True 
Example #16
Source File: tweetstreamer.py    From listentotwitter with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, tweet_callback, new_keywords_callback):
        self._tweet_callback = tweet_callback
        self._new_keywords_callback = new_keywords_callback

        self._auth = OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
        self._auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)

        self._streamthread = None
        self._new_streamthead = None
        self._keywords_tracking = None
        self._current_keywords_tracking = []
        self._update_keywords_tracking_locked = False
        self._last_update_keywords_tracking_locked = 0
        self._last_connect = 0 
Example #17
Source File: LARRYCHATTER_CommandPost.py    From LARRYCHATTER with MIT License 5 votes vote down vote up
def postTweetPhoto():
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth)
    stegoImageCWD = os.getcwd()
    stegoImagePath = stegoImageCWD + '/secret-file.png'
    api.update_with_media(stegoImagePath) 
Example #18
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, oauth_token, oauth_secret, consumer_key, consumer_secret, timeout=60):
        """
        Basic interface to twitter pandas is pretty much a wrapper around tweepy.  As such, we take in very similar args
        to the main constructor.

        :param oauth_token:
        :param oauth_secret:
        :param consumer_key:
        :param consumer_secret:
        :param timeout:
        :return:

        """

        # configure OAUTH
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(oauth_token, oauth_secret)

        # set up tweepy client
        self.client = tweepy.API(
            auth,
            wait_on_rate_limit=True,
            wait_on_rate_limit_notify=True,
            timeout=60,
            retry_count=5,
            retry_delay=60,
            retry_errors={401, 404, 500, 503},
        )

    # #################################################################
    # #####  Internal functions and protected methods             #####
    # ################################################################# 
Example #19
Source File: twitter_stream.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def twitter_connection(file):
        '''Create the object from which the Twitter API will be consumed,
        reading the credentials from a file, defined in path parameter.'''
        (CONSUMER_KEY,
         CONSUMER_SECRET,
         OAUTH_TOKEN,
     OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()

        # We instanced the authorization manager
        auth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
        auth.set_access_token(OAUTH_TOKEN,OAUTH_TOKEN_SECRET)

        return (tweepy.API(auth), auth) 
Example #20
Source File: twitter.py    From kryptoflow with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, producer=None, twitter_config=None):
        super(TwitterStream, self).__init__()
        self.topic = 'twitter'
        self.auth = tweepy.OAuthHandler(twitter_config['consumer_key'], twitter_config['consumer_secret'])
        self.auth.set_access_token(twitter_config['access_token'], twitter_config['access_secret'])
        self.analyzer = TextAnalyzer()

        self.producer = producer 
Example #21
Source File: service.py    From polybot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def auth(self):
        auth = tweepy.OAuthHandler(
            self.config.get("twitter", "api_key"),
            self.config.get("twitter", "api_secret"),
        )
        auth.set_access_token(
            self.config.get("twitter", "access_key"),
            self.config.get("twitter", "access_secret"),
        )
        self.tweepy = tweepy.API(auth)
        me = self.tweepy.me()
        self.log.info("Connected to Twitter as %s", me.screen_name) 
Example #22
Source File: tweepy_pool.py    From smappPy with GNU General Public License v2.0 5 votes vote down vote up
def _get_tweepy_oauth_handler(self, oauth_dict):
        try:
            auth = tweepy.OAuthHandler(oauth_dict["consumer_key"], oauth_dict["consumer_secret"])
        except TweepError:
            print TweepError
        auth.set_access_token(oauth_dict["access_token"], oauth_dict["access_token_secret"])
        return auth 
Example #23
Source File: twitter_client.py    From indra with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_oauth_file(auth_file):
    try:
        fh = open(auth_file, 'rt')
    except IOError:
        print('Could not get Twitter credentials.')
        return None
    lines = [l.strip() for l in fh.readlines()]
    oauth = tweepy.OAuthHandler(lines[0], lines[1])
    oauth.set_access_token(lines[2], lines[3])
    fh.close()
    return oauth 
Example #24
Source File: twitter_client.py    From indra with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_oauth_dict(auth_dict):
    oauth = tweepy.OAuthHandler(auth_dict.get('consumer_token'),
                                auth_dict.get('consumer_secret'))
    oauth.set_access_token(auth_dict.get('access_token'),
                           auth_dict.get('access_secret'))
    return oauth 
Example #25
Source File: twitter.py    From busy-beaver with MIT License 5 votes vote down vote up
def __init__(self, consumer_key, consumer_secret, token, token_secret):
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(token, token_secret)
        self.client = tweepy.API(auth) 
Example #26
Source File: twitpost.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def initialize(self, bot_handler: Any) -> None:
        self.config_info = bot_handler.get_config_info('twitter')
        auth = tweepy.OAuthHandler(self.config_info['consumer_key'],
                                   self.config_info['consumer_secret'])
        auth.set_access_token(self.config_info['access_token'],
                              self.config_info['access_token_secret'])
        self.api = tweepy.API(auth, parser=tweepy.parsers.JSONParser()) 
Example #27
Source File: load.py    From twitter-for-bigquery with Apache License 2.0 5 votes vote down vote up
def start(schema, logger):

        listener = TwitterListener(config.DATASET_ID, config.TABLE_ID, logger=logger)
        auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)
        auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET)

        while True:

            logger.info("Connecting to Twitter stream")

            stream = None

            try:

                stream = tweepy.Stream(auth, listener, headers = {"Accept-Encoding": "deflate, gzip"})

                # Choose stream: filtered or sample
                stream.sample()
                # stream.filter(track=TwitterListener.TRACK_ITEMS)

            except:

                logger.exception("Unexpected error");

                if stream:
                    stream.disconnect()

                time.sleep(60) 
Example #28
Source File: twitter.py    From kafka-compose with MIT License 5 votes vote down vote up
def main():
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    listener = TwitterStreamListener()
    twitter_stream = tweepy.Stream(auth=api.auth, listener=listener)
    twitter_stream.filter(track=TRACKS, languages=['en'], async=True) 
Example #29
Source File: tweets.py    From Python with MIT License 5 votes vote down vote up
def initialize():
	global api, auth, user
	ck = "here" # consumer key
	cks = "here" # consumer key SECRET
	at = "here" # access token
	ats = "here" # access token SECRET

	auth = tweepy.OAuthHandler(ck,cks)
	auth.set_access_token(at,ats)

	api = tweepy.API(auth)
	user = api.me() 
Example #30
Source File: oauth.py    From smappPy with GNU General Public License v2.0 5 votes vote down vote up
def tweepy_auth(filename):
    """Create and return a tweepy.OAuthHandler object from a file containing oauth fields"""
    import tweepy
    oauth_dict = read_oauth(filename)
    auth = tweepy.OAuthHandler(oauth_dict["consumer_key"], oauth_dict["consumer_secret"])
    auth.set_access_token(oauth_dict["access_token"], oauth_dict["access_token_secret"])
    return auth