当前位置: 首页>>代码示例>>Python>>正文


Python tweepy.OAuthHandler方法代码示例

本文整理汇总了Python中tweepy.OAuthHandler方法的典型用法代码示例。如果您正苦于以下问题:Python tweepy.OAuthHandler方法的具体用法?Python tweepy.OAuthHandler怎么用?Python tweepy.OAuthHandler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tweepy的用法示例。


在下文中一共展示了tweepy.OAuthHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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") 
开发者ID:SecPi,项目名称:SecPi,代码行数:27,代码来源:twitter.py

示例2: sendTweet

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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!") 
开发者ID:supthunder,项目名称:premeStock,代码行数:20,代码来源:monitor.py

示例3: get

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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('/') 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:26,代码来源:read_tweepy.py

示例4: __init__

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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 
开发者ID:pajbot,项目名称:pajbot,代码行数:26,代码来源:twitter.py

示例5: initialize

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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() 
开发者ID:jpescada,项目名称:TwitterPiBot,代码行数:20,代码来源:twitter_client.py

示例6: last_tweet

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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 
开发者ID:DarkStar7471,项目名称:THM-Bot,代码行数:18,代码来源:social.py

示例7: __init__

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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 
开发者ID:congosto,项目名称:t-hoarder,代码行数:25,代码来源:tweet_streaming_large.py

示例8: get_medias

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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 
开发者ID:Spark-NF,项目名称:twitter_media_downloader,代码行数:26,代码来源:parser.py

示例9: send_tweet

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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)) 
开发者ID:meneses-pt,项目名称:goals.zone,代码行数:23,代码来源:goals_populator.py

示例10: main

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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]) 
开发者ID:AntreasAntoniou,项目名称:DeepClassificationBot,代码行数:21,代码来源:bot.py

示例11: auth

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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 
开发者ID:zbarge,项目名称:stocklook,代码行数:27,代码来源:twitah.py

示例12: test_get_tweepy_auth

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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) 
开发者ID:michaelbrooks,项目名称:twitter-monitor,代码行数:18,代码来源:test_basic_stream.py

示例13: tweeter

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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) 
开发者ID:rhiever,项目名称:reddit-twitter-bot,代码行数:25,代码来源:reddit_twitter_bot.py

示例14: get_all_tweets

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
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 
开发者ID:utkusen,项目名称:rhodiola,代码行数:22,代码来源:rhodiola.py

示例15: __init__

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import OAuthHandler [as 别名]
def __init__(self):
            self.consumer_key = settings.TWITTER_KEY
            self.consumer_secret = settings.TWITTER_SECRET
            self.token = settings.TWITTER_ACCESS_TOKEN
            self.token_secret = settings.TWITTER_TOKEN_SECRET
            auth = tweepy.OAuthHandler(self.consumer_key,
                                       self.consumer_secret)
            auth.set_access_token(self.token, self.token_secret)

            self.api = tweepy.API(auth) 
开发者ID:kimeraapp,项目名称:pythonjobs.ie,代码行数:12,代码来源:services.py


注:本文中的tweepy.OAuthHandler方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。