def _get_twitter(): """Create a connection to Twitter""" global client if not client or not client.access_token: client = AppClient( os.getenv('CONSUMER_KEY', settings.APIKEYS['CONSUMER_KEY']), os.getenv('CONSUMER_SECRET', settings.APIKEYS['CONSUMER_SECRET'])) client.get_access_token() return client
def tweet(tweet_id): client = AppClient( current_app.config['TWITTER_CLIENT_ID'], current_app.config['TWITTER_CLIENT_SECRET'], ) client.get_access_token() resource = client.api.statuses.show response = resource.get(id=tweet_id) data = json.dumps(response.data) return Response(data, mimetype='application/json')
def client(consumer_key=None, consumer_secret=None): global _client if consumer_key is None: consumer_key = CONSUMER_KEY if consumer_secret is None: consumer_secret = CONSUMER_SECRET if _client is None: _client = AppClient(consumer_key, consumer_secret) access_token = _client.get_access_token() _client = AppClient(consumer_key, consumer_secret, access_token) return _client
def handle(self, *args, **options): debug = options['debug'] print 'Debug mode: ' + ('On' if debug else 'Off') clients = [] for api_key in api_keys: client = AppClient(api_key['consumer_key'], api_key['consumer_secret']) access_token = client.get_access_token() client = AppClient(api_key['consumer_key'], api_key['consumer_secret'], access_token) clients.append(client) self.grab_qualifying_sxsw_events(clients) print 'Punting out! All done!'
def _initialize_client(self): '''Initialize the birdy API client''' try: # Initialize our client object with consumer keys. client = AppClient(self.consumer_key, self.consumer_secret) # Obtain the OAuth2 access token using our consumer keys. self.access_token = client.get_access_token() # Re-initialize our client object that stores the access token for later use. client = AppClient(self.consumer_key, self.consumer_secret, self.access_token) log.debug('Successfully initialized Twitter client') except TwitterClientError as ex: log.warning('Connection or access token retrievel error:' + str(ex)) client = None return client
def get_media_links(username): global client, response, twit client = AppClient(myconfig.CONSUMER_KEY, myconfig.CONSUMER_SECRET, myconfig.SAVED_ACCESS_TOKEN) #response = client.api.users.show.get(screen_name='luismoramedina') #print json.dumps(response.data) #response = client.api.statuses.user_timeline.get(screen_name='luismoramedina') # Action: get timeline response = client.api.statuses.user_timeline.get(screen_name=username, count=200) #response = client.api.statuses.user_timeline.get(screen_name='luismoramedina') #response = client.api.statuses.user_timeline.get(screen_name='pilibohi') #print response.data[0]['text'] # Action: parse timeline data = [] for twit in response.data: if 'entities' in twit and 'media' in twit['entities']: data.append(twit['entities']['media'][0]['media_url']) # for twit in response.data: # if 'entities' in twit and 'urls' in twit['entities']: # for url in twit['entities']['urls']: # expanded_url = url['expanded_url'] # if 'instagram' in expanded_url: # data.append(expanded_url + 'media/') # else: # data.append(expanded_url) return data
def twitter_main(): client = AppClient(tw['APIKEY'], tw['APISECRET']) access_token = client.get_access_token() response = client.api.users.show.get(screen_name='LaunchDarkly') global twitter_followers_count twitter_followers_count = response.data.followers_count print "\nTwitter followers: " + str(twitter_followers_count)
def client(self): if self._client is None: logging.debug('Creating new Twitter client.') self._client = AppClient( self.consumer_key, self.consumer_secret, access_token=self.app_client_access_token ) return self._client
def __init__(self, credential_info): self.client = AppClient( credential_info["consumer_key"], credential_info["consumer_secret"], credential_info.get("bearer_token") ) self.token = credential_info.get("bearer_token") or self.client.get_access_token() self.iterations = 0 self.time_start = float(credential_info.get("time_start")) self.since_id = None self.current_max_id = None
from flask import Flask # initialize Flask application app = Flask(__name__) app.config['PYSCSS_STYLE'] = 'compressed' app.debug = True # initialize Twitter client from birdy.twitter import AppClient from secret import CONSUMER_KEY, CONSUMER_SECRET client = AppClient(CONSUMER_KEY, CONSUMER_SECRET) token = client.get_access_token() # compile and minify scss from flask.ext.assets import Environment, Bundle assets = Environment(app) assets.url = app.static_url_path css = Bundle('stylesheets/styles.scss', filters='pyscss', output='stylesheets/styles.min.css') assets.register('css_all', css) # initialize views / route listeners from application import views
from birdy.twitter import AppClient import json from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer from constants import CONSTANTS from secrets import SECRETS import datetime DATE_RANGE_HALF = datetime.timedelta(days=1) RADII = [5, 25, -1] # RADII = [20] RESULTS_PER_BATCH = 100 MAX_BATCHES = 2 client = AppClient(SECRETS['CONSUMER_KEY'], SECRETS['CONSUMER_SECRET']) client.get_access_token() def make_report2(keywords, date_string, latitude, longitude): import pickle results = None with open("sample_data.tweetresults", "rb") as sample_data_file: results = pickle.load(sample_data_file) return results def make_report(keywords, date_string, latitude, longitude): date = datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ') date_start = date - DATE_RANGE_HALF date_end = date + DATE_RANGE_HALF or_together_keywords = keywords.replace(',',' OR ')
def login(): client = AppClient(CONSUMER_KEY, CONSUMER_SECRET) access_token = client.get_access_token() return client
from flask import make_response, render_template, jsonify, send_from_directory from sqlalchemy import create_engine from flask.ext.sqlalchemy import SQLAlchemy from birdy.twitter import AppClient from models import Source, Mention engine = create_engine('sqlite+pysqlite:///sqlite.db') from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) CONSUMER_KEY = 'XCvzOpRBPjKoWFMSYnHqHg' CONSUMER_SECRET = 'flO2rrzu6xss6ubnJUS8hp0nhgbSYp8cjjCjnaHCzG8' client = AppClient(CONSUMER_KEY, CONSUMER_SECRET) access_token = client.get_access_token() QUERIES = ['jeffknupp.com', 'jeffknupp'] def get_twitter_mentions(): statuses = [] for query in QUERIES: response = client.api.search.tweets.get(q='jeffknupp.com', count=100) statuses += response.data.statuses session = Session() twitter = session.query(Source).get(1) new_mentions = 0 for status in statuses: if not session.query(Mention).filter( Mention.domain_id == status.id_str).count():
def __init__(self): super(Twitter, self).__init__() self.client = AppClient(os.getenv("TWITTER_CONSUMER_KEY"), os.getenv("TWITTER_CONSUMER_SECRET"), os.getenv("TWITTER_ACCESS_TOKEN"))
from birdy.twitter import AppClient from birdy.twitter import TwitterApiError from birdy.twitter import TwitterRateLimitError import networkx as net import matplotlib.pyplot as plt import time CONSUMER_KEY = 'vaP7IuNKKiaQdS5bJu7p0yVui' CONSUMER_SECRET = '69hDzO08lSeO42REjhZo3gcwZXLoXt0PsGlBKJm3qA4gO58acE' ACCESS_TOKEN = 'AAAAAAAAAAAAAAAAAAAAAKAfXwAAAAAAF7oWrApsqSNCrt2blKpzQ7D%2ByTI%3D0pUxpiT33W74hpcwcflI4wFhLdLO3gWU0HlS920TCWHkPYHGZ9' client = AppClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN) g = net.Graph() def addUsersFollowed(username, depth=0, taboo_list=[]): if depth>2 or username in taboo_list: return taboo_list.append(username) print 'adding followers for ' + username ids = getFolloweesIds(username) users = usersFromIds(ids) for user in users: # i.e. if the user is a celebrity if user.friends_count > 200: continue else: g.add_edge(username, user.screen_name)
class TTR_API(object): def __init__(self, credential_info): self.client = AppClient( credential_info["consumer_key"], credential_info["consumer_secret"], credential_info.get("bearer_token") ) self.token = credential_info.get("bearer_token") or self.client.get_access_token() self.iterations = 0 self.time_start = float(credential_info.get("time_start")) self.since_id = None self.current_max_id = None def __wait(self): if self.iterations == 0: return seconds_used = time() - self.time_start wait_time = 1.98 - (seconds_used / (self.iterations or 1)) if wait_time > 0: log.info("will wait %s" % wait_time) sleep(wait_time) def get_user_timeline(self, screen_name): result = self.client.api.statuses.user_timeline.get(screen_name=screen_name) if result and result.data: for data in result.data: yield TTR_APIMessage(data) def get_tweet(self, tweet_sn_id): result = self.client.api.statuses.show.get(id=tweet_sn_id) if result and result.data: return result.data def search_iteration(self, q, max_id=None, since_id=None): self.__wait() params = {"q": q, "result_type": "recent", "count": 100, "include_entities": False} if max_id: params["max_id"] = max_id if since_id: params["since_id"] = since_id log.debug("send request to twitter: %s" % params) response = self.client.api.search.tweets.get(**params) self.iterations += 1 if response and len(response.data.statuses): return response.data.statuses return None def search_past(self, q, iterations_count=None): log.info("<<< [%s] <<<" % q) max_id = None iteration = 0 while iteration <= (iterations_count or properties.count_iterations_search_past): result = self.search_iteration(q, max_id=max_id) if result: max_id = result[-1]["id"] - 1 log.info("found %s messages for %s <<< [%s]" % (len(result), q, max_id)) self.current_max_id = max_id if not self.since_id: self.since_id = result[0]["id"] for el in result: yield TTR_APIMessage(el) else: break iteration += 1 def search_future(self, q, since_id, max_id=None): log.info("%s >>> [%s] >>>" % (since_id, q)) current_max_id = max_id _since_id = since_id while True: result = self.search_iteration(q, since_id=_since_id, max_id=current_max_id) if result: if not self.since_id: self.since_id = result[0]["id"] for el in result: yield TTR_APIMessage(el) else: break if len(result) < batch_len: break else: current_max_id = result[-1]["id"] self.current_max_id = current_max_id