Skip to content

Commit 653248e

Browse files
author
Jessica Garson
committed
users/me
1 parent f5540be commit 653248e

File tree

3 files changed

+299
-0
lines changed

3 files changed

+299
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from requests_oauthlib import OAuth1Session
2+
import os
3+
import json
4+
5+
# In your terminal please set your environment variables by running the following lines of code.
6+
# export 'CONSUMER_KEY'='<your_consumer_key>'
7+
# export 'CONSUMER_SECRET'='<your_consumer_secret>'
8+
9+
consumer_key = os.environ.get("CONSUMER_KEY")
10+
consumer_secret = os.environ.get("CONSUMER_SECRET")
11+
12+
# User fields are adjustable, options include:
13+
# created_at, description, entities, id, location, name,
14+
# pinned_tweet_id, profile_image_url, protected,
15+
# public_metrics, url, username, verified, and withheld
16+
fields = "created_at,description"
17+
params = {"user.fields": fields}
18+
19+
# Get request token
20+
request_token_url = "https://api.twitter.com/oauth/request_token"
21+
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
22+
23+
try:
24+
fetch_response = oauth.fetch_request_token(request_token_url)
25+
except ValueError:
26+
print(
27+
"There may have been an issue with the consumer_key or consumer_secret you entered."
28+
)
29+
30+
resource_owner_key = fetch_response.get("oauth_token")
31+
resource_owner_secret = fetch_response.get("oauth_token_secret")
32+
print("Got OAuth token: %s" % resource_owner_key)
33+
34+
# # Get authorization
35+
base_authorization_url = "https://api.twitter.com/oauth/authorize"
36+
authorization_url = oauth.authorization_url(base_authorization_url)
37+
print("Please go here and authorize: %s" % authorization_url)
38+
verifier = input("Paste the PIN here: ")
39+
40+
# Get the access token
41+
access_token_url = "https://api.twitter.com/oauth/access_token"
42+
oauth = OAuth1Session(
43+
consumer_key,
44+
client_secret=consumer_secret,
45+
resource_owner_key=resource_owner_key,
46+
resource_owner_secret=resource_owner_secret,
47+
verifier=verifier,
48+
)
49+
oauth_tokens = oauth.fetch_access_token(access_token_url)
50+
51+
access_token = oauth_tokens["oauth_token"]
52+
access_token_secret = oauth_tokens["oauth_token_secret"]
53+
54+
# Make the request
55+
oauth = OAuth1Session(
56+
consumer_key,
57+
client_secret=consumer_secret,
58+
resource_owner_key=access_token,
59+
resource_owner_secret=access_token_secret,
60+
)
61+
62+
response = oauth.get("https://api.twitter.com/2/users/me", params=params)
63+
64+
if response.status_code != 200:
65+
raise Exception(
66+
"Request returned an error: {} {}".format(response.status_code, response.text)
67+
)
68+
69+
print("Response code: {}".format(response.status_code))
70+
71+
json_response = response.json()
72+
73+
print(json.dumps(json_response, indent=4, sort_keys=True))
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
const got = require('got');
2+
const crypto = require('crypto');
3+
const OAuth = require('oauth-1.0a');
4+
const qs = require('querystring');
5+
const readline = require('readline').createInterface({
6+
input: process.stdin,
7+
output: process.stdout
8+
})
9+
10+
// The code below sets the consumer key and consumer secret from your environment variables
11+
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
12+
// export CONSUMER_KEY='YOUR-KEY'
13+
// export CONSUMER_SECRET='YOUR-SECRET'
14+
const consumer_key = process.env.CONSUMER_KEY;
15+
const consumer_secret = process.env.CONSUMER_SECRET;
16+
17+
// These are the parameters for the API request
18+
// specify Tweet IDs to fetch, and any additional fields that are required
19+
// by default, only the Tweet ID and text are returned
20+
const params = 'user.fields=created_at,description&expansions=pinned_tweet_id' // Edit optional query parameters here
21+
22+
const endpointURL = `https://api.twitter.com/2/users/me?{params}`;
23+
24+
// this example uses PIN-based OAuth to authorize the user
25+
const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob';
26+
const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
27+
const accessTokenURL = 'https://api.twitter.com/oauth/access_token';
28+
29+
const oauth = OAuth({
30+
consumer: {
31+
key: consumer_key,
32+
secret: consumer_secret
33+
},
34+
signature_method: 'HMAC-SHA1',
35+
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
36+
});
37+
38+
async function input(prompt) {
39+
return new Promise(async (resolve, reject) => {
40+
readline.question(prompt, (out) => {
41+
readline.close();
42+
resolve(out);
43+
});
44+
});
45+
}
46+
47+
async function requestToken() {
48+
49+
const authHeader = oauth.toHeader(oauth.authorize({
50+
url: requestTokenURL,
51+
method: 'POST'
52+
}));
53+
54+
const req = await got.post(requestTokenURL, {
55+
headers: {
56+
Authorization: authHeader["Authorization"]
57+
}
58+
});
59+
60+
if (req.body) {
61+
return qs.parse(req.body);
62+
} else {
63+
throw new Error('Cannot get an OAuth request token');
64+
}
65+
}
66+
67+
async function accessToken({
68+
oauth_token,
69+
oauth_token_secret
70+
}, verifier) {
71+
72+
const authHeader = oauth.toHeader(oauth.authorize({
73+
url: accessTokenURL,
74+
method: 'POST'
75+
}));
76+
77+
const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`
78+
79+
const req = await got.post(path, {
80+
headers: {
81+
Authorization: authHeader["Authorization"]
82+
}
83+
});
84+
85+
if (req.body) {
86+
return qs.parse(req.body);
87+
} else {
88+
throw new Error('Cannot get an OAuth request token');
89+
}
90+
}
91+
92+
async function getRequest({
93+
oauth_token,
94+
oauth_token_secret
95+
}) {
96+
97+
const token = {
98+
key: oauth_token,
99+
secret: oauth_token_secret
100+
};
101+
102+
const authHeader = oauth.toHeader(oauth.authorize({
103+
url: endpointURL,
104+
method: 'GET'
105+
}, token));
106+
107+
const req = await got(endpointURL, {
108+
headers: {
109+
Authorization: authHeader["Authorization"],
110+
'user-agent': "v2UserLookupJS"
111+
}
112+
});
113+
114+
if (req.body) {
115+
return JSON.parse(req.body);
116+
} else {
117+
throw new Error('Unsuccessful request');
118+
}
119+
}
120+
121+
(async () => {
122+
try {
123+
124+
// Get request token
125+
const oAuthRequestToken = await requestToken();
126+
127+
// Get authorization
128+
authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);
129+
console.log('Please go here and authorize:', authorizeURL.href);
130+
const pin = await input('Paste the PIN here: ');
131+
132+
// Get the access token
133+
const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
134+
135+
// Make the request
136+
const response = await getRequest(oAuthAccessToken);
137+
console.dir(response, {
138+
depth: null
139+
});
140+
141+
} catch (e) {
142+
console.log(e);
143+
process.exit(-1);
144+
}
145+
process.exit();
146+
})();
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
require 'oauth'
2+
require 'json'
3+
require 'typhoeus'
4+
require 'oauth/request_proxy/typhoeus_request'
5+
6+
# The code below sets the consumer key and secret from your environment variables
7+
# To set environment variables on Mac OS X, run the export command below from the terminal:
8+
# export CONSUMER_KEY='YOUR-KEY', CONSUMER_SECRET='YOUR-SECRET'
9+
consumer_key = ENV["CONSUMER_KEY"]
10+
consumer_secret = ENV["CONSUMER_SECRET"]
11+
12+
user_lookup_url = "https://api.twitter.com/2/users/me"
13+
14+
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
15+
:site => 'https://api.twitter.com',
16+
:authorize_path => '/oauth/authenticate',
17+
:debug_output => false)
18+
19+
def get_request_token(consumer)
20+
21+
request_token = consumer.get_request_token()
22+
23+
return request_token
24+
end
25+
26+
def get_user_authorization(request_token)
27+
puts "Follow this URL to have a user authorize your app: #{request_token.authorize_url()}"
28+
puts "Enter PIN: "
29+
pin = gets.strip
30+
31+
return pin
32+
end
33+
34+
def obtain_access_token(consumer, request_token, pin)
35+
token = request_token.token
36+
token_secret = request_token.secret
37+
hash = { :oauth_token => token, :oauth_token_secret => token_secret }
38+
request_token = OAuth::RequestToken.from_hash(consumer, hash)
39+
40+
# Get access token
41+
access_token = request_token.get_access_token({:oauth_verifier => pin})
42+
43+
return access_token
44+
end
45+
46+
# Add or remove optional parameters values from the params object below. Full list of parameters and their values can be found in the docs:
47+
# https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users
48+
query_params = {
49+
# "expansions": "pinned_tweet_id",
50+
# "tweet.fields": "attachments,author_id,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang",
51+
"user.fields": "created_at,description"
52+
}
53+
54+
def user_lookup(url, oauth_params, query_params)
55+
options = {
56+
:method => :get,
57+
headers: {
58+
"User-Agent": "v2UserLookupRuby"
59+
},
60+
params: query_params
61+
}
62+
request = Typhoeus::Request.new(url, options)
63+
oauth_helper = OAuth::Client::Helper.new(request, oauth_params.merge(:request_uri => url))
64+
request.options[:headers].merge!({"Authorization" => oauth_helper.header}) # Signs the request
65+
response = request.run
66+
67+
return response
68+
end
69+
70+
# PIN-based OAuth flow - Step 1
71+
request_token = get_request_token(consumer)
72+
# PIN-based OAuth flow - Step 2
73+
pin = get_user_authorization(request_token)
74+
# PIN-based OAuth flow - Step 3
75+
access_token = obtain_access_token(consumer, request_token, pin)
76+
77+
oauth_params = {:consumer => consumer, :token => access_token}
78+
79+
response = user_lookup(user_lookup_url, oauth_params, query_params)
80+
puts response.code, JSON.pretty_generate(JSON.parse(response.body))

0 commit comments

Comments
 (0)