import requests
from requests_oauthlib import OAuth1

api_key = '4gjrfoldzln6sHGieBZQqlDbl'
api_secret = '1f3EsoBJ3kXWkmmiu3CEJyX9pmkExYPC4rLGgdMV9WPTrotlq1'
access_token = '949230339053899776-2J64QJvoFwnYZhSQUwFoQDBx4o0rrmC'
access_secret = 'KwsUk73LEDP44TRjxD4f7g9caSGabAHbMeFTjPc5AzbZ6'

url = "https://stream.twitter.com/1.1/statuses/filter.json"
#url = "https://stream.twitter.com/1.1/search/tweets.json"

auth = OAuth1(api_key, api_secret, access_token, access_secret)
print("test1")
#r = requests.post(url, auth=auth, stream=True, data={"follow":"nasa9084","track":"emacs"})
r = requests.post(url,
                  auth=auth,
                  stream=True,
                  data={
                      "follow": "31bit",
                      "track": "emacs"
                  })
print("test2")
for line in r.iter_lines():
    print("test3")
    if not list:
        print("null")
    print(line["text"])
print("test4")
Beispiel #2
0
from autocorrect import spell
from ibm_watson import PersonalityInsightsV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import json
import wikipedia
import pandas as pd

#Twitter Data Extraction
auth_params = {
    'app_key': 'Your API key',
    'app_secret': 'Your app_secret key',
    'oauth_token': 'Your oauth_token',
    'oauth_token_secret': 'Your oauth_token_secret'
}

auth = OAuth1(auth_params['app_key'], auth_params['app_secret'],
              auth_params['oauth_token'], auth_params['oauth_token_secret'])

list_of_tweets_celebs = []
# url according to twitter API
url_rest = "https://api.twitter.com/1.1/search/tweets.json"

