# Construct handshaker with wiki URI and consumer
handshaker = Handshaker("https://en.wikipedia.org/w/index.php", consumer_token)

# Step 1: Initialize -- ask MediaWiki for a temporary key/secret for user
redirect, request_token = handshaker.initiate()

# Step 2: Authorize -- send user to MediaWiki to confirm authorization
print("Point your browser to: %s" % redirect)  #
response_qs = input("Response query string: ")

# Step 3: Complete -- obtain authorized key/secret for "resource owner"
access_token = handshaker.complete(request_token, response_qs)

# Construct an auth object with the consumer and access tokens
auth1 = OAuth1(consumer_token.key,
               client_secret=consumer_token.secret,
               resource_owner_key=access_token.key,
               resource_owner_secret=access_token.secret)

# Now, accessing the API on behalf of a user
print("Reading top 10 watchlist items")
response = requests.get("https://en.wikipedia.org/w/api.php",
                        params={
                            'action': "query",
                            'list': "watchlist",
                            'wllimit': 10,
                            'wlprop': "title|comment",
                            'format': "json"
                        },
                        auth=auth1)
doc = response.json()
if 'error' in doc:
Beispiel #2
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: ')

        answered = False
        while not answered:
            print(
                "\nHow would you like twarc to obtain your user keys?\n\n1) generate access keys by visiting Twitter\n2) manually enter your access token and secret\n"
            )
            answer = get_input('Please enter your choice [1/2] ')
            if answer == "1":
                answered = True
                generate = True
            elif answer == "2":
                answered = True
                generate = False

        if generate:
            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]
        else:
            self.access_token = get_input("Enter your Access Token: ")
            self.access_token_secret = get_input(
                "Enter your Access Token Secret: ")
            screen_name = "default"

        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))
def put(url):
    auth = OAuth1(ConsumerKey, ConsumerSecret, TokenKey, TokenSecret)
    response = requests.put(url, headers=headers, auth=auth, data=fileContent)
    return response
Beispiel #4
0
    def set_auth(self, consumer_key, consumer_secret, access_token, acces_secret):

        self.oauth = OAuth1(consumer_key, consumer_secret, access_token, acces_secret)
             'oauth_signature_method':'HMAC-SHA1',
             'oauth_timestamp':'generated-timestamp',
             'oauth_token':'XXXXX-XXXXXXXXX_XXXXXXXXXX',
             'oauth_version':'1.0'
             }
 
