Beispiel #1
0
    def get_stream(self):
        queue_module = self.get_config_default('tweets-client', 'track-module',
                                               'tweetsclient.config_track')
        queue_class = self.get_config_default('tweets-client', 'track-class',
                                              'ConfigTrackPlugin')
        log.debug("Loading track plugin: {module} - {klass}",
                  module=queue_module,
                  klass=queue_class)

        pluginClass = self.load_plugin(queue_module, queue_class)
        self.track = pluginClass()
        #self.track = tweetsclient.MySQLTrackPlugin({'verbose': self.verbose})
        # self.track = tweetsclient.ConfigTrackPlugin({'verbose': self.verbose})
        stream_type = self.track.get_type()
        log.debug("Initializing a {0} stream of tweets.", stream_type)
        track_items = self.track.get_items()
        log.debug(str(track_items))
        stream = None
        if stream_type == 'users':
            stream = tweetstream.FilterStream(self.user, self.passwd,
                                              track_items)
        elif stream_type == 'words':
            stream = tweetstream.TrackStream(self.user, self.passwd,
                                             track_items)
        else:
            stream = tweetstream.TweetStream(self.user, self.passwd)
        return stream
 def start(self):
     """Attach to the IOLoop."""
     self._tweetstream = tweetstream.TweetStream(
         ioloop=self._ioloop, configuration=self._configuration)
     self._tweetstream.set_error_callback(self._error)
     self._tweetstream.fetch("/1/statuses/filter.json?track=%s" %
                             self._twitter_search_term,
                             callback=self.extract_from_tweet)
Beispiel #3
0
    def start(self, filter=False):
        self._dbconnect()

        while True:
            self.stream = tweetstream.TweetStream(TWITTER_USER, TWITTER_PASS)

            for tweet in self.stream:
                if not 'geo' in tweet or not tweet['geo']:
                    continue
                self.analyzer.analyze_tweet(tweet)
def main():

    socket._fileobject.default_bufsize = 0

    # Did they provide the correct args?
    if len(sys.argv) != 4:
        usage()
        sys.exit(-1)

    max = int(sys.argv[1])
    output = sys.argv[2]
    file_kill = sys.argv[3]

    # --------------------------------------------------------------------------
    # Grab sample stream of tweets, likely only 1% of all tweets.

    count = 0

    try:
        with codecs.open(output, "w", 'utf-8') as f:
            with tweetstream.TweetStream("profoundalias",
                                         "tschusisgerman1") as stream:
                for tweet in stream:
                    if os.path.exists(file_kill):
                        print "prematurely killing"
                        break

                    if "user" in tweet:
                        print "Got tweet from %-16s\t(tweet %d, rate %.1f tweets/sec)" \
                            % (tweet["user"]["screen_name"], stream.count, stream.rate)

                        if "retweeted_status" in tweet:
                            pass
                        else:
                            f.write(tx.status_str_from_dict(tweet) + u"\n")
                            f.flush()
                            count += 1

                        if count > max:
                            break

    except tweetstream.ConnectionError, e:
        print "Disconnected from twitter. Reason:", e.reason
Beispiel #5
0
    def main(self):
        i = 0
        s = sched.scheduler(time.time, time.sleep)
        output = self.filepath

        #Grab every tweet using Streaming API
        with tweetstream.TweetStream(self.uname, self.password) as stream:
            for tweet in stream:
                if tweet.has_key("text"):
                    try:
                        #Write tweet to file and print it to STDOUT
                        message = tweet['text'] + "\n"
                        output.write(message)
                        print tweet['user']['screen_name'] + ": " + tweet[
                            'text'], "\n"

                        ################################
                        #Timestamp code
                        #Timestamps should be placed once every hour
                        s.enter(10, 1, t.timestamp, (s, ))
                        s.run()
                    except KeyError:
                        pass
Beispiel #6
0
    for client in clients:
        client.write_message(tweet)


if 'TWITTER_ACCESS_TOKEN' in os.environ:
    tweetstream_config = {
        "twitter_consumer_key": os.environ["TWITTER_CONSUMER_KEY"],
        "twitter_consumer_secret": os.environ["TWITTER_CONSUMER_SECRET"],
        "twitter_access_token": os.environ["TWITTER_ACCESS_TOKEN"],
        "twitter_access_token_secret":
        os.environ["TWITTER_ACCESS_TOKEN_SECRET"],
    }

    params = {'track': '#twitter'}

    stream = tweetstream.TweetStream(tweetstream_config)
    stream.fetch("/1.1/statuses/filter.json?" + urlencode(params),
                 callback=tweetstream_callback)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        with open('static/index.html') as f:
            self.write(f.read())


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        self.stream.set_nodelay(True)
        clients.add(self)
Beispiel #7
0
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs
from Phidgets.Devices.TextLCD import TextLCD, TextLCD_ScreenSize

# for twitter

import tweetstream
import json
import urllib2
import re

USER = "******"
PASSWORD = "******"
SEARCHTERM = "royalwedding"

stream = tweetstream.TweetStream(USER, PASSWORD)

#Create an TextLCD object
try:
    textLCD = TextLCD()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)


#Information Display Function
def DisplayDeviceInfo():
    try:
        isAttached = textLCD.isAttached()
        name = textLCD.getDeviceName()
Beispiel #8
0
import tweetstream

twitterUsername = "******"
twitterPassword = "******"
try:
    with tweetstream.TweetStream(twitterUsername, twitterPassword) as stream:
        for tweet in stream:
            try:
                print stream.count, "(", stream.rate, "tweets/sec). ", tweet[
                    'user']['screen_name'], ':', tweet['text'].encode('utf-8')
                #print tweet #Use for raw output
            except:
                print "ERROR: Presumably missing field"

except tweetstream.ConnectionError, e:
    print "Disconnected from twitter. Reason:", e.reason
Beispiel #9
0
                      int(allowance / price)))
            break
        else:
            print(f'Buying contracts {quantity} @ {price}')
            allowance = allowance - quantity * price
            print(f'Still need to buy: {allowance}')
            print(p.buy(short_contract, int(price * 100), quantity))
            print('Remaining allowance: {allowance}')
        time.sleep(1)

    #p.buy_no(short_contract, )


key, secret = ts.load_keys('../etc/api.txt')
start_ts = datetime.datetime.strptime('Aug 28 2019 16:00', '%b %d %Y %H:%M')
ts = ts.TweetStream(start_ts, key, secret)
ts.set_callback(callback)
ts.run()

#callback(None)
#p.buy_no('16805', 59, 1)
'''
ws = piws.PredictItWebSocket()
ws.set_queue_callback(callback)
ws.set_contract_stats_filter(lambda c: not (c == '16805' or c == '16808'))
asyncio.get_event_loop().run_until_complete(ws.start())
'''

# Need to place two orders:
# A no order on the contract we are shorting
# and a yes order on the contract we're long on