#list of twitter handles of famous bollywood celebrities
List_handles = [
    '@aamirkhan', '@AapkaAbhijeet', '@juniorbachchan', '@aditiraohydari',
    '@AdityaRoyKapoor', '@AftabShivdasani', '@ajaydevgn', '@AjazkhanActor',
    '@akshaykumar', '@Zafarsays', '@aliaa08', '@SrBachchan', '@AmritaRao',
    '@amuarora', '@AnilKapoor', '@anjanasukhani', '@The_AnuMalik',
    '@Anupsonicp', '@AnupamPkher', '@basuanurag', '@IAmAnushka',
    '@AnushkaSharma', '@arbaazSkhan', '@apshaha', '@rampalarjun', '@arrahman',
    '@ArshadWarsi', '@ashabhosle', '@AshishChowdhry', '@AshmitPatel',
    '@ashwinmushran', '@itsaadee', '@atul_kulkarni', '@Ayeshatakia',
Beispiel #3
0
import requests
from requests_oauthlib import OAuth1

url = 'https://sandboxapi.deere.com/platform/organizations'
auth = OAuth1(
    'johndeere-JcFsHU6CV0klrsgkDHewTLuSAP1QZ2Q8Tx9sFCOs',
    '5b67d63b58a9e80facb93354b18a79eb9be3b668f02e331cace8f5a4190254fa',
    'd8d3c1b7-8f56-4cc3-96a6-0b6da898eea6',
    '19Ryi+uXOFxS3/8Q0h+pHjlGVXaYndLhTOl64Wg4cdA4/5ly0f48DxcN+nBsfFgXP71ruvCHMb4T5fYXeGzQ5uAzGYDKyfONgE0Mp6y1bbA='
)
headers = {"Accept": "application/vnd.deere.axiom.v3+json"}
r = requests.get('https://sandboxapi.deere.com/platform/organizations',
                 headers=headers,
                 auth=auth)
data = r.json()

#  create tables
for organization in data['values']:
    #print(organization)
    # insert organization
    #organization = {
    #    id: 1,
    #    name: 'asd',
    #}
    for link in organization['links']:
        if link['rel'] == 'machines':
            rMachine = requests.get(link['uri'], headers=headers, auth=auth)
            dataMachine = rMachine.json()
            for machine in dataMachine['values']:
                # insert machine
                print(machine)
Beispiel #4
0
import requests
from requests_oauthlib import OAuth1
import configparser
import json
import random

BASE_URL_TWITTER = "https://api.twitter.com/1.1/tweets/search/30day/dev.json"
BASE_URL_MAPBOX = "https://api.mapbox.com/geocoding/v5/mapbox.places/"

config = configparser.ConfigParser()
config.read("config.ini")

auth = OAuth1(config["TwitterAPI"]['API_KEY'],
              config["TwitterAPI"]['API_SECRET_KEY'],
              config["TwitterAPI"]['ACCESS_TOKEN'],
              config["TwitterAPI"]['ACCESS_TOKEN_SECRET'])


def get_coords(loc):
    rr = requests.get(BASE_URL_MAPBOX + loc + ".json?access_token=" +
                      config['mapboxAPI']['API_KEY'] +
                      "&cachebuster=1549145420259&autocomplete=true")
    location = json.loads(rr.text)
    try:
        if 'bbox' in location['features'][0]:
            arr = location['features'][0]['bbox']
            x = random.uniform(arr[0], arr[2])
            y = random.uniform(arr[1], arr[3])
        elif 'center' in location['features'][0]:
            arr = location['features'][0]['center']
            x = arr[0]
Beispiel #5
0
import sys
import pickle
reload(sys)
sys.setdefaultencoding('utf8')
from requests_oauthlib import OAuth1

# authentication pieces
client_key = ""  # fill in
client_secret = ""  # fill in
token = ""  # fill in
token_secret = ""  # fill in
# the base for all Twitter calls
base_twitter_url = "https://api.twitter.com/1.1/"

# setup authentication
oauth = OAuth1(client_key, client_secret, token, token_secret)


#
# Main Twitter API function for sending requests
#
def send_request(screen_name, relationship_type, next_cursor=None):

    url = "https://api.twitter.com/1.1/%s/ids.json?screen_name=%s&count=5000" % (
        relationship_type, username)

    if next_cursor is not None:
        url += "&cursor=%s" % next_cursor

    response = requests.get(url, auth=oauth)
Beispiel #6
0
def put(url):
	auth = OAuth1(ConsumerKey, ConsumerSecret, TokenKey, TokenSecret)
	response = requests.put(url, headers=headers, auth=auth, data=fileContent)
	print response.status_code
	return response.content
Beispiel #7
0
    def __init__(self,
                 app_key=None,
                 app_secret=None,
                 oauth_token=None,
                 oauth_token_secret=None,
                 access_token=None,
                 token_type='bearer',
                 oauth_version=1,
                 api_version='1.1',
                 client_args=None,
                 auth_endpoint='authenticate'):
        """Instantiates an instance of Twython. Takes optional parameters for
        authentication and such (see below).

        :param app_key: (optional) Your applications key
        :param app_secret: (optional) Your applications secret key
        :param oauth_token: (optional) When using **OAuth 1**, combined with
        oauth_token_secret to make authenticated calls
        :param oauth_token_secret: (optional) When using **OAuth 1** combined
        with oauth_token to make authenticated calls
        :param access_token: (optional) When using **OAuth 2**, provide a
        valid access token if you have one
        :param token_type: (optional) When using **OAuth 2**, provide your
        token type. Default: bearer
        :param oauth_version: (optional) Choose which OAuth version to use.
        Default: 1
        :param api_version: (optional) Choose which Twitter API version to
        use. Default: 1.1

        :param client_args: (optional) Accepts some requests Session parameters
        and some requests Request parameters.
              See http://docs.python-requests.org/en/latest/api/#sessionapi
              and requests section below it for details.
              [ex. headers, proxies, verify(SSL verification)]
        :param auth_endpoint: (optional) Lets you select which authentication
        endpoint will use your application.
              This will allow the application to have DM access
              if the endpoint is 'authorize'.
                Default: authenticate.
        """

        # API urls, OAuth urls and API version; needed for hitting that there
        # API.
        self.api_version = api_version
        self.api_url = 'https://api.twitter.com/%s'

        self.app_key = app_key
        self.app_secret = app_secret
        self.oauth_token = oauth_token
        self.oauth_token_secret = oauth_token_secret
        self.access_token = access_token

        # OAuth 1
        self.request_token_url = self.api_url % 'oauth/request_token'
        self.access_token_url = self.api_url % 'oauth/access_token'
        self.authenticate_url = self.api_url % ('oauth/%s' % auth_endpoint)

        if self.access_token:  # If they pass an access token, force OAuth 2
            oauth_version = 2

        self.oauth_version = oauth_version

        # OAuth 2
        if oauth_version == 2:
            self.request_token_url = self.api_url % 'oauth2/token'

        self.client_args = client_args or {}
        default_headers = {'User-Agent': 'Twython v' + __version__}
        if 'headers' not in self.client_args:
            # If they didn't set any headers, set our defaults for them
            self.client_args['headers'] = default_headers
        elif 'User-Agent' not in self.client_args['headers']:
            # If they set headers, but didn't include User-Agent.. set
            # it for them
            self.client_args['headers'].update(default_headers)

        # Generate OAuth authentication object for the request
        # If no keys/tokens are passed to __init__, auth=None allows for
        # unauthenticated requests, although I think all v1.1 requests
        # need auth
        auth = None
        if oauth_version == 1:
            # User Authentication is through OAuth 1
            if self.app_key is not None and self.app_secret is not None and \
               self.oauth_token is None and self.oauth_token_secret is None:
                auth = OAuth1(self.app_key, self.app_secret)

            if self.app_key is not None and self.app_secret is not None and \
               self.oauth_token is not None and self.oauth_token_secret is \
               not None:
                auth = OAuth1(self.app_key, self.app_secret, self.oauth_token,
                              self.oauth_token_secret)
        elif oauth_version == 2 and self.access_token:
            # Application Authentication is through OAuth 2
            token = {
                'token_type': token_type,
                'access_token': self.access_token
            }
            auth = OAuth2(self.app_key, token=token)

        self.client = requests.Session()
        self.client.auth = auth

        # Make a copy of the client args and iterate over them
        # Pop out all the acceptable args at this point because they will
        # Never be used again.
        client_args_copy = self.client_args.copy()
        for k, v in client_args_copy.items():
            if k in ('cert', 'hooks', 'max_redirects', 'proxies'):
                setattr(self.client, k, v)
                self.client_args.pop(k)  # Pop, pop!

        # Headers are always present, so we unconditionally pop them and merge
        # them into the session headers.
        self.client.headers.update(self.client_args.pop('headers'))

        self._last_call = None
Beispiel #8
0
def post_accessory():

    for num, row in enumerate(cursor.execute("SELECT * FROM accessories"),
                              start=1):
        if num > 0:
            sku = row[0]
            name = row[1]
            description = row[2]
            price = row[3]
            tags = row[4].replace("[", "").replace("]",
                                                   "").replace("'",
                                                               "").split(", ")
            cats = row[5]

            # try:
            #     s3_urls = row[8].decode('utf-8').replace("[", "").replace("]", "").replace("'", "").split(", ")
            # except:
            #     s3_urls = row[8].replace("[", "").replace("]", "").replace("'", "").split(", ")

            # sub_cats = row[4].split(", ")

            try:
                cats_list = []
                for item in range(0, len(accessory_categories)):
                    if cats == accessory_categories[item]['name']:
                        cat_id = accessory_categories[item]['id']
                        cat_name = accessory_categories[item]['name']
                        cats_list.append({"id": cat_id, 'name': cat_name})
            except:
                cats_list = []

            try:
                tags_list = []

                for tag in tags:
                    for item in range(0, len(accessory_tags)):
                        id = accessory_tags[item]['id']
                        if tag == accessory_tags[item]['name']:
                            tag_id = accessory_tags[item]['id']
                            tag_name = accessory_tags[item]['name']
                            tags_list.append({"id": tag_id, 'name': tag_name})
            except:
                tags_list = []
            tags_list.append({"id": 222, 'name': 'icom'})

            # images = []
            # for img in s3_urls:
            #     if img == 'http://cybercomm.flywheelsites.com/wp-content/uploads/2019/07/img_notavailable_insignia-01.png':
            #         images = []
            #     else:
            #         images.append({"src": img})

            # if float(price) > 499.99 or float(price) == 0.0:
            data = {
                "name": name,
                "type": "simple",
                "sku": sku,
                "regular_price": str(price),
                "short_description": sku,
                "description": description,
                "categories": cats_list,
                "tags": tags_list,
                "meta_data": [{
                    'key': 'is_quotable',
                    'value': False
                }]
            }

            # else:
            #     data = {
            #         "name": name,
            #         "type": "simple",
            #         "sku": sku,
            #         "regular_price": str(price),
            #         "short_description": info,
            #         "description": description,
            #         "categories": cats_list,
            #         "tags": tags_list,
            #         "images": images,
            #     }
            #
            # print(sku, data)

            headers = {
                "Content-Type": "application/json",
                "wp_api": "True",
                "version": "wc/v3"
            }
            req = requests.post(
                'http://staging.gotoess.flywheelsites.com/wp-json/wc/v3/products',
                auth=OAuth1(client_key=key, client_secret=secret),
                headers=headers,
                data=json.dumps(data))
            print(num, req.json())
Beispiel #9
0
def post_radios():

    for row in cursor.execute("SELECT * FROM radios"):

        name = row[0]
        description = row[1]
        specs = row[2]
        features = row[3]
        category = row[4]
        brochures = row[6]

        # cats = row[2].replace("[", "").replace("]", "").replace("'", "").split(", ")
        # tags = row[3].replace("[", "").replace("]", "").replace("'", "").split(", ")

        try:
            s3_urls = row[5].decode('utf-8').replace("[", "").replace(
                "]", "").replace("'", "").split(", ")
        except:
            s3_urls = row[5].replace("[",
                                     "").replace("]",
                                                 "").replace("'",
                                                             "").split(", ")
        s3_urls = s3_urls[0].split(',')

        cats_list = []

        for item in range(0, len(radio_categories)):
            if category == radio_categories[item]['name']:
                cat_id = radio_categories[item]['id']
                cat_name = radio_categories[item]['name']
                cats_list.append({"id": cat_id, 'name': cat_name})

        tags_list = []
        for item in range(0, len(accessory_tags)):
            try:
                if name == accessory_tags[item]['name']:
                    tag_id = accessory_tags[item]['id']
                    tag_name = accessory_tags[item]['name']
                    tags_list.append({"id": tag_id})
            except:
                tags_list = []
        tags_list.append({"id": 222, 'name': 'icom'})

        images = []
        for img in s3_urls:
            if img == '':
                images = []
            else:
                images.append({"src": img})
        # print(images)

        # productName, description, categories, tags, industry, features, professional_commercial, radioShortname, S3images
        data = {
            "name":
            name,
            "type":
            "simple",
            "description":
            description,
            "specifications":
            specs,
            "features":
            features,
            "categories":
            cats_list,
            "tags":
            tags_list,
            "images":
            images,
            "meta_data": [{
                'key': 'is_quotable',
                'value': True
            }, {
                'key': 'specifications',
                'value': specs
            }]
        }

        headers = {
            "Content-Type": "application/json",
            "wp_api": "True",
            "version": "wc/v3"
        }
        req = requests.post('c',
                            auth=OAuth1(client_key=key, client_secret=secret),
                            headers=headers,
                            data=json.dumps(data))
        print(req.json())
Beispiel #10
0
def get_articles():
    """Uses the oauth token and secret to obtain all articles of the authenticated user from Figshare
    
    Adds the results to the session under 'items', or raises an exception if the response contains an error.
    """

    app.logger.debug("Retrieving all articles owned by the user.")

    oauth_token = g.user.oauth_token
    oauth_token_secret = g.user.oauth_token_secret

    app.logger.debug("Token : {}".format(g.user.oauth_token))
    app.logger.debug("Secret: {}".format(g.user.oauth_token_secret))

    oauth = OAuth1(client_key,
                   client_secret=client_secret,
                   resource_owner_key=oauth_token,
                   resource_owner_secret=oauth_token_secret)

    # We'll start at page 0, will be updated at the start of the first loop.
    page = 0

    # The list of articles + titles we will return later.
    articles = []
    # The dictionary of article details that we'll return later.
    details = {}

    while True:
        page += 1
        params = {'page': page}

        response = requests.get(
            url='http://api.figshare.com/v1/my_data/articles',
            auth=oauth,
            params=params)
        app.logger.debug("Called: {}".format(response.url))

        results = json.loads(response.content)

        if 'error' in results:
            app.logger.error(results)
            if results['error'] == 'No valid token could be found':
                raise FigshareNoTokenError(results['error'])
            else:
                raise Exception(results['error'])
        elif results == {}:
            app.logger.error(
                "No articles found, retrieved empty response. This probably means that we have an OAuth issue."
            )
            raise FigshareEmptyResponse(
                "No articles found, retrieved empty response. This probably means that we have an OAuth issue."
            )
        else:
            if len(results['items']) == 0:
                print "No more results"
                break
            else:
                # Add all articles in results['items'] (a list) to the session['items'] dictionary, to improve lookup.
                for article in results['items']:

                    # Filter out those articles that have Drafts status
                    if article['status'] != 'Drafts':

                        articles.append({
                            'id': article['article_id'],
                            'text': article['title']
                        })

                        details[str(article['article_id'])] = article
                    else:
                        app.logger.debug(
                            'Skipped article {} because it is still a draft'.
                            format(article['article_id']))

    return articles, details
Beispiel #11
0
import os

import requests
from requests_oauthlib import OAuth1

consumer_key = os.getenv("TWITTER_CONSUMER_KEY")
consumer_secret = os.getenv("TWITTER_CONSUMER_SECRET")

# need to pull this from DB
oauth_token = os.getenv("OAUTH_TOKEN")
oauth_token_secret = os.getenv("OAUTH_TOKEN_SECRET")

oauth = OAuth1(
    client_key=consumer_key,
    client_secret=consumer_secret,
    resource_owner_key=oauth_token,
    resource_owner_secret=oauth_token_secret,
)


url = u"https://api.twitter.com/1.1/account/settings.json"
r = requests.get(url, auth=oauth)

print(r.status_code)
print(r.json())
Beispiel #12
0
    CONSUMER_KEY = os.environ.get('CONSUMER_KEY')
    CONSUMER_SECRET = os.environ.get('CONSUMER_SECRET')
    ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN')
    ACCESS_TOKEN_SECRET = os.environ.get('ACCESS_TOKEN_SECRET')
    DATABASE = os.environ.get('DATABASE')
    DATABASE_HOST = os.environ.get('DATABASE_HOST')
    DATABASE_USER = os.environ.get('DATABASE_USER')
    DATABASE_PASSWORD = os.environ.get('DATABASE_PASSWORD')

#Set up tweepy client for sending Tweets and DMs.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

# Generate user context auth (OAuth1)
USER_AUTH = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                   ACCESS_TOKEN_SECRET)

