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


Python tweepy.Stream类代码示例

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


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

示例1: main

def main():
#    dirname = os.path.dirname(inspect.getfile(inspect.currentframe()))
#    basename = os.path.basename(inspect.getfile(inspect.currentframe()))
    dirname = os.path.dirname(os.path.realpath(__file__))
    basename = os.path.basename(os.path.realpath(__file__))
    name_noextension = os.path.splitext(basename)[0]
    """Start log."""
    configinput = __import__("config" + name_noextension)
    outputDir = os.path.join(dirname, configinput.directory)
    if not os.path.exists(outputDir):
        os.makedirs(outputDir)
    logfilename = os.path.join(outputDir,basename) + ".log"
    logging.basicConfig(filename=logfilename,level=logging.DEBUG, format='%(asctime)s %(message)s')
    logging.info('Started')
    save_pid()


    """Execute the twitter api."""
    try:
        auth = OAuthHandler(configinput.consumer_key, configinput.consumer_secret)
        auth.set_access_token(configinput.access_token, configinput.access_secret)
        twitter_stream = Stream(auth, MyListener(os.path.join(dirname, configinput.directory), os.path.join(dirname, configinput.to_dir), basename))   # el segundo argumento es el nombre del archibvo json
        twitter_stream.filter(track=configinput.keyword_list_filter)
    except BaseException as e:
        logging.error('Failed to execute twitter api: ' + str(e))    
    
    logging.info('Finished')
开发者ID:amador2001,项目名称:ObservatorioHF,代码行数:27,代码来源:input.py

示例2: stream_twitter

def stream_twitter(battle_id):
    #Avoiding circular import
    from battle.models import Battle

    battle = Battle.objects.get(id=battle_id)
    if battle.end_time < timezone.now():
        return

    battle.battlehashtags_set.update(typos=0, words=0)
    battle_hashtags = battle.battlehashtags_set.all().prefetch_related('hashtag')
    if battle_hashtags.count() == 0:
        return

    hashtag_values = [x.hashtag.value for x in battle_hashtags]

    listener = TwitterStreamListener(battle_hashtags)
    auth = OAuthHandler(
        settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET
    )

    auth.set_access_token(
        settings.TWITTER_ACCESS_TOKEN,
        settings.TWITTER_ACCESS_TOKEN_SECRET
    )

    stream = Stream(auth, listener)

    delay = battle.end_time - timezone.now()
    Timer(delay.total_seconds(), stream.disconnect).start()

    stream.filter(track=hashtag_values, languages=['en'])
开发者ID:bestan,项目名称:battle-hashtags,代码行数:32,代码来源:tasks.py

示例3: Streamer

class Streamer( object ):

	def __init__( self, queue, terms=[], consumer=None, consumer_secret=None,
			token=None, secret=None):

		if consumer == None or consumer_secret == None or token == None or secret == None:
			config = configparser.ConfigParser()
			config.readfp( open( os.path.expanduser( "~/.slackTwitter" ) ) )

			consumer = config.get( "twitter", "consumer" )
			consumer_secret = config.get( "twitter", "consumer_secret" )
			token = config.get( "twitter", "token" )
			secret = config.get( "twitter", "secret" )

		auth = OAuthHandler( consumer, consumer_secret )
		auth.set_access_token( token, secret )

		listener = StreamerListener()
		self.stream = TweepyStream( auth=auth, listener=listener )

		self._queue = queue
		self._terms = terms
	
	def start( self ):
		self.stream.filter( track=self._terms )
开发者ID:streed,项目名称:tweetSchedule,代码行数:25,代码来源:stream.py

示例4: run

 def run(self,user,message):
     if utilities.getCommand() == "autotweet":
         streamListener = ReplyToTweet()
         streamListener.setAPI(self.twitterApi)
         streamListener.setUser(self.account_user_id)
         twitterStream = Stream(self.auth, streamListener)
         twitterStream.userstream(_with='user')
开发者ID:LeStarch,项目名称:AutoAck,代码行数:7,代码来源:Tweet.py

示例5: main

def main():
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    backend = FileBackend("./test-db")
    stream = Stream(auth, l)
    stream.filter(track=['トレクル'])
开发者ID:gosu-clan,项目名称:twanki,代码行数:7,代码来源:twanki.py

示例6: minetweets

def minetweets():
    line = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, line)
    # stream.filter(track=['Watson', 'Cognitive', 'Machine Learning'])
    stream.filter(track=args, languages=["en"])
开发者ID:agrimrules,项目名称:SocialAnalytics,代码行数:7,代码来源:socialPy.py

示例7: 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

示例8: StreamConsumerThreadClass

