How to use the twython.TwythonStreamer function in twython

To help you get started, we’ve selected a few twython examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github andyikchu / insightproject / inputdata / twitter_stream.py View on Github external
#from twython import Twython
from twython import TwythonStreamer
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()

#TODO: load from external file for all producers
COMPANIES = ["MMM", "AXP", "AAPL", "BA", "CAT", "CVX", "CSCO", "KO", "DD", "XOM", "GE", "GS", "HD", "INTC", "IBM", "JNJ", "JPM", "MCD", "MRK", "MSFT", "NKE", "PFE", "PG", "TRV", "UNH", "UTX", "VZ", "V", "WMT", "DIS"]

COMPANIES = list('$' + company for company in COMPANIES)

keyfile = open("/home/ubuntu/.twitterkeys/keys.txt", "r")
TWITTERKEYS = dict(line.rstrip().split(": ") for line in keyfile)
keyfile.close()

class NewsStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            print data['text'].encode('utf-8') + data['timestamp_ms'] + str(data['id'])
    def on_error(self, status_code, data):
        print "error" + str(status_code)

stream = NewsStreamer(TWITTERKEYS['consumer key'], TWITTERKEYS['consumer secret'], TWITTERKEYS['access token'], TWITTERKEYS['access token secret'])

stream.statuses.filter(filter_level = 'medium', language='en', track=','.join(COMPANIES))
github quip / quip-api / samples / twitterbot / twitterbot.py View on Github external
"""

import argparse
import logging
import quip
import twython

ACCESS_TOKEN = ""

TWITTER_API_KEY = ""
TWITTER_API_SECRET = ""
TWITTER_ACCESS_TOKEN = ""
TWITTER_ACCESS_SECRET = ""


class TwitterBot(twython.TwythonStreamer):
    def __init__(self, thread_id, quip_api_base_url):
        self.quip_client = quip.QuipClient(
            access_token=ACCESS_TOKEN, base_url=quip_api_base_url)
        self.thread_id = thread_id
        super(TwitterBot, self).__init__(
            TWITTER_API_KEY, TWITTER_API_SECRET,
            TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET)

    def on_success(self, data):
        name = data["user"]["name"]
        screen_name = data["user"]["screen_name"]
        text = _format_status_text(data)
        url = "https://twitter.com/%s/status/%s" % (screen_name, data["id_str"])
        message = "%s (@%s) tweeted: %s\n%s" % (name, screen_name, text, url)
        try:
            self.quip_client.new_message(self.thread_id, message, silent=True)
github fritzr / discord-twitter-bot / DiscordTwitterBot.py View on Github external
def ident(x): return x
    if key is None: key = ident
    def compare(x, y): return x < y
    if cmp is None: cmp = compare

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if cmp(key(a[mid]), key(x)): lo = mid+1
        else: hi = mid
    return lo

class TwitterUserStream(TwythonStreamer):
    """Stream tweets from a user's Twitter feed. Whenever a tweet is
received on the stream, each function in callbacks will be called with the
Twitter response data as the argument.

Note that the Twitter API may deliver messages out of order and may deliver repeat
messages. Use the 'show_dupes' property to control whether duplicate messages are
reported to the callbacks. The 'store' property controls how many of the most
recent messages to store."""
    def __init__(self, user=None, callbacks=[], show_dupes=False, store=10):
        self.data = Storage()
        super(TwitterUserStream, self).__init__(*self.data.twitter)
        self.twitter = Twython(*self.data.twitter)

        self.error = "" # text of last error
        self._errors = 0
        self._max_errors = 5
github pybites / 100DaysOfCode / 020 / domain_mentions.py View on Github external
def create_post(data):
    tweet_text = data['text']
    tweet_id = data['id_str']
    user = data['user']['screen_name']
    name = data['user']['name']
    followers = data['user']['followers_count']
    return MSG.format(domain='.'.join(DOMAIN),
                      user=user,
                      name=name,
                      followers=followers,
                      tweet_text=tweet_text,
                      tweet_id=tweet_id)


class MyStreamer(TwythonStreamer):
    ''' https://twython.readthedocs.io/en/latest/usage/streaming_api.html '''

    def on_success(self, data):
        post = create_post(data)
        logging.debug(post)
        try:
            slack.chat.post_message(CHANNEL, post, as_user=True)
        except Exception as exc:
            logging.error('\nOH NO!')
            logging.error('an exception occurred in slack.chat.post_message({}, {}, as_user=True)'.format(CHANNEL, post))
            logging.error('exception raised by slack API was:\n{}\n'.format(exc))

    def on_error(self, status_code, data):
        print('An error occurred: {}, exiting'.format(status_code))
        self.disconnect()
github projectsapollo / ISS_Arthur / pi_code.py View on Github external
# GPIO pin number of LED
LED = 36

GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, GPIO.LOW)



# Twitter application authentication
APP_KEY = 'YourTwitterInfoHere'
APP_SECRET = 'YourTwitterInfoHere'
OAUTH_TOKEN = 'YourTwitterInfoHere'
OAUTH_TOKEN_SECRET = 'YourTwitterInfoHere'

# Setup callbacks from Twython Streamer
class BlinkyStreamer(TwythonStreamer):
        def on_success(self, data):
                if 'text' in data:
                        print data['text'].encode('utf-8')
                        print
                        i=0
                        while i < 20:
                        	GPIO.output(LED,1)
                         	time.sleep(0.5)
                         	GPIO.output(LED,0)
                         	time.sleep(0.5)
                         	i = i + 1




# Create streamer
github dasfaha / twitter-location / TwitterLocationFilter.py View on Github external
#Only the south west and north east coner matter
#Broader scope
#Latitude, Longitude
#51.518918,-0.076518
#Latitude, Longitude
#51.523591,-0.066133


from twython import TwythonStreamer
#io library for streaming data to a file
import io
import json
#twitter stream filter takes a polygon with southwest corner first , coordinates in geoJSON so (long, lat)
brick_lane_polygon ='-0.076518,51.518918,-0.066133,51.523591'

class MyStreamer(TwythonStreamer):
    def __init__(self, *kargs, **kwargs):
        self.f = open('brickLaneStream.log', 'a')
        TwythonStreamer.__init__(self, *kargs, **kwargs)
    def on_success(self, data):
        if 'text' in data:
            txt_val = json.dumps(data)
            self.f.write(txt_val.decode('utf-8') + '\n')
            print "Sending to file:", data['text'].encode('utf-8')
        elif 'warning' in data:
            self.f.write(json.dumps(data).encode('utf-8') + '\n')
            
    def on_error(self, status_code, data):
        self.f.write('ERROR: code: {0} - message: {1}\n'.format(status_code, data))


if __name__ == '__main__':
github pyaiot / pyaiot / utils / twitter / riot-twitter.py View on Github external
if message is None:
        request = Message(code=POST, payload="Hello Twitter".encode('utf-8'))
        request.set_request_uri('coap://localhost/alive')
    else:
        request = Message(code=POST,
                          payload="twitter:{}".format(message).encode('utf-8'))
        request.set_request_uri('coap://localhost/server')

    try:
        yield from protocol.request(request).response
    except Exception as e:
        print('Failed to fetch resource:')
        print(e)


class RiotTwitterStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            asyncio.get_event_loop().run_until_complete(
                coap_message(data['text'].replace('\n', ' ')))

    def on_error(self, status_code, data):
        print(status_code)

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(coap_message())
    stream = RiotTwitterStreamer(APP_KEY, APP_SECRET,
                                 OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    stream.statuses.filter(track='RIOT-OS')
github MarkAYoder / BeagleBoard-exercises / python / twitter / TweetBlinky / TweetBlinky.py View on Github external
from twython import TwythonStreamer

# Search terms
TERMS = '#ASEERosEval2014'

# GPIO pin number of LED
LED = "P9_12"

# Twitter application authentication
APP_KEY = 'D3PuaQNFRYAtNVKXPppmw'
APP_SECRET = 'nG8zoU8MvR2bGre2UfWbW9vhBgRGRkB9kQCQ1wrXqY'
OAUTH_TOKEN = '48435578-fCNrU1hHOI1hgescqTkXm7aKAeMpGvi0yYTNtYpoV'
OAUTH_TOKEN_SECRET = 'YvGHOIkvfz81ZsMvtcKJ7G9iLidanFzM4nW3QpGOOfaFC'

# Setup callbacks from Twython Streamer
class BlinkyStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
	    print data['text'].encode('utf-8')
	    print
	    GPIO.output(LED, GPIO.HIGH)
	    time.sleep(0.5)
	    GPIO.output(LED, GPIO.LOW)

# Setup GPIO as output
# GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, GPIO.LOW)

# Create streamer
try:
    stream = BlinkyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
github Zedsquared / NixieBot / nixiebot.py View on Github external
if (status_code == 420) :
            print("***************** filter is rate limited!" )
            print("*****************sleeping for" + str(self.backOffTime) )
            for i in range (1,int(self.backOffTime / 10)) :
                if running :
                    time.sleep(10)
                else :
                    break
            if self.backOffTime < 1200 :
                self.backOffTime = self.backOffTime * 2
        # Want to stop trying to get data because of the error?
        # Uncomment the next line!
        #self.disconnect()

        
class randomStreamer(TwythonStreamer):
    backOffTime = 60
    global randq
    global onlyOriginalRandoms
    
    def on_success(self, data):
        global originalTweets
        global reTweets
        global onlyOriginalRandoms
        global dequeHold
        if 'text' in data:
            if killURLs :
                data['text'] = killURL(data)
            isOriginal = not ('retweeted_status' in data)
            if log_level >=4 :
                print ("incoming Random, deque at: " + str(len(recentTweetDeque)) + "  " + data['text'])
            if not dequeHold :