#TODO: --> config.dat
PARS = [5, 4, 3, 4, 3, 5, 4, 4, 4, 4, 4, 3, 4, 4, 5, 5, 3, 4]
SCORER_ACCOUNTS = []  #Add scores to config.dat

EAGLE_IMAGES = [
    './static/eagle1.jpg', './static/eagle2.jpg', './static/eagle3.jpg',
    './static/eagle4.jpg'
]
BIRDIE_IMAGES = [
    './static/birdie1.jpg', './static/birdie2.jpg', './static/birdie3.jpg',
    './static/birdie4.jpg'
]

from __future__ import unicode_literals
from requests_oauthlib import OAuth1
import requests
import pprint

REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize"
ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"

CONSUMER_KEY = "xxxxxxxxxxxxxxxxxx"
CONSUMER_SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# request token
oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET_KEY)

endpoint = "https://api.twitter.com/1.1/search/tweets.json?q=santaclara"
r = requests.get(endpoint, auth=oauth)

# Prettyprint to print in Json format
pretty_print = pprint.PrettyPrinter(indent=4)
pretty_print.pprint(r.json())







def get_twitter_auth(user_id):
    consumer_key, consumer_secret = local_cache.get_server_state(
    )['twitter_keys']
    access_token, access_secret = get_cached_access_pair(user_id)
    return OAuth1(consumer_key, consumer_secret, access_token, access_secret)