class StreamConsumerThreadClass(threading.Thread):
    def __init__(self,term='',oauthfile=''):
        threading.Thread.__init__(self)
        self.searchterm = term
        self.name = term
        self.consume = True
        
        oauth = json.loads(open(oauthfile,'r').read())
        
        listener = MongoDBListener()
        auth = OAuthHandler(oauth['consumer_key'], oauth['consumer_secret'])
        auth.set_access_token(oauth['access_token'], oauth['access_token_secret'])
    
        self.stream = Stream(auth, listener,timeout=60)  
        
        
    def stopConsume(self):
        self.stream.disconnect()
      
    def run(self):
        now = datetime.datetime.now()
        print "Twitter Stream with terms: %s started at: %s" % (self.getName(), now)
        
        connected = False
        while True:
            try: 
                if not connected:
                    connected = True
                    self.stream.filter(track=[self.searchterm])
            except SSLError, e:
                print e
                connected = False            
开发者ID:arianpasquali,项目名称:twitterstream-to-mongodb,代码行数:32,代码来源:twitterstreamtomongodb.py

示例9: main

def main(argv):
    query = ""
    try:
        opts, args = getopt.getopt(argv, "helps:w:i:", ["query="])
    except getopt.GetoptError:
        print ("stream.py --query <query>")
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print ("stream.py --query <query>")
            sys.exit()
        elif opt in ("-q", "--query"):
            query = arg


    array = []
    with open("keys.txt", "r") as ins:
        for line in ins:
            array.append(line.rstrip('\n'))
    l = StdOutListener()
    auth = OAuthHandler(array[0], array[1])
    auth.set_access_token(array[2], array[3])

    stream = Stream(auth, l)
    stream.filter(track=[query])
开发者ID:c0cky,项目名称:wandrlust_twitter_harvester,代码行数:26,代码来源:stream.py

示例10: run

def run(track_list):
    listener = StdOutListener()
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
     
    stream = Stream(auth, listener)
    stream.filter(track=track_list)
开发者ID:myf,项目名称:Twitter_Hack,代码行数:7,代码来源:stream_api.py

示例11: stream_users

def stream_users(in_file, auth):    
    screen_names = [x.strip() for x in in_file]
    
    tw_list = user_ids(screen_names, auth)
    
    twitterStream = Stream(auth, Listener())
    twitterStream.filter(follow=tw_list)
开发者ID:leosquared,项目名称:tweet_tracker,代码行数:7,代码来源:senate_tweets.py

示例12: get_streaming_data

    def get_streaming_data(self):
        tweets_grabbed = 0
        while (tweets_grabbed < self.num_tweets_to_grab):
            twitterStream = Stream(self.auth, listener(self.s, self.twit_utils, self.num_tweets_to_grab, self.retweet_count))
            try:               
                twitterStream.sample()
            except Exception as e:
                    print("Error. Restarting Stream.... Error: ")
                    print(e.__doc__)
                    #print(e.message)
                    print("Le Error! Restart")
                    time.sleep(3) # Sleep for 5 minutes if error ocurred
            finally:
                tweets_grabbed = self.s.get_tweets_grabbed()
                print("tweets_grabbed = ", tweets_grabbed)

        lang, top_lang,love_words, swear_words, top_tweets, countries = self.s.get_stats()

        print(Counter(lang))
        print(Counter(top_lang))
        print("Love Words {} Swear Words {}".format(love_words, swear_words))
        print(Counter(countries))

        self.c.execute("INSERT INTO lang_data VALUES (?,?, DATETIME('now'))", (str(list(Counter(lang).items())), str(list(Counter(top_lang).items()))))

        self.c.execute("INSERT INTO love_data VALUES (?,?, DATETIME('now'))", (love_words, swear_words))

        for t in top_tweets:
            self.c.execute("INSERT INTO twit_data VALUES (?, DATETIME('now'))", (t,))

        self.c.execute("INSERT INTO country_data VALUES (?, DATETIME('now'))", (str(list(Counter(countries).items())),))

        self.conn.commit()
开发者ID:shantnu,项目名称:TwitPy,代码行数:33,代码来源:twit.py

示例13: run

    def run(self):
        global streamobj
        streamobj = Stream(self.auth, self.listener)

        #LOCATION OF USA = [-124.85, 24.39, -66.88, 49.38,] filter tweets from the USA, and are written in English
        streamobj.filter(locations = [-124.85, 24.39, -66.88, 49.38,], languages=['en'])
        return
开发者ID:tweetbot,项目名称:tweetbot,代码行数:7,代码来源:tweetbot.py

示例14: setup_streams

def setup_streams(auth):
    twitter_list = WBListener()
    #twitter_list2 = WBListener()
    global stream_obj

    stream_obj = Stream(auth, twitter_list)
    stream_obj.filter(track=['#trump'], async=True)
开发者ID:YoungMaker,项目名称:TwitterWhiteboard,代码行数:7,代码来源:twitter.py

示例15: startListen

    def startListen(self):
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
 
        stream = Stream(auth, self)
#     stream.filter(track=[positiveEmoticons])
        stream.filter(locations = [113.90625,-43.665217,157.148438,-13.35399])
开发者ID:s3341458,项目名称:python_twitter_analysis,代码行数:7,代码来源:Crawler.py


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