'''

#API access
API_KEY = "XXXXXX_XXXXXXXXX_XXXXXXXXXX"
API_SECRET = "XXXXXX_XXXXXXXXX_XXXXXXXXXX"
ACCESS_TOKEN = "XXXXXX_XXXXXXXXX_XXXXXXXXXX"
ACCESS_TOKEN_SECRET = "XXXXXX_XXXXXXXXX_XXXXXXXXXX"

#OAuth1
auth = OAuth1(API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)


#Make a request to api.twitter.com/search
def make_req(keywords):
    for keyword in keywords:
        response = rq.get(url,
                          auth=auth,
                          params={
                              'q': keyword,
                              "lang": "en",
                              "result_type": "mixed",
                              "count": 100
                          })
        #params={'q': 'requests+language:python'})
        if response.status_code != 200:
Beispiel #6
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
 def __init__(self):
     wc_creds = CredentialsUtility.get_wc_api_keys()
     self.env = os.environ.get('ENV', 'test')
     self.base_url = API_HOSTS[self.env]
     self.auth = OAuth1(wc_creds['wc_key'], wc_creds['wc_secret'])
# Grab the time when the script starts.
start_time_epoch = time.time()

accountNum = 'xxxxxxxxx'
domain = 'xxxxxxxx.liveperson.net'
engHistoryURI = 'https://' + domain + '/interaction_history/api/account/' + accountNum + '/interactions/search?'

# oauth stuff
consumer_key = 'xxxxxx'
consumer_secret = 'xxxxxxx'
access_token = 'xxxxxxx'
access_token_secret = 'xxxxxxx'
oauth = OAuth1(consumer_key,
			   client_secret=consumer_secret,
			   resource_owner_key=access_token,
			   resource_owner_secret=access_token_secret,
			   signature_method='HMAC-SHA1',
			   signature_type='auth_header')

client = requests.session()
postheader = {'content-type': 'application/json'}
# Customize the body for what you want 
body={
	'interactive':'true',
	'ended':'true',
	'start':{
		# http://www.epochconverter.com/ - grab the millisecond version
		'from':'1451606399000', #Dec 31 2015
		'to':'1453334399000' #jan 15 2016
	},
	'skillIds': [
Beispiel #9
0
import requests
from requests_oauthlib import OAuth1
import configparser

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 = 'path/to/video/file'

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):
    MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json'
    POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/update.json'

    '''
    Defines video tweet properties
    '''
    self.video_filename = file_name
    self.total_bytes = os.path.getsize(self.video_filename)
    self.media_id = None
Beispiel #10
0
import nltk
import collections
import nltk
nltk.download('punkt')
from nltk.tokenize import TweetTokenizer
import os

auth_params = {
    'app_key': 'XXXXXXXXXXXXXXXXXXXXXXXX',
    'app_secret': 'XXXXXXXXXXXXXXXXXXXXXXXX',
    'oauth_token': 'XXXXXXXXXXXXXXXXXXXXXXXX',
    'oauth_token_secret': 'XXXXXXXXXXXXXXXXXXXXXXXX'
}

# Creating an OAuth Client connection
auth = OAuth1(auth_params['app_key'], auth_params['app_secret'],
              auth_params['oauth_token'], auth_params['oauth_token_secret'])

# Words about negative/positive for query. You can change
words = [
    {
        'word': 'bad',
        'value': 0
    },
    {
        'word': 'sad',
        'value': 0
    },
    {
        'word': 'sadness',
        'value': 0
    },
import requests
from requests_oauthlib import OAuth1
import argparse
import sys
import string
import simplejson
import json
import os
import datetime
import csv

url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('wsa9XC1P3lfM0IihoICjgJUjw', 'fa7RwF9HoeGChYTIcpgignp2WqgsKPWGpegC2IkvxaW0BFERSi',
                  '788872315253755904-J0Pe363NDpZaBYku6iex8KUdabudXiq', '1vkKNfixNHT4CI8g5UZg5UYbOAGL2zANEsCnf0bQjIewG')
requests.get(url, auth=auth)

parser = argparse.ArgumentParser(description='Take the search string and value from 1 to 5 for Analysis you want to perform as input')
#parser.add_argument('search',metavar='N', nargs=2, help='Search term and analysis value')
parser.add_argument("-s", "--search", type=str, required=True)
parser.add_argument("-a", "--analysis", type=int, default=5)

args = parser.parse_args()
payload = {'q': args.search, 'result_type': 'recent'}
r = requests.get('https://api.twitter.com/1.1/search/tweets.json',auth=auth, params=payload)

#We will use the variables day, month, year, hour, minute and second for our output file name#
now = datetime.datetime.now()
day = int(now.day)
month = int(now.month)
year = int(now.year)
hour = int(now.hour)
 def _create_oauth_session(self, oauth_dict):
     oauth = OAuth1(oauth_dict['consumer_key'],
                    rsa_key=oauth_dict['key_cert'], signature_method=SIGNATURE_RSA,
                    resource_owner_key=oauth_dict['access_token'],
                    resource_owner_secret=oauth_dict['access_token_secret'])
     self._session.auth = oauth
Beispiel #13
0
import requests, json, config
from requests_oauthlib import OAuth1

url = 'https://stream.twitter.com/1.1/statuses/sample.json'
auth = OAuth1(config.consumerKey, config.consumerSecret, config.accessToken,
              config.accessSecret)
file = open('tweets.txt', 'w')
r = requests.get(url, auth=auth, stream=True)

for line in r.iter_lines():
    if line:
        decoded_line = line.decode('utf-8')
        text = json.loads(decoded_line)
        print(text)
        file.write(text + '\n')
Beispiel #14
0
  tokenfile = open(tokenfilename, "r")
  token_credentials = json.load(tokenfile)
  tokenfile.close()

client_key = mapmyfitness_apikeys.consumer_key
client_secret = mapmyfitness_apikeys.secret_key



if token_credentials is None or  len(token_credentials) != 2:

  temporary_credentials_url = 'http://api.mapmyfitness.com/3.1/oauth/request_token'

  callback_uri = 'http://' + os.uname()[1] + ':12345/'

  oauth = OAuth1(client_key, client_secret=client_secret, callback_uri=callback_uri, signature_type='BODY')

  r = requests.post(url=temporary_credentials_url,
      headers={'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/x-www-form-urlencoded'},
      auth=oauth)

  print(r.request.body)

  temporary_credentials = urlparse.parse_qs(r.content)

  authorize_url = 'https://www.mapmyfitness.com/oauth/authorize/?oauth_token=%s&oauth_callback=%s' % (temporary_credentials['oauth_token'][0], escape(callback_uri))

  print "sending to url"
  print "authorize_url: %s" % authorize_url
Beispiel #15
0
 def createAuth(cls):
     return OAuth1(cls.HATHI_CLIENT_KEY,
                   client_secret=cls.HATHI_CLIENT_SECRET,
                   signature_type='query')
Beispiel #16
0
    def _connect(self, method, endpoint, params=None, headers=None, body=None):
        self.running = True

        error_count = 0
        # https://developer.twitter.com/en/docs/twitter-api/v1/tweets/filter-realtime/guides/connecting
        stall_timeout = 90
        network_error_wait = network_error_wait_step = 0.25
        network_error_wait_max = 16
        http_error_wait = http_error_wait_start = 5
        http_error_wait_max = 320
        http_420_error_wait_start = 60

        auth = OAuth1(self.consumer_key, self.consumer_secret,
                      self.access_token, self.access_token_secret)

        if self.session is None:
            self.session = requests.Session()
            self.session.headers["User-Agent"] = self.user_agent

        url = f"https://stream.twitter.com/1.1/{endpoint}.json"

        try:
            while self.running and error_count <= self.max_retries:
                try:
                    with self.session.request(method,
                                              url,
                                              params=params,
                                              headers=headers,
                                              data=body,
                                              timeout=stall_timeout,
                                              stream=True,
                                              auth=auth,
                                              verify=self.verify,
                                              proxies=self.proxies) as resp:
                        if resp.status_code == 200:
                            error_count = 0
                            http_error_wait = http_error_wait_start
                            network_error_wait = network_error_wait_step

                            self.on_connect()
                            if not self.running:
                                break

                            for line in resp.iter_lines(
                                    chunk_size=self.chunk_size):
                                if line:
                                    self.on_data(line)
                                else:
                                    self.on_keep_alive()
                                if not self.running:
                                    break

                            if resp.raw.closed:
                                self.on_closed(resp)
                        else:
                            self.on_request_error(resp.status_code)
                            if not self.running:
                                break

                            error_count += 1

                            if resp.status_code == 420:
                                if http_error_wait < http_420_error_wait_start:
                                    http_error_wait = http_420_error_wait_start

                            sleep(http_error_wait)

                            http_error_wait *= 2
                            if http_error_wait > http_error_wait_max:
                                http_error_wait = http_error_wait_max
                except (requests.ConnectionError, requests.Timeout,
                        requests.exceptions.ChunkedEncodingError, ssl.SSLError,
                        urllib3.exceptions.ReadTimeoutError,
                        urllib3.exceptions.ProtocolError) as exc:
                    # This is still necessary, as a SSLError can actually be
                    # thrown when using Requests
                    # If it's not time out treat it like any other exception
                    if isinstance(exc, ssl.SSLError):
                        if not (exc.args and "timed out" in str(exc.args[0])):
                            raise

                    self.on_connection_error()
                    if not self.running:
                        break

                    sleep(network_error_wait)

                    network_error_wait += network_error_wait_step
                    if network_error_wait > network_error_wait_max:
                        network_error_wait = network_error_wait_max
        except Exception as exc:
            self.on_exception(exc)
        finally:
            self.session.close()
            self.running = False
            self.on_disconnect()
Beispiel #17
0
 def get_auth(self, username, password):
     return OAuth1(client_key=username, client_secret=password)
Beispiel #18
0
def main():

    args = parse_args()

    configure_logging(args.debug)

    # Get OAuth
    logging.info('Verifying credentials')
    logging.debug('API_KEY: %s', args.api_key)
    logging.debug('API_SECRET: %s', args.api_secret)
    logging.debug('ACCESS_TOKEN: %s', args.access_token)
    logging.debug('ACCESS_TOKEN_SECRET: %s', args.token_secret)

    auth = OAuth1(args.api_key, args.api_secret, args.access_token,
                  args.token_secret)
    requests.get(URL_CREDS, auth=auth)

    # Search params
    params = {'q': args.query, 'count': args.count}

    if args.since_id is not None:
        params[SINCE_ID_PARAM] = args.since_id

    if args.max_id is not None:
        params[MAX_ID_PARAM] = args.max_id

    logging.info('Querying twitter for: %s', args.query)

    i = 0
    total_tweets = 0
    newest_id = 0
    while True:

        # Get Tweets
        logging.info(
            'SINCE_ID: %s ',
            params[SINCE_ID_PARAM] if SINCE_ID_PARAM in params else '')
        logging.info('MAX_ID:   %s',
                     params[MAX_ID_PARAM] if MAX_ID_PARAM in params else '')

        r = requests.get(URL_SEARCH_TWEETS, auth=auth, params=params)

        if r.status_code != 200:
            logging.debug('Reponse %s', r.status_code)
            logging.debug(r.headers)
            logging.debug(r.content)

            waiting_time = int(r.headers['x-rate-limit-reset']
                               ) - datetime.datetime.now().timestamp() + 1
            if waiting_time < 0:
                waiting_time = 0
            logging.info('Rate limit reached: %s seconds to reset...zZz',
                         waiting_time)
            time.sleep(waiting_time)
            continue

        n_tweets = len(r.json()['statuses'])
        total_tweets = total_tweets + n_tweets
        logging.info('Retrieved %s - Total %s', n_tweets, total_tweets)

        if n_tweets == 0:
            break

        # Write JSON to disk
        fo = open('%s/%s_%s.json' % (args.path, args.file_prefix, i), "wb")
        logging.info('Writing output to: %s', fo.name)
        fo.write(r.content)
        fo.close()

        # Get the minimum ID recovered
        # As Twitter returns most recent first, we have to
        # paginate results backwards in time, from newer to older
        # See: https://dev.twitter.com/rest/public/timelines
        if MAX_ID_PARAM in params:
            min_id = params[MAX_ID_PARAM]
        else:
            min_id = sys.maxsize

        for tweet in r.json()['statuses']:
            current_id = tweet['id']
            if current_id < min_id:
                min_id = current_id
            if current_id > newest_id:
                newest_id = current_id

        # max_id is inclusive, so we have to substract 1 to avoid retrieving
        # the same tweet twice
        params[MAX_ID_PARAM] = min_id - 1

        i = i + 1

    logging.info('Tweets retrieved: %s.', total_tweets)
    if total_tweets > 0:
        logging.info('This is the end. Newest id: %s', newest_id)
Beispiel #19
0
from requests_oauthlib import OAuth1
import json
import requests
import secrets  # file that contains your OAuth credentials

CACHE_FILENAME = "twitter_cache.json"
CACHE_DICT = {}

client_key = secrets.TWITTER_API_KEY
client_secret = secrets.TWITTER_API_SECRET
access_token = secrets.TWITTER_ACCESS_TOKEN
access_token_secret = secrets.TWITTER_ACCESS_TOKEN_SECRET

oauth = OAuth1(client_key,
               client_secret=client_secret,
               resource_owner_key=access_token,
               resource_owner_secret=access_token_secret)


def test_oauth():
    ''' Helper function that returns an HTTP 200 OK response code and a 
    representation of the requesting user if authentication was 
    successful; returns a 401 status code and an error message if 
    not. Only use this method to test if supplied user credentials are 
    valid. Not used to achieve the goal of this assignment.'''

    url = "https://api.twitter.com/1.1/account/verify_credentials.json"
    auth = OAuth1(client_key, client_secret, access_token, access_token_secret)
    authentication_state = requests.get(url, auth=auth).json()
    return authentication_state
Beispiel #20
0
try:
	import json
except ImportError:
	import simplejson as json
from twitter import Twitter,OAuth
from requests_oauthlib import OAuth1
import csv
import pandas as pd
import requests

ACCESS_TOKEN='1001763355001081856-bIqkKr2Wlv9Wh09dTQlC5oywsZIyqo'
ACCESS_SECRET='98ftA7Ugf9i8SGiPxLg5qUkuL5aT0GMNh6DCc2xM58lky'
CONSUMER_KEY='sDCUDdWy9UVc3O9yXNj9yuNK6'
CONSUMER_SECRET='x6yApBCjqf82hbFO1nDa5K4sXNTqh0lPmO9iMWyVEzgOb5Rfjq'

auth=OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET)
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
requests.get(url,auth=auth)
entity_url="https://api.twitter.com/1.1/statuses/retweets/"
colnames=["Similarity","Number","Text","Id"]
label=input("Enter the claim number:")
label="claim"+str(label)
inputFile=label+"_sorted.csv"
df=pd.read_csv(inputFile,names=colnames,sep="|")
values=df['Id']
for val in values:
	link=entity_url+str(val)+".json"
	r=requests.get(link,auth=auth)
	#for tweet in r.json()
	response=r.json()
	print(response)
Beispiel #21
0
import os
import sys
import time
import json
import requests
from requests_oauthlib import OAuth1
import constants



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


oauth = OAuth1(constants.CONSUMER_KEY,
               client_secret=constants.CONSUMER_SECRET,
               resource_owner_key=constants.ACCESS_KEY,
               resource_owner_secret=constants.ACCESS_SECRET)


class VideoTweet:

    def __init__(self, file_name):
        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):
        print('INIT')
        request_data = {
            'command': 'INIT',
#!/usr/bin/env python
# coding: UTF-8

from requests_oauthlib import OAuth1
from requests_oauthlib import OAuth1Session
import requests
import subprocess
import json

url = "https://stream.twitter.com/1.1/statuses/filter.json"
tweet_url = "https://api.twitter.com/1.1/statuses/update.json"

with open('token.json', 'r') as f:
    TOKEN = json.load(f)

auth = OAuth1(**TOKEN)
twitter = OAuth1Session(**TOKEN)
r = requests.post(url, auth=auth, stream=True, data={'track': '@Tkon_bot'})

print("ready.")
for line in r.iter_lines():
    if line != '':
        #print(line.decode('utf-8'))
        try:
            data = json.loads(line.decode('utf-8'))
        except json.decoder.JSONDecodeError:
            continue

        get_time = subprocess.check_output('date').decode('utf-8')
        print('@' + data['user']['screen_name'] + ':' + data['text'])
        textv = data['text'].split(' ')
Beispiel #23
0
import re
import datetime
import time
import os
import pprint
import configparser
from requests_oauthlib import OAuth1

config = configparser.ConfigParser()
config.read('roguelike.ini', encoding="UTF-8")

api_key = config.get('api_key', 'api_key')
api_secret = config.get('api_key', 'api_secret')
token = config.get('api_key', 'token')
token_secret = config.get('api_key', 'token_secret')
auth = OAuth1(api_key, api_secret, token, token_secret)

query = config.get('query', 'query')

url = "https://api.twitter.com/1.1/search/tweets.json?&q=" + query
params = {
    'count': 100,
    'include_rts': False,
    'result_type': 'recent',
    'include_entities': True
}

res = requests.get(url, auth=auth, params=params)
if res.status_code == 200:
    print("OK")
else:
Beispiel #24
0
def send_answer(text, tweet_id):
    data = {'status': f'{text}', 'in_reply_to_status_id': f'{tweet_id}'}
    requests.post(endpoint_answer,
                  data=data,
                  auth=OAuth1(secrets['key'], secrets['secret_key'],
                              secrets['access'], secrets['secret_access']))
Beispiel #25
0
    def __init__(self,
                 app_key,
                 app_secret,
                 oauth_token,
                 oauth_token_secret,
                 timeout=300,
                 retry_count=None,
                 retry_in=10,
                 client_args=None,
                 handlers=None,
                 chunk_size=1):
        """Streaming class for a friendly streaming user experience
        Authentication IS required to use the Twitter Streaming API

        :param app_key: (required) Your applications key
        :param app_secret: (required) Your applications secret key
        :param oauth_token: (required) Used with oauth_token_secret to make
                            authenticated calls
        :param oauth_token_secret: (required) Used with oauth_token to make
                                   authenticated calls
        :param timeout: (optional) How long (in secs) the streamer should wait
                        for a response from Twitter Streaming API
        :param retry_count: (optional) Number of times the API call should be
                            retired
        :param retry_in: (optional) Amount of time (in secs) the previous
                         API call should be tried again
        :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 handlers: (optional) Array of message types for which
                         corresponding handlers will be called

        :param chunk_size: (optional) Define the buffer size before data is
                           actually returned from the Streaming API. Default: 1
        """

        self.auth = OAuth1(app_key, app_secret, oauth_token,
                           oauth_token_secret)

        self.client_args = client_args or {}
        default_headers = {'User-Agent': 'Twython Streaming 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)
        self.client_args['timeout'] = timeout

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

        # 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', 'headers', 'hooks', 'max_redirects', 'proxies'):
                setattr(self.client, k, v)
                self.client_args.pop(k)  # Pop, pop!

        self.api_version = '1.1'

        self.retry_in = retry_in
        self.retry_count = retry_count

        # Set up type methods
        StreamTypes = TwythonStreamerTypes(self)
        self.statuses = StreamTypes.statuses
        self.user = StreamTypes.user
        self.site = StreamTypes.site

        self.connected = False

        self.handlers = handlers if handlers else \
            ['delete', 'limit', 'disconnect']

        self.chunk_size = chunk_size
Beispiel #26
0
## SI 206 - HW
##Emil Meriles
##SEC 005

#usage should be python3 hw5_twitter.py <username> <num_tweets>
username = sys.argv[1]
num_tweets = sys.argv[2]

consumer_key = secret_data.CONSUMER_KEY
consumer_secret = secret_data.CONSUMER_SECRET
access_token = secret_data.ACCESS_KEY
access_secret = secret_data.ACCESS_SECRET

#Code for OAuth starts
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1(consumer_key, consumer_secret, access_token, access_secret)
data=requests.get(url, auth=auth)
#Code for OAuth ends

#Write your code below:
#Code for Part 3:Caching

CACHE_FNAME = 'twitter_cache.json'
try:
    cache_file = open(CACHE_FNAME, 'r')
    cache_contents = cache_file.read()
    CACHE_DICTION = json.loads(cache_contents)
    cache_file.close()
except:
    CACHE_DICTION = {}
#Finish parts 1 and 2 and then come back to this
def delete(url):
    auth = OAuth1(ConsumerKey, ConsumerSecret, TokenKey, TokenSecret)
    response = requests.delete(url, headers=headers, auth=auth)
    return response
Beispiel #28
0
def submit(request, myname, myfood, towhere, fromwhere):
    headeroauth = OAuth1(client_key,
                         client_secret,
                         resource_owner_key,
                         resource_owner_secret,
                         signature_type='auth_header')

    userurl = 'https://api.twitter.com/1.1/account/verify_credentials.json'
    userinfo = requests.get(userurl, auth=headeroauth).json()
    theid = userinfo["id_str"]
    screen_name = userinfo["screen_name"]

    #print(theid)
    url = 'https://api.twitter.com/1.1/direct_messages/new.json?'

    friendsURL = 'https://api.twitter.com/1.1/friends/ids.json'
    params = {
        'screen_name': screen_name,
        'count': 200,
    }
    friendsresponse = requests.get(friendsURL, params=params,
                                   auth=headeroauth).json()
    friendslist = friendsresponse["ids"]

    followsURL = 'https://api.twitter.com/1.1/followers/ids.json'
    followsresponse = requests.get(followsURL, params=params,
                                   auth=headeroauth).json()
    followslist = followsresponse["ids"]

    friendfollows = []
    for e in friendslist:
        if e in followslist:
            friendfollows.append(e)

    #count=0
    #frienddict={}
    #for userobject in friendlist:
    #    if (count==5):
    #        break
    #    key=str(count)+"name"
    #    frienddict[key]=userobject['name']
    #    frienddict[str(count)+key]=userobject['screen_name']
    #    count+=1
    #print(frienddict)
    userURL = 'https://api.twitter.com/1.1/users/show.json'
    frienddict = {}
    i = 0
    while i < 5 and i < len(friendfollows):
        x = friendfollows[i]
        frienddict[str(i) + 'name'] = requests.get(
            userURL, params={
                'user_id': x
            }, auth=headeroauth).json()['name']

        postdata = {
            'text':
            myname + " is asking for " + myfood + " from " + fromwhere +
            " delivered to " + towhere + ". Thanks!",
            'user_id':
            x,
        }
        #r = requests.post(url, data=postdata,auth=headeroauth)
        i = i + 1

    #print(r.text)
    return render(request, 'confirmation.html', context=frienddict)
Beispiel #29
0
import json
import requests
import os
from requests_oauthlib import OAuth1
# consumer_key = chave de acesso para a api
# consumer_ky_secret = chave secreta de acesso da api
# token_key = chave de acesso do usuario
# token_secret = chave secreta de acesso do usuario
consumer_key = ''
consumer_key_secret = ''
token_key = ''
token_secret = ''
auth = OAuth1(
    consumer_key,
    consumer_key_secret,
    token_key,
    token_secret,
)
# URLS PARA ESPECIFICAR OQUE QUER FAZER
url_base = 'https://api.twitter.com/1.1/'

urls = {
    "1.1": {
        "user": {
            "followers_list": "followers/list.json",
            "followers_ids": "followers/ids.json",
            "friends_ids": "friends/ids.json",
            "friends_list": "friends/list.json",
            'lookup': 'users/lookup.json'
        },
        "direct": {
Beispiel #30
0
    """
    url = 'https://api.twitter.com/1.1/search/tweets.json'
    tweets = []

    for search_terms in args:
        params = {'q': search_terms, 'lang': 'en', 'count': count}
        response = requests.get(url, auth=auth, params=params)
        tweets += response.json()['statuses']

    return tweets


with open(config('TWITTER_CREDENTIALS'), 'r') as f:
    secrets = json.load(f)

auth = OAuth1(secrets['api_key'], secrets['api_secret_key'],
              secrets['access_token'], secrets['access_token_secret'])

if __name__ == "__main__":
    # prompt a user for search terms
    search_terms = input("Enter search terms separated by commas: ")
    search_terms = search_terms.split(',')
    tweets = get_tweets(search_terms)

    # save the tweets to a local file for analysis
    with open('tweets.json', 'w') as f:
        json.dump(tweets, f, indent=4, separators=(",", ":"))

    # output sentiment predictions of tweets
    for tweet in tweets:
        prediction_response = get_prediction(tweet['text'])
        if prediction_response.status_code == 200: