コード例 #1
0
def get_api_wrapper(cache_dir):
    auth = tweepy.OAuthHandler(
        os.environ["TWITTER_CONSUMER_KEY"],
        os.environ["TWITTER_CONSUMER_SECRET"]
    )
    auth.set_access_token(
        os.environ["TWITTER_ACCESS_TOKEN"],
        os.environ["TWITTER_ACCESS_TOKEN_SECRET"]
    )
    return tweepy.API(auth, cache=tweepy.FileCache(cache_dir))
コード例 #2
0
def getTwitterAPI(cachetime=360000):
  #----------------------------------------------------------------
  #API settings for Twitter
  consumer_key,consumer_secret,skey,ssecret=getTwitterKeys()
  #----------------------------------------------------------------

  #----------------------------------------------------------------
  #API initialisation for Twitter
  auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  auth.set_access_token(skey, ssecret)
  #api = tweepy.API(auth)
  api = tweepy.API(auth, cache=tweepy.FileCache('cache',cachetime), retry_errors=[500], retry_delay=5, retry_count=2)
  #----------------------------------------------------------------
  return api
コード例 #3
0
ファイル: spiralengine.py プロジェクト: taherh/tweetspiral
    def __init__(self, request, ac_engine, raw_api=False):
        '''Initialize spiral engine request and authenticate if applicable'''

        self.logged_in = False
        self.ac_engine = ac_engine

        auth = None

        parser = None
        cache_prefix = 'NORMAL'
        if raw_api:
            parser = tweepy.parsers.RawParser()
            cache_prefix = 'RAW'
            
        # check if we have a login token
        access_token = request.session.get('access_token_tw', None)
        access_token_secret = request.session.get('access_token_secret_tw', None)
        if access_token and access_token_secret:
            auth = tweepy.OAuth1UserHandler(settings.TWITTER_CONSUMER_KEY,
                                       settings.TWITTER_CONSUMER_SECRET,
                                       access_token=access_token,
                                       access_token_secret=access_token_secret)
            self.logged_in = True
        else:
            auth = tweepy.OAuth2BearerHandler(settings.TWITTER_BEARER_TOKEN)
        
        if settings.API_CACHE == 'memory':
            cache = tweepy.MemoryCache(timeout=settings.API_CACHE_TIMEOUT)
        elif settings.API_CACHE == 'file':
            cache = tweepy.FileCache(cache_dir=settings.API_FILE_CACHE_PATH + "/" + cache_prefix,
                                     timeout=settings.API_CACHE_TIMEOUT)
        elif settings.API_CACHE == 'redis':
            cache = tweepy.cache.RedisCache(redis.StrictRedis(),
                                      pre_identifier = "tweepy:" + cache_prefix + ":",
                                      timeout=settings.API_CACHE_TIMEOUT)
        else:
            cache = None
    
        self.api = tweepy.API(auth, cache=cache,
                              parser=parser)
コード例 #4
0
def timeline_to_feed(config):
    api_kwargs = {}
    if config.get('cache_dir'):
        api_kwargs['cache'] = tweepy.FileCache('.cache', timeout=60 * 5)

    api = get_api(config, **api_kwargs)
    print('Created Twitter API connection')

    me = api.me()
    print("Begin creating feed for {}'s timeline".format(me.screen_name))

    feed = AtomFeed(
        title=config.get(
            'feed_title',
            'Links from the timeline of @{}'.format(me.screen_name)),
        url='https://twitter.com/{}'.format(me.screen_name),
        feed_url=config.get('feed_url'),
        generator=('Tauphi', 'https://github.com/tgecho/tauphi', None),
    )

    assert config.get('max_items') or config.get(
        'max_days'), 'Please specify at least one of max_items or max_days.'

    item_count = 0
    min_date = date.today() - timedelta(
        days=config['max_days']) if config.get('max_days') else None

    for tweet in tweepy.Cursor(api.home_timeline, count=200).items():
        if tweet.entities.get('urls'):
            author = tweet.author

            item_count += 1

            if item_count % 10 == 0:
                print('{} items found'.format(item_count))

            if config.get(
                    'max_items') and item_count > config.get('max_items'):
                print('Max items ({}) reached'.format(config['max_items']))
                break

            if min_date and tweet.created_at.date() < min_date:
                print('Max days ({}) reached'.format(config['max_days']))
                break

            tweet_url = 'https://twitter.com/{}/status/{}'.format(
                tweet.author.screen_name, tweet.id_str)

            title = tweet.text
            content = """
            <p>{}</p>
            <p>
                <a href="{}">@{}</a>
                (<a href="{}">original</a>)
            </p>
            """.format(tweet.text,
                       'https://twitter.com/{}'.format(author.screen_name),
                       author.screen_name, tweet_url)

            for url in tweet.entities['urls']:
                expanded = url['expanded_url']
                display = url['display_url']

                title = title.replace(url['url'], display)

                link = '<a href="{}" title="{}">{}</a>'.format(
                    url['url'],
                    expanded,
                    display,
                )
                content = content.replace(url['url'], link)

                if any(expanded.endswith(e) for e in IMAGE_EXTENSIONS):
                    content += '<p><img src="{}" /></p>'.format(expanded)

            if getattr(tweet, 'extended_entities', None):
                for embed in tweet.extended_entities['media']:
                    if embed == 'photo':
                        content += '<p><img src="{}" /></p>'.format(
                            embed.media_url_https)

            if len(tweet.entities['urls']) == 1:
                item_url = tweet.entities['urls'][0]['url']
            else:
                item_url = tweet_url

            feed.add(id=tweet_url,
                     url=item_url,
                     title=title,
                     content=content,
                     content_type='html',
                     author='{} (@{})'.format(author.name, author.screen_name),
                     published=tweet.created_at,
                     updated=tweet.created_at,
                     links=[{
                         'href': u['url']
                     } for u in tweet.entities['urls']])

    feed_str = unicode(feed)

    print('Feed generated with {} items'.format(item_count))
    return feed_str
コード例 #5
0
import webbrowser
import pickle
import os
import sys
import csv
import StringIO

# this assumes the existence of a credentials.py in your sys.path holding key/secret for Twitter application
# https://dev.twitter.com/apps -- e.g., one of @rdhyee's: https://dev.twitter.com/apps/171403/show

from credentials import consumer_key, consumer_secret

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

# set the cache_dir to the "cache" dir in the same directory as this script
file_cache = tweepy.FileCache(cache_dir=os.path.join(os.path.split(sys.argv[0])[0], "cache"))

def get_user_followers(api, user_id):
    user = api.get_user("rdhyee")
    print user.screen_name
    print user.followers_count
    for friend in tweepy.Cursor(api.followers, screen_name=user.screen_name).items():
       print friend.screen_name

# if auth.dat exists, read in the auth token, else do the authn dance

tweepy_config_path = os.path.join(os.path.expanduser("~"), ".tweepyauth")

try:
    auth_file = open(tweepy_config_path)
    auth = pickle.load(auth_file)