Skip to content

Commit 09ad6fa

Browse files
authored
Merge pull request #57 from twitterdev/manage-list-sample
Manage list sample
2 parents cde0175 + 50b4106 commit 09ad6fa

29 files changed

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

0 commit comments

Comments
 (0)