Ejemplo n.º 1
0
Archivo: login.py Proyecto: somair/halo
def get_profile(access_token_key, access_token_secret, trim=True):
    config = current_app.config
    auth = OAuthHandler(config['TWITTER_CONSUMER_KEY'],
                        config['TWITTER_CONSUMER_SECRET'])
    auth.set_access_token(access_token_key, access_token_secret)
    api = Twitter(auth)
    profile = api.verify_credentials()
    if trim:
        profile = trim_profile(profile)
    return profile
Ejemplo n.º 2
0
def oauth_dance(app_name, consumer_key, consumer_secret, token_filename=None):
    """
    Perform the OAuth dance with some command-line prompts. Return the
    oauth_token and oauth_token_secret.

    Provide the name of your app in `app_name`, your consumer_key, and
    consumer_secret. This function will open a web browser to let the
    user Allow your app to access their Twitter account. PIN
    authentication is used.

    If a token_filename is given, the oauth tokens will be written to
    the file.
    """
    print("Hi there! We're gonna get you all set up to use %s." % app_name)
    twitter = Twitter(auth=OAuth('', '', consumer_key, consumer_secret),
                      format='',
                      api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.request_token())
    print("""
In the web browser window that opens please choose to Allow
access. Copy the PIN number that appears on the next page and paste or
type it here:
""")
    oauth_url = ('http://api.twitter.com/oauth/authorize?oauth_token=' +
                 oauth_token)
    print("Opening: %s\n" % oauth_url)

    try:
        r = webbrowser.open(oauth_url)
        time.sleep(2)  # Sometimes the last command can print some
        # crap. Wait a bit so it doesn't mess up the next
        # prompt.
        if not r:
            raise Exception()
    except:
        print("""
Uh, I couldn't open a browser on your computer. Please go here to get
your PIN:

""" + oauth_url)
    oauth_verifier = _input("Please enter the PIN: ").strip()
    twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, consumer_key,
                                 consumer_secret),
                      format='',
                      api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    if token_filename:
        write_token_file(token_filename, oauth_token, oauth_token_secret)
        print()
        print("That's it! Your authorization keys have been written to %s." %
              (token_filename))
    return oauth_token, oauth_token_secret
Ejemplo n.º 3
0
def main(args=sys.argv[1:]):
    twitter = Twitter(auth=NoAuth(), api_version='1', domain='api.twitter.com')

    if not args:
        print __doc__
        return 1

    screen_name = args[0]

    if args[1:]:
        max_id = args[1]
    else:
        max_id = None

    n_tweets = 0
    while True:
        try:
            tweets_processed, max_id = get_tweets(twitter, screen_name, max_id)
            n_tweets += tweets_processed
            log_debug("Processed %i tweets (max_id %s)" % (n_tweets, max_id))
            if tweets_processed == 0:
                log_debug("That's it, we got all the tweets. Done.")
                break
        except TwitterError, e:
            log_debug(
                "Twitter bailed out. I'm going to sleep a bit then try again")
            sleep(3)
Ejemplo n.º 4
0
    def __init__(self, configFilename):
        self.configFilename = configFilename
        self.config = load_config(self.configFilename)

        global ACTIVE_PREFIXES
        ACTIVE_PREFIXES = PREFIXES[self.config.get('irc', 'prefixes')]

        oauth_file = self.config.get('twitter', 'oauth_token_file')
        if not os.path.exists(oauth_file):
            oauth_dance("IRC Bot", CONSUMER_KEY, CONSUMER_SECRET, oauth_file)
        oauth_token, oauth_secret = read_token_file(oauth_file)

        self.twitter = Twitter(
            auth=OAuth(
                oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET),
            api_version='1',
            domain='api.twitter.com')

        self.irc = irclib.IRC()
        self.irc.add_global_handler('privmsg', self.handle_privmsg)
        self.irc.add_global_handler('ctcp', self.handle_ctcp)
        self.ircServer = self.irc.server()

        self.sched = Scheduler(
            (SchedTask(self.process_events, 1),
             SchedTask(self.check_statuses, 120)))
        self.lastUpdate = (datetime.utcnow() - timedelta(minutes=10)).utctimetuple()
Ejemplo n.º 5
0
def connect_to_twitter():
    '''
    Connect to Twitter Stream API using the API wrapper in stream.py in the following steps:

    Authenticate
    ============
    Authenticate app using OAuth

    Connect
    =======
    Connect to the streaming API using oauth object received from previous step

    Returns authenticated and stream connected Twitter object
    '''
    twitter = Twitter()
    twitter.authenticate()
    twitter.connect()
    return twitter
Ejemplo n.º 6
0
    if options['refresh'] and options['action'] not in ('friends', 'public',
                                                        'replies'):
        print >> sys.stderr, "You can only refresh the friends, public, or replies actions."
        print >> sys.stderr, "Use 'twitter -h' for help."
        return 1

    oauth_filename = os.path.expanduser(options['oauth_filename'])

    if (options['action'] == 'authorize'
            or not os.path.exists(oauth_filename)):
        oauth_dance("the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET,
                    options['oauth_filename'])

    oauth_token, oauth_token_secret = read_token_file(oauth_filename)

    twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY,
                                 CONSUMER_SECRET),
                      secure=options['secure'],
                      api_version='1',
                      domain='api.twitter.com')

    try:
        Action()(twitter, options)
    except NoSuchActionError, e:
        print >> sys.stderr, e
        raise SystemExit(1)
    except TwitterError, e:
        print >> sys.stderr, str(e)
        print >> sys.stderr, "Use 'twitter -h' for help."
        raise SystemExit(1)
Ejemplo n.º 7
0
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS

from api import Twitter

account_name = "Yang55109999"

twitter = Twitter(account_name)
twitter.connect()

tweets = twitter.get_tweets()

sorted_tweets = twitter.sort_by_popularity()

fmt = '{likes:<5} | {rts: <5} | {text}'
print(fmt.format(likes='♥', rts='♺', text='✍'))
print('-' * 100)
for tw in sorted_tweets[:10]:
    print(
        fmt.format(likes=tw.likes, rts=tw.rts, text=tw.text.replace('\n',
                                                                    '⏎')))

all_tweets_excl_rts_mentions = ' '.join([
    tw.text.lower() for tw in tweets
    if not tw.text.startswith('RT') and not tw.text.startswith('@')
])

pb_mask = np.array(Image.open("pybites.png"))
stopwords = set(STOPWORDS)