Beispiel #15
0
def delete(url):
	auth = OAuth1(ConsumerKey, ConsumerSecret, TokenKey, TokenSecret)
	response = requests.delete(url, headers=headers, auth=auth)
	return response.status_code
    def __init__(self,
                 user=None,
                 password=None,
                 client_app_key=None,
                 client_app_secret=None,
                 user_oauth_token=None,
                 user_oauth_token_secret=None,
                 api_app_key=None,
                 auth_type=None):
        '''Set up client for API communications
           This is where you'll need to specify all the authentication and
           required headers

           Preference will be given towards passed in variables, otherwise
           environment variables will be used

           Config file is supported but discouraged since it's a common
           source of credential leaks
        '''
        # Setup Host here
        self.url = URL
        # Setup Session object for all future API calls
        self.session = requests.Session()

        # Setup authentication
        # If interested in using a config file instead of env vars, load with
        # self._load_key_yml(config_key, path)
        # Feel free to clear out auth methods not implemented by the API
        if not auth_type:
            auth_type = AuthType[os.getenv('AUTH_TYPE', default='NONE')]
        if (auth_type == AuthType.HTTPBASICAUTH
                or auth_type == AuthType.HTTPDIGESTAUTH):
            if not user:
                user = os.getenv('CLIENT_USER')
            if not password:
                password = os.getenv('CLIENT_PASSWORD')
            if auth_type == AuthType.HTTPBASICAUTH:
                self.session.auth = HTTPBasicAuth(user, password)
            else:
                self.session.auth = HTTPDigestAuth(user, password)
        if auth_type == AuthType.OAUTH1:
            if not client_app_key:
                client_app_key = os.getenv('CLIENT_APP_KEY')
            if not client_app_secret:
                client_app_secret = os.getenv('CLIENT_APP_SECRET')
            if not user_oauth_token:
                user_oauth_token = os.getenv('USER_OAUTH_TOKEN')
            if not user_oauth_token_secret:
                user_oauth_token_secret = os.getenv('USER_OAUTH_TOKEN_SECRET')
            self.session.auth = OAuth1(client_app_key, client_app_secret,
                                       user_oauth_token,
                                       user_oauth_token_secret)
        if auth_type == AuthType.OAUTH2:
            # Feel free to create a PR if you want to contribute
            raise NotImplementedError("OAuth2 currently not supported")

        # Some APIs require an API key in a header in addition to or instead
        # of standard authentication methods
        if not api_app_key:
            api_app_key = os.getenv('API_APP_KEY')
        self.session.headers.update({'App-Key': api_app_key})

        # Setup any additional headers required by the API
        # This sometimes includes additional account info
        account_owner = os.getenv('PINGDOM_ACCOUNT_OWNER')
        if account_owner:
            self.session.headers.update({'account-email': account_owner})

        logger.info('Authenticating...')
        if self._authenticate():
            logger.info('Authentication Successful!')
        else:
            logger.info('Authentication Failed!')
            raise AuthenticationError('Authentication Failed!')
