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


Python tweepy.OAuthHandler类代码示例

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


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

示例1: __init__

class MainRunner:
    def __init__(self, conf):
        self._conf = conf
        self._out = None
        self.listeners = []
        self._auth = OAuthHandler(conf.consumer_key, conf.consumer_secret)
        self._auth.set_access_token(conf.access_token, conf.access_token_secret)
        self._run_listener()

    def _run_listener(self):
        listener = Listener(self.out, self._conf.places)
        stream = Stream(self._auth, listener)
        locations = []
        for city in self._conf.places:
            locations.extend(city['southwest'].values())
            locations.extend(city['northeast'].values())
        stream.filter(locations=locations)

    @property
    def out(self):
        if self._out is None:
            try:
                self._out = open(self._conf.output, 'a')
            except FileNotFoundError:
                if path.exists('output.txt'):
                    self._out = open('output.txt', 'a')
                else:
                    self._out = open('output.txt', 'a')
        return self._out

    def __del__(self):
        self.out.close()
开发者ID:litleleprikon,项目名称:bachelor_paper,代码行数:32,代码来源:main_runner.py

示例2: __init__

 def __init__(self):
     global API
     auth = OAuthHandler(ckey, csecret)
     auth.set_access_token(atoken, asecret)
     self.twitterStream = Stream(auth, listener())
     API = tweepy.API(auth)
     verifyDir(IMAGE_DIR)
开发者ID:WorldViews,项目名称:Spirals,代码行数:7,代码来源:PeriscopeWatcher.py

示例3: twitter_login

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)
开发者ID:7pairs,项目名称:twingo2,代码行数:26,代码来源:views.py

示例4: __call__

 def __call__(self):
     self.items = queue.Queue()
     auth = OAuthHandler(mykeys.ckey, mykeys.csecret)
     auth.set_access_token(mykeys.atoken, mykeys.asecret)
     self.stream = Stream(auth, self)
     self.stream.filter(track=self.terms, async=True)
     return self
开发者ID:IBMStreams,项目名称:streamsx.topology,代码行数:7,代码来源:tweets.py

示例5: run

    def run(self):
        l = StdOutListener(self)
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)

        stream = Stream(auth, l)
        stream.filter(track=self.tags, languages=['en'])
开发者ID:jbulter,项目名称:Twitter_Stream,代码行数:7,代码来源:twitter_sink.py

示例6: unwrapped_callback

    def unwrapped_callback(self, resp):
        if resp is None:
            raise LoginCallbackError(_("You denied the request to login"))

        # Try to read more from the user's Twitter profile
        auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
        auth.set_access_token(resp['oauth_token'], resp['oauth_token_secret'])
        api = TwitterAPI(auth)
        try:
            twinfo = api.verify_credentials(include_entities='false', skip_status='true', include_email='true')
            fullname = twinfo.name
            avatar_url = twinfo.profile_image_url_https.replace('_normal.', '_bigger.')
            email = getattr(twinfo, 'email', None)
        except TweepError:
            fullname = None
            avatar_url = None
            email = None

        return {'email': email,
                'userid': resp['user_id'],
                'username': resp['screen_name'],
                'fullname': fullname,
                'avatar_url': avatar_url,
                'oauth_token': resp['oauth_token'],
                'oauth_token_secret': resp['oauth_token_secret'],
                'oauth_token_type': None,  # Twitter doesn't have token types
                }
开发者ID:hasgeek,项目名称:lastuser,代码行数:27,代码来源:twitter.py

示例7: __init__

    def __init__(self,slacker):

        # auth
        auth = OAuthHandler(settings.twitter_consumer_key, settings.twitter_consumer_secret)
        auth.set_access_token(settings.twitter_access_token, settings.twitter_access_token_secret)

        # out
        l = StdOutListener(slacker)

        # stream
        stream = Stream(auth, l)
        print("opening twitter stream")
        # if only a certain list
        if FILTER_LIST:
            api = API(auth)
            employees = api.list_members(LIST_USER,LIST)
            list = map(lambda val: str(val),employees.ids())
            #print(list)
            print("only List: "+LIST)
            stream.filter(follow=list)
        elif FILTER_KEYWORDS:
            print("only Keywords: "+str(KEYWORDS))
            stream.filter(track=KEYWORDS)
        else:
            print("your timeline")
            stream.userstream()
开发者ID:ixds,项目名称:twitterStreamToSlack,代码行数:26,代码来源:twitter.py

