本文整理汇总了Python中tweepy.Stream类的典型用法代码示例。如果您正苦于以下问题:Python Stream类的具体用法?Python Stream怎么用?Python Stream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Stream类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: get_tweets
def get_tweets(cls, keyword):
global tweet_file
# get the auth
auth = cls.get_auth()
# define the listener
listener = StdOutListener()
# define stream object
stream = Stream(auth, listener)
# define the api object
api = tweepy.API(auth)
current_milli_time = str(int(round(time.time() * 1000)))
# open a file to write tweets
tweet_file = open(keyword+'_'+current_milli_time+'.txt', 'a')
try:
# get past tweets, max 500
result = tweepy.Cursor(api.search, q=keyword).items(10)
for tweet in result:
tweet_file.write(tweet.text.encode("UTF-8"))
tweet_file.write('\n')
#pprint(tweet)
# Close the file
# tweet_file.close()
# run live feeds
stream.filter(track=[keyword])
except Exception as ex:
print(ex.message, ex)
finally:
tweet_file.close()
开发者ID:gouravshenoy,项目名称:Twitter-Text-Analysis,代码行数:35,代码来源:twitter_feeds.py
示例17: main
def main():
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
if not file_exist('db_tweet.csv'):
cabecalho('db_tweet.csv')
twitterStream.filter(locations=[-46.825390,-24.008381,-46.364830,-23.357611])
开发者ID:davirussi,项目名称:twitter_proj,代码行数:7,代码来源:main.py
示例18: __init__
class TweetController:
"""docstring for Controller"""
def __init__(self):
self.settings = Settings()
# self.auth = OAuthHandler(Listener.api_data["consumer_key"], Listener.api_data["consumer_secret"])
# self.auth.set_access_token(Listener.api_data["access_token"], Listener.api_data["access_token_secret"])
self.api = tweepy.API(self.settings.auth, parser=tweepy.parsers.JSONParser())
self.db = DataBase()
# self.tweet_gui = tweet_gui
self.default_keyword = ['Obama', 'hillary ', 'Trump']
self.db.create_table_if_not_exist()
def start_stream(self):
self.tweet_listener = Listener()
self.stream = Stream(auth=self.settings.auth, listener=self.tweet_listener)
self.stream.filter(track=self.default_keyword, async=True)
def stop_stream(self):
self.stream.disconnect()
def set_keyword(self, default_keyword):
self.default_keyword = default_keyword
print(default_keyword)
开发者ID:sevmardi,项目名称:Twitter-Sentiment-Analysis,代码行数:25,代码来源:TweetController.py
示例19: 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
示例20: interactive
def interactive(username=None, password=None, filenames=None):
if not username:
username = raw_input('Username: ').strip()
if not password:
password = getpass("Password: ").strip()
s = Stream(username, password, TWSSBuildClassifierListner())
s.sample()
开发者ID:azizmb,项目名称:TWSS,代码行数:7,代码来源:get_data.py
注:本文中的tweepy.Stream类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论