Beispiel #17
0
def post(url):
	auth = OAuth1(ConsumerKey, ConsumerSecret, TokenKey, TokenSecret)
	response = requests.post(url, headers=headers, auth=auth, data=fileContent)
	return response.content
Beispiel #18
0
        'Bearer AAAAAAAAAAAAAAAAAAAAAFXzAwAAAAAAMHCxpeSDG1gLNLghVe8d74hl6k4%3DRUMF4xAQLsbeBhTSRrCiQpJtxoGWeyHrDb5te2jpGskWDFW82F',
        'X-Guest-Token':
        requests.post(
            "https://api.twitter.com/1.1/guest/activate.json",
            headers={
                "Authorization":
                "Bearer AAAAAAAAAAAAAAAAAAAAAFXzAwAAAAAAMHCxpeSDG1gLNLghVe8d74hl6k4%3DRUMF4xAQLsbeBhTSRrCiQpJtxoGWeyHrDb5te2jpGskWDFW82F"
            }).json()['guest_token']
    })
trend = lambda q, c, o1, o2: requests.get(
    'https://api.twitter.com/2/search/adaptive.json?qf_abuse=true&q=%23' + q.
    replace('#', '%23').replace('%23', '') +
    '&query_source=trend_click&spelling_corrections=true&tweet_search_mode=live&earned=true&include_entities=true&include_cards=true&cards_platform=Android-12&include_carousels=true&ext=stickerInfo%2CmediaRestrictions%2CaltText%2CmediaStats%2CmediaColor%2Cinfo360%2CcameraMoment%2Cmaster_playlist_only&include_media_features=true&include_blocking=true&include_blocked_by=true&tweet_mode=extended&include_reply_count=true&include_composer_source=true&simple_quoted_tweet=true&include_ext_media_availability=true&include_user_entities=true&include_profile_interstitial_type=true',
    auth=OAuth1('3nVuSoBZnx6U4vzUxf5w',
                'Bcs59EFbbsdF6Sl9Ng71smgStWEGwXXKSjYvPVt7qys',
                o1,
                o2,
                decoding=None)
).text if not c else requests.get(
    'https://api.twitter.com/2/search/adaptive.json?cursor=scroll%3A' + c.
    replace('=', '%3D') + '&qf_abuse=true&q=%23' + q.replace(
        '#', '%23').replace('%23', '') +
    '&query_source=trend_click&spelling_corrections=true&tweet_search_mode=live&earned=true&include_entities=true&include_cards=true&cards_platform=Android-12&include_carousels=true&ext=stickerInfo%2CmediaRestrictions%2CaltText%2CmediaStats%2CmediaColor%2Cinfo360%2CcameraMoment%2Cmaster_playlist_only&include_media_features=true&include_blocking=true&include_blocked_by=true&tweet_mode=extended&include_reply_count=true&include_composer_source=true&simple_quoted_tweet=true&include_ext_media_availability=true&include_user_entities=true&include_profile_interstitial_type=true',
    auth=OAuth1('3nVuSoBZnx6U4vzUxf5w',
                'Bcs59EFbbsdF6Sl9Ng71smgStWEGwXXKSjYvPVt7qys',
                o1,
                o2,
                decoding=None)).text
uinput = lambda m: raw_input(m) if platform.python_version().split(".")[
    0] == "2" else str(input(m))
