Skip to content

Commit 54b1618

Browse files
committed
Adding Reverse chron home timeline code
1 parent aa131cf commit 54b1618

File tree

7 files changed

+737
-0
lines changed

7 files changed

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

0 commit comments

Comments
 (0)