示例8: init_api

 def init_api(self):
     oauth_handler = TweepyOAuthHandler(self._consumer_key,
                                        self._consumer_secret,
                                        secure=configuration.twitter['use_https'])
     oauth_handler.set_access_token(self._access_token_key,
                                    self._access_token_secret)
     self._api = BaseTweepyApi(oauth_handler, secure=configuration.twitter['use_https'])
开发者ID:floppym,项目名称:turses,代码行数:7,代码来源:backends.py

示例9: IRCListener

class IRCListener(StreamListener):

    def __init__(self, config, bot):
        self.bot = bot

        self.auth = OAuthHandler(config["auth"]["consumer_key"], config["auth"]["consumer_secret"])
        self.auth.set_access_token(config["auth"]["access_token"], config["auth"]["access_token_secret"])

        api = tweepy.API(self.auth)

        stream = Stream(self.auth, self)

        self.users = [str(api.get_user(u).id) for u in config["follow"]]
        stream.filter(follow=self.users, async=True)

        log.debug("a twitter.IRCListener instance created")

    def on_data(self, data):
        parsed = json.loads(data)
        if "text" in parsed and parsed["user"]["id_str"] in self.users:
            # TODO: use Twisted color formatting
            ourtweeter = parsed["user"]["name"]
            ourtweet = parsed["text"]
            statusLinkPart = " - https://twitter.com/" + parsed["user"]["screen_name"] + "/status/" + parsed["id_str"]
            self.bot.announce(ourtweeter, " tweeted ", ourtweet, statusLinkPart, specialColors=(None, None, attributes.fg.blue, None))
        return True

    def on_error(self, status):
        log.debug("Twitter error: " + str(status))
开发者ID:aa-m-sa,项目名称:boxbot,代码行数:29,代码来源:twitter.py

示例10: main

 def main(self):
     #twitter authorization
     auth = OAuthHandler(AuthDetails.consumer_key, AuthDetails.consumer_secret)
     auth.set_access_token(AuthDetails.access_token, AuthDetails.access_token_secret)
     language = 'en'
     pt = ProcessTweet()
     searchTerm = pt.unicodetostring(self.searchTerm)
     stopAt = pt.unicodetostring(self.stopAt)
     #calls method to train the classfier
     tr = Training()
     (priors, likelihood) = tr.starttraining()
     #stream tweets from twitter
     twitterStream = Stream(auth, Listener(searchTerm, stopAt))
     twitterStream.filter(track=[searchTerm], languages=[language])
     sen = Sentiment()
     sentiment_tally = Counter()
     (sentiment_tally, tweet_list) = sen.gettweetstoanalyse(priors, likelihood, searchTerm)
     tr = Training()
     sen = Sentiment()
     (neutral, positive, negative) = sen.analyse(sentiment_tally)
     tweet_list = self.edittweetlists(tweet_list)
     #truncate streamtweets table
     self.removetweetsfromdatabase()
     #save training data
     tr.savetrainingdatatodb(priors, likelihood)
     return (neutral, positive, negative, tweet_list)
开发者ID:dmaher,项目名称:NaiveBayesSentimentAnalysis,代码行数:26,代码来源:run.py

示例11: TwitterPlayer

class TwitterPlayer(player.Player):
    def __init__(self, model, code, access_token, access_token_secret, opponent):
        player.Player.__init__(self, model, code)
        self._opponent = opponent
        self._last_id = None

        self._auth = OAuthHandler(auth.consumer_key, auth.consumer_secret)
        self._auth.set_access_token(access_token, access_token_secret)
        self._api = API(self._auth)
        self._listener = TwitterListener(self, self._api)
        self._stream = Stream(self._auth, self._listener)

    @property
    def username(self):
        return self._auth.get_username()

    def allow(self):
        print 'This is the opponent\'s turn...'
        self._stream.userstream()

    def update(self, event):
        if event.player == self.code:
            return
        message = '@%s %s' % (self._opponent, self._model.events[-1][1])
        self.tweet(message)

    def tweet(self, message):
        if self._last_id is None:
            self._api.update_status(message)
        else:
            self._api.update_status(message, self._last_id)
开发者ID:benijake,项目名称:twishogi,代码行数:31,代码来源:player.py