###################################
Beispiel #19
0
 def _connect(self, method, endpoint, **kwargs):
     auth = OAuth1(self.consumer_key, self.consumer_secret,
                   self.access_token, self.access_token_secret)
     url = f"https://stream.twitter.com/1.1/{endpoint}.json"
     super()._connect(method, url, auth=auth, **kwargs)
Beispiel #20
0
    def callback(self, request):
        """Process the LinkedIn redirect"""
        if 'denied' in request.GET:
            return AuthenticationDenied("User denied authentication",
                                        provider_name=self.name,
                                        provider_type=self.type)

        verifier = request.GET.get('oauth_verifier')
        if not verifier:
            raise ThirdPartyFailure("No oauth_verifier returned")

        request_token = request.session['token']

        # turn our request token into an access token
        oauth = OAuth1(
            self.consumer_key,
            client_secret=self.consumer_secret,
            resource_owner_key=request_token['oauth_token'],
            resource_owner_secret=request_token['oauth_token_secret'],
            verifier=verifier)
        resp = requests.post(ACCESS_URL, auth=oauth)
        if resp.status_code != 200:
            raise ThirdPartyFailure("Status %s: %s" %
                                    (resp.status_code, resp.content))
        access_token = dict(parse_qsl(resp.content))
        creds = {
            'oauthAccessToken': access_token['oauth_token'],
            'oauthAccessTokenSecret': access_token['oauth_token_secret'],
        }

        # setup oauth for general api calls
        oauth = OAuth1(self.consumer_key,
                       client_secret=self.consumer_secret,
                       resource_owner_key=creds['oauthAccessToken'],
                       resource_owner_secret=creds['oauthAccessTokenSecret'])

        profile_url = 'http://api.linkedin.com/v1/people/~'
        profile_url += (':(first-name,last-name,id,date-of-birth,picture-url,'
                        'email-address)')
        profile_url += '?format=json'

        resp = requests.get(profile_url, auth=oauth)
        if resp.status_code != 200:
            raise ThirdPartyFailure("Status %s: %s" %
                                    (resp.status_code, resp.content))
        data = resp.json()

        # Setup the normalized contact info
        profile = {}
        profile['displayName'] = data['firstName'] + data['lastName']
        profile['name'] = {
            'givenName': data['firstName'],
            'familyName': data['lastName'],
            'formatted': '%s %s' % (data['firstName'], data['lastName'])
        }
        if data.get('emailAddress'):
            profile['emails'] = [{'value': data.get('emailAddress')}]
        if data.get('pictureUrl'):
            profile['photos'] = [{'value': data.get('pictureUrl')}]

        profile['accounts'] = [{
            'domain': 'linkedin.com',
            'userid': data['id']
        }]
        return LinkedInAuthenticationComplete(profile=profile,
                                              credentials=creds,
                                              provider_name=self.name,
                                              provider_type=self.type)
Beispiel #21
0
"""
.py file containing functions for interacting with Twitter's api.
in test_twitterfuncs.py, you will find functions that test the functionality and return the responses
of each function using a few different scenarios
"""
import requests
from requests_oauthlib import OAuth1
import pandas as pd

tokens = OAuth1('sWjlYbgUANObCyZ1YPeKerP3K', 'j7tbbJmTGKFqSG1RXjNfVU3dY9j54oQ0UU0tAwDqmtuE4Fv8BD'
              ,'1223025397035606017-VuF2llYRiSepf0XS8O8i4nikToLCr9', 'BIX3EPvTLGoyBrDnp9cXSeQeq6xeoz6gl73xcCAfWidg9')
searchtwt = 'https://api.twitter.com/1.1/search/tweets.json'
flwerlist = 'https://api.twitter.com/1.1/followers/list.json?'
user_search = 'https://api.twitter.com/1.1/users/show.json?'
tweet_search = 'https://api.twitter.com/1.1/search/tweets.json'
q = '?q='
chars = {'space': (' ', '%20'), 
        'hashtag': ('#', '%23')}

def find_user(screen_name, keys=None):
    """
    parameters
    ------------
    screen_name: str
        Twitter handle to search for. Can have @ or not.
    keys: list; optional
        keys to return about user object
    
    return
    ------------
    dict of user object
Beispiel #22
0
 def generateAyxRequest(self, endpoint):
     queryoauth = OAuth1(self.client_key,
                         self.client_secret,
                         signature_type='query')
     return requests.get(endpoint, auth=queryoauth)
    def run(self):
        result = Result()
        db = SqlHelper(constants.SQL_DATABASE_NAME)
        df = db.fetch_table_as_dataframe('top_cities')
        cities = pd.DataFrame(data=df.iloc[0:self.top_how_much],
                              columns={'city'})
        for index, row in cities.iterrows():
            self.logger.debug(str(index + 1) + ". " + row['city'])

        # cities = {'city': ['Heidelberg', 'Karlsruhe']}
        city_for_search = pd.DataFrame(cities, columns=['city'])

        immo_oauth = OAuth1(
            constants.IMMOSCOUT_CLIENT_KEY,
            client_secret=constants.IMMOSCOUT_CLIENT_SECRET,
            resource_owner_key=constants.IMMOSCOUT_RESOURCE_OWNER_KEY,
            resource_owner_secret=constants.IMMOSCOUT_RESOURCE_OWNER_SECRET)

        # create empty geo_df
        geo_df = pd.DataFrame(columns={'geoId', 'city'})
        # get geoid from Immoscout24 API
        geo_df = self.get_geo_id(city_for_search, geo_df, immo_oauth)

        # Fläche Retaurant:
        # https: // se909eeccf1caa559.jimcontent.com / download / version / 1507517357 / module / 11096440527 / name / AuszugDiplomarbeit_13.03.2006.pdf
        # Gast = 40 %
        # Technik = 12 %
        # Personal = 8 %
        # Gast = 40 %
        total_floor_space_min = constants.FLOOR_SPACE_GUEST * constants.SEATS_MIN / 40 * 100.0
        total_floor_space_max = constants.FLOOR_SPACE_GUEST * constants.SEATS_MAX / 40 * 100.0

        restaurant_df = pd.DataFrame()
        # get Immoscout24 object by geocode
        for index, row in geo_df.iterrows():
            params = {
                'realestatetype':
                'gastronomy',
                'geocodes':
                str(row['geoId']),
                'gastronomytypes':
                'restaurant',
                'channel':
                'is24',
                'numberofseats':
                str(constants.SEATS_MIN) + '-' + str(constants.SEATS_MAX),
                'pagesize':
                '200',
                'totalfloorspace':
                str(total_floor_space_min) + '-' + str(total_floor_space_max)
            }
            immo_search_response = requests.request(
                method='GET',
                url=constants.IMMOSCOUT_SEARCH_URL,
                params=params,
                headers=constants.IMMOSCOUT_HEADERS,
                auth=immo_oauth)
            immo_search_json = pd.read_json(immo_search_response.text)
            hits = immo_search_json['resultlist.resultlist'][0]['numberOfHits']
            self.logger.info("Hits: " + str(hits) + " for city: " +
                             str(row['city']) + "\r\n")
            if hits == 1:
                immo_object = immo_search_json['resultlist.resultlist'][1][0][
                    'resultlistEntry']['resultlist.realEstate']
                real_estate_id = immo_search_json['resultlist.resultlist'][1][
                    0]['resultlistEntry']['resultlist.realEstate']['@id']
                restaurant_df = restaurant_df.append(self.transform_df(
                    immo_object, real_estate_id),
                                                     ignore_index=True,
                                                     sort=True)
            elif hits >= 1:
                for i in range(hits):
                    immo_object = immo_search_json['resultlist.resultlist'][1][
                        0]['resultlistEntry'][i]['resultlist.realEstate']
                    real_estate_id = immo_search_json['resultlist.resultlist'][
                        1][0]['resultlistEntry'][i]['resultlist.realEstate'][
                            '@id']
                    restaurant_df = restaurant_df.append(self.transform_df(
                        immo_object, real_estate_id),
                                                         ignore_index=True,
                                                         sort=True)
            else:
                self.logger.info('No object found for city: ' +
                                 str(row['city']))
        self.logger.info(restaurant_df)
        result_json = restaurant_df.to_json(orient='records')
        attributes = self._create_datastore_entity(result_json)
        success = self._save(self.entity_id, attributes)
        result.set_success(success)
        self.logger.info(result)
        return result
Beispiel #24
0
 def executeWorkflow(self, app_id, question_payload):
     endpoint = self.generateAyxEndpoint('workflows', app_id) + 'jobs/'
     queryoauth = OAuth1(self.client_key,
                         self.client_secret,
                         signature_type='query')
     return requests.post(endpoint, auth=queryoauth, json=question_payload)
from credentials import *
from requests_oauthlib import OAuth1
import requests

# Global Auth
AUTH = OAuth1(consumer_key, consumer_secret, access_token, access_token_secret)


def request_user_id():
    # user_id = input("Please enter the user id: ")
    user_id = "newlifeshoes"
    return (user_id)


def fetch_followers(user_id, count):
    URL = 'https://api.twitter.com/1.1/followers/list.json'
    # URL = 'https://api.twitter.com/1.1/statuses/mentions_timeline.json'
    PARAMS = {'screen_name': user_id, 'count': count}

    # sending get request and saving the response as response object
    r = requests.get(url=URL, params=PARAMS, auth=AUTH)

    # print(r)
    # print("\n\n")

    # extracting data in json format
    # for some reason i need to add ['users'] in the forloop statement itself.
    # no idea why it doesnt work like it did in fetch mention timeline
    for tweet in r.json()['users']:
        # print(tweet['screen_name'])
        print(tweet)
import json
import requests
from requests_oauthlib import OAuth1

MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json'
POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/update.json'

CONSUMER_KEY = 'your-consumer-key'
CONSUMER_SECRET = 'your-consumer-secret'
ACCESS_TOKEN = 'your-access-token'
ACCESS_TOKEN_SECRET = 'your-access-secret'

VIDEO_FILENAME = 'icon.jpg'

oauth = OAuth1(CONSUMER_KEY,
               client_secret=CONSUMER_SECRET,
               resource_owner_key=ACCESS_TOKEN,
               resource_owner_secret=ACCESS_TOKEN_SECRET)


class VideoTweet(object):
    def __init__(self, file_name):
        '''
    Defines video tweet properties
    '''
        self.video_filename = file_name
        self.total_bytes = os.path.getsize(self.video_filename)
        self.media_id = None
        self.processing_info = None

    def upload_init(self):
        '''
Beispiel #27
0
def get_oauth():
    oauth = OAuth1(CONSUMER_KEY,
                   client_secret=CONSUMER_SECRET,
                   resource_owner_key=OAUTH_TOKEN,
                   resource_owner_secret=OAUTH_TOKEN_SECRET)
    return oauth
Beispiel #28
0
def get(url):
	auth = OAuth1(ConsumerKey, ConsumerSecret, TokenKey, TokenSecret)
	response = requests.get(url, headers=headers, auth=auth)
	#print response.status_code,
	return response.content
Beispiel #29
0
    def configure(self):
        print(
            "\nTwarc needs to know a few things before it can talk to Twitter on your behalf.\n"
        )

        reuse = False
        if self.consumer_key and self.consumer_secret:
            print(
                "You already have these application keys in your config %s\n" %
                self.config)
            print("consumer key: %s" % self.consumer_key)
            print("consumer secret: %s" % self.consumer_secret)
            reuse = get_input(
                "\nWould you like to use those for your new profile? [y/n] ")
            reuse = reuse.lower() == 'y'

        if not reuse:
            print(
                "\nPlease enter your Twitter application credentials from apps.twitter.com:\n"
            )

            self.consumer_key = get_input('consumer key: ')
            self.consumer_secret = get_input('consumer secret: ')

        request_token_url = 'https://api.twitter.com/oauth/request_token'
        oauth = OAuth1(self.consumer_key, client_secret=self.consumer_secret)
        r = requests.post(url=request_token_url, auth=oauth)

        credentials = parse_qs(r.text)
        if not credentials:
            print("\nError: invalid credentials.")
            print(
                "Please check that you are copying and pasting correctly and try again.\n"
            )
            return

        resource_owner_key = credentials.get('oauth_token')[0]
        resource_owner_secret = credentials.get('oauth_token_secret')[0]

        base_authorization_url = 'https://api.twitter.com/oauth/authorize'
        authorize_url = base_authorization_url + '?oauth_token=' + resource_owner_key
        print(
            '\nPlease log into Twitter and visit this URL in your browser:\n%s'
            % authorize_url)
        verifier = get_input(
            '\nAfter you have authorized the application please enter the displayed PIN: '
        )

        access_token_url = 'https://api.twitter.com/oauth/access_token'
        oauth = OAuth1(self.consumer_key,
                       client_secret=self.consumer_secret,
                       resource_owner_key=resource_owner_key,
                       resource_owner_secret=resource_owner_secret,
                       verifier=verifier)
        r = requests.post(url=access_token_url, auth=oauth)
        credentials = parse_qs(r.text)

        if not credentials:
            print('\nError: invalid PIN')
            print(
                'Please check that you entered the PIN correctly and try again.\n'
            )
            return

        self.access_token = resource_owner_key = credentials.get(
            'oauth_token')[0]
        self.access_token_secret = credentials.get('oauth_token_secret')[0]

        screen_name = credentials.get('screen_name')[0]

        config = self.save_config(screen_name)
        print(
            '\nThe credentials for %s have been saved to your configuration file at %s'
            % (screen_name, self.config))
        print('\n✨ ✨ ✨  Happy twarcing! ✨ ✨ ✨\n')

        if len(config.sections()) > 1:
            print(
                'Note: you have multiple profiles in %s so in order to use %s you will use --profile\n'
                % (self.config, screen_name))
Beispiel #30
0
def oauth_dance(server,
                consumer_key,
                key_cert_data,
                print_tokens=False,
                verify=None):
    if verify is None:
        verify = server.startswith("https")

    # step 1: get request tokens
    oauth = OAuth1(consumer_key,
                   signature_method=SIGNATURE_RSA,
                   rsa_key=key_cert_data)
    r = requests.post(server + "/plugins/servlet/oauth/request-token",
                      verify=verify,
                      auth=oauth)
    request = dict(parse_qsl(r.text))
    request_token = request["oauth_token"]
    request_token_secret = request["oauth_token_secret"]
    if print_tokens:
        print("Request tokens received.")
        print("    Request token:        {}".format(request_token))
        print("    Request token secret: {}".format(request_token_secret))

    # step 2: prompt user to validate
    auth_url = "{}/plugins/servlet/oauth/authorize?oauth_token={}".format(
        server, request_token)
    if print_tokens:
        print("Please visit this URL to authorize the OAuth request:\n\t{}".
              format(auth_url))
    else:
        webbrowser.open_new(auth_url)
        print(
            "Your browser is opening the OAuth authorization for this client session."
        )

    approved = input(
        "Have you authorized this program to connect on your behalf to {}? (y/n)"
        .format(server))

    if approved.lower() != "y":
        exit(
            "Abandoning OAuth dance. Your partner faceplants. The audience boos. You feel shame."
        )

    # step 3: get access tokens for validated user
    oauth = OAuth1(
        consumer_key,
        signature_method=SIGNATURE_RSA,
        rsa_key=key_cert_data,
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret,
    )
    r = requests.post(server + "/plugins/servlet/oauth/access-token",
                      verify=verify,
                      auth=oauth)
    access = dict(parse_qsl(r.text))

    if print_tokens:
        print("Access tokens received.")
        print("    Access token:        {}".format(access["oauth_token"]))
        print("    Access token secret: {}".format(
            access["oauth_token_secret"]))

    return {
        "access_token": access["oauth_token"],
        "access_token_secret": access["oauth_token_secret"],
        "consumer_key": consumer_key,
        "key_cert": key_cert_data,
    }