示例12: _request_tweets

    def _request_tweets(self, search_word, since_id):
        auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        auth.set_access_token(self.access_token, self.access_secret)

        tweets = []
        api = tweepy.API(auth)
        max_id = None
        new_since_id = None
        total = 0
        logger.info("start search by %s" % search_word)
        while True:
            tweets_batch = api.search(search_word, max_id=max_id, since_id=since_id)
            logger.info("get " + str(len(tweets_batch)) + " tweets by '" + search_word + "'")
            if not new_since_id: new_since_id = tweets_batch.since_id
            if max_id == tweets_batch.max_id: break

            max_id = tweets_batch.max_id
            total += len(tweets_batch)

            for tweet in tweets_batch:
                tweets.append(tweet._json)

            if not max_id:
                break

        logger.info("done with search found %s new tweets" % total)
        return new_since_id, tweets
开发者ID:mishadev,项目名称:stuff,代码行数:27,代码来源:dataproviders.py

示例13: process

    def process(self, statement):
        confidence = self.classifier.classify(statement.text.lower())
        tokens = nltk.word_tokenize(str(statement))
        tagged = nltk.pos_tag(tokens)
        nouns = [word for word, pos in tagged if
                 (pos == 'NN' or pos == 'NNP' or pos =='JJ' or pos == 'NNS' or pos == 'NNPS')]
        downcased = [x.lower() for x in nouns]
        searchTerm = " ".join(downcased).encode('utf-8')
        #"http://where.yahooapis.com/v1/places.q('Place name')?appid=yourappidhere"
        st=""
        if len(nouns) != 0:
            auth = OAuthHandler(twitter_consumer_key, twitter_consumer_secret)
            auth.set_access_token(twitter_access_key, twitter_access_secret)

            api = tweepy.API(auth)
            for status in tweepy.Cursor(api.search, q='#'+searchTerm).items(20):
                st = st+status.text
            response = Statement("Jarvis: "+st)
        else:
            response = Statement("Jarvis: "+"Sorry sir, Nothing Found")
        return confidence, response


#what's trending in city
#movie reviews
#people talking about some topic
开发者ID:anirudh24,项目名称:self_aware_bot,代码行数:26,代码来源:tweet_tag.py

示例14: run_twitter_query

def run_twitter_query():
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)
    #names = list(np.array(get_companies())[:,1])
    #print names[num1:num2]
    d = hand_made_list()
    search_list = []
    for key, value in d.items():
        if key == 'SPY':
            search_list.append(value[0]) # append the full anme of the symbol
            search_list.append('#SP500') # Don't append #SPY because it's not helpful
            search_list.append('$SP500')
        elif key == 'F':
            # search_list.append(value[0]) # append the full name of the symbol
            search_list.append('Ford') # append the name of the symbol
        elif key == 'GE':
            search_list.append('General Electric') # append the full anme of the symbol
        elif key == 'S':
            search_list.append('Sprint') # append the full anme of the symbol
        elif key == 'T':
            search_list.append('AT&T') # append the full anme of the symbol
        elif key == 'MU':
            search_list.append('Micron Tech') # append the full anme of the symbol
        elif key == 'TRI':
            search_list.append('Thomson Reuters') # append the full anme of the symbol
        else:
            for cell in value:
                search_list.append(cell)

    stream.filter(track=search_list)
开发者ID:gravity226,项目名称:NASDAQ,代码行数:32,代码来源:save_stock_tweets.py

示例15: get_tweets

def get_tweets():
    access_token,access_secret,consumer_key,consumer_secret = read_config()
    auth = OAuthHandler(consumer_key,consumer_secret)
    auth.set_access_token(access_token,access_secret)
    global hashes
    count = 0
    api = tweepy.API(auth)
    hashes = hashes.replace("'","").split(",")
    for hashtag in hashes:
        tweets = api.search(hashtag)
        for tweet in tweets:
            #print tweet.text
            twitter_json = {}
            twitter_json["created_at"] = str(tweet.created_at)
            twitter_json["caption"] = tweet.text
            twitter_json["username"] = tweet.user.name
            twitter_json["thumbs"] = sentiment.check_sentiments(tweet.text)
            twitter_json["source"] = "twitter"
            twitter_json["link"] = "https://twitter.com/"+str(tweet.user.screen_name)+"/status/"+str(tweet.id)
            print twitter_json["link"]
            if 'media' in tweet.entities:
                twitter_json["url"] = tweet.entities['media'][0]['media_url']
            else:
                twitter_json["url"] = ""
            push_mongo(twitter_json)
开发者ID:xgt001,项目名称:infinite_feed,代码行数:25,代码来源:twitter_feed.py


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