Skip to content

Manage list sample #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions Manage-Lists/Manage-Followed-Lists/follow_list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Follow a list using PIN-based OAuth to authorize the user
// https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/quick-start
const got = require("got");
const crypto = require("crypto");
const OAuth = require("oauth-1.0a");
const qs = require("querystring");

const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});

// The code below sets the consumer key and consumer secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CONSUMER_KEY='YOUR-KEY'
// export CONSUMER_SECRET='YOUR-SECRET'
const consumer_key = process.env.CONSUMER_KEY;
const consumer_secret = process.env.CONSUMER_SECRET;

// Be sure to replace your-user-id with your own user ID or one of an authenticated user
// You can find a user ID by using the user lookup endpoint
const id = "your-user-id";

// Be sure to add replace list-id-to-follow with the list id you wish to follow.

const data = {
list_id: "list-id-to-follow",
};

const endpointURL = `https://api.twitter.com/2/users/${id}/followed_lists`;

// this example uses PIN-based OAuth to authorize the user
const requestTokenURL =
"https://api.twitter.com/oauth/request_token?oauth_callback=oob";
const authorizeURL = new URL("https://api.twitter.com/oauth/authorize");
const accessTokenURL = "https://api.twitter.com/oauth/access_token";
const oauth = OAuth({
consumer: {
key: consumer_key,
secret: consumer_secret,
},
signature_method: "HMAC-SHA1",
hash_function: (baseString, key) =>
crypto.createHmac("sha1", key).update(baseString).digest("base64"),
});

async function input(prompt) {
return new Promise(async (resolve, reject) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}

async function requestToken() {
const authHeader = oauth.toHeader(
oauth.authorize({
url: requestTokenURL,
method: "POST",
})
);

const req = await got.post(requestTokenURL, {
headers: {
Authorization: authHeader["Authorization"],
},
});
if (req.body) {
return qs.parse(req.body);
} else {
throw new Error("Cannot get an OAuth request token");
}
}

async function accessToken({ oauth_token, oauth_token_secret }, verifier) {
const authHeader = oauth.toHeader(
oauth.authorize({
url: accessTokenURL,
method: "POST",
})
);
const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`;
const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"],
},
});
if (req.body) {
return qs.parse(req.body);
} else {
throw new Error("Cannot get an OAuth request token");
}
}

async function getRequest({ oauth_token, oauth_token_secret }) {
const token = {
key: oauth_token,
secret: oauth_token_secret,
};

const authHeader = oauth.toHeader(
oauth.authorize(
{
url: endpointURL,
method: "POST",
},
token
)
);

const req = await got.post(endpointURL, {
json: data,
responseType: "json",
headers: {
Authorization: authHeader["Authorization"],
"user-agent": "v2followListJS",
"content-type": "application/json",
accept: "application/json",
},
});
if (req.body) {
return req.body;
} else {
throw new Error("Unsuccessful request");
}
}

(async () => {
try {
// Get request token
const oAuthRequestToken = await requestToken();
// Get authorization
authorizeURL.searchParams.append(
"oauth_token",
oAuthRequestToken.oauth_token
);
console.log("Please go here and authorize:", authorizeURL.href);
const pin = await input("Paste the PIN here: ");
// Get the access token
const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
// Make the request
const response = await getRequest(oAuthAccessToken);
console.dir(response, {
depth: null,
});
} catch (e) {
console.log(e);
process.exit(-1);
}
process.exit();
})();
77 changes: 77 additions & 0 deletions Manage-Lists/Manage-Followed-Lists/follow_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from requests_oauthlib import OAuth1Session
import os
import json

# In your terminal please set your environment variables by running the following lines of code.
# export 'CONSUMER_KEY'='<your_consumer_key>'
# export 'CONSUMER_SECRET'='<your_consumer_secret>'

consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")


# Be sure to replace your-user-id with your own user ID or one of an authenticating user
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"

# Be sure to add replace list-id-to-follow with the list id you wish to follow.
payload = {"list_id": "list-id-to-follow"}

# Get request token
request_token_url = "https://api.twitter.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)

try:
fetch_response = oauth.fetch_request_token(request_token_url)
except ValueError:
print(
"There may have been an issue with the consumer_key or consumer_secret you entered."
)

resource_owner_key = fetch_response.get("oauth_token")
resource_owner_secret = fetch_response.get("oauth_token_secret")
print("Got OAuth token: %s" % resource_owner_key)

# Get authorization
base_authorization_url = "https://api.twitter.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")

# Get the access token
access_token_url = "https://api.twitter.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier,
)
oauth_tokens = oauth.fetch_access_token(access_token_url)

access_token = oauth_tokens["oauth_token"]
access_token_secret = oauth_tokens["oauth_token_secret"]

# Make the request
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=access_token,
resource_owner_secret=access_token_secret,
)

# Making the request
response = oauth.post(
"https://api.twitter.com/2/users/{}/followed_lists".format(id), json=payload
)

if response.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(response.status_code, response.text)
)

print("Response code: {}".format(response.status_code))

# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
85 changes: 85 additions & 0 deletions Manage-Lists/Manage-Followed-Lists/follow_list.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request
require 'oauth'
require 'json'
require 'typhoeus'
require 'oauth/request_proxy/typhoeus_request'

# The code below sets the consumer key and secret from your environment variables
# To set environment variables on Mac OS X, run the export command below from the terminal:
# export CONSUMER_KEY='YOUR-KEY', CONSUMER_SECRET='YOUR-SECRET'
consumer_key = ENV["CONSUMER_KEY"]
consumer_secret = ENV["CONSUMER_SECRET"]

# Be sure to replace your-user-id with your own user ID or one of an authenticating user
# You can find a user ID by using the user lookup endpoint
id = "your-user-id"

following_url = "https://api.twitter.com/2/users/#{id}/followed_lists"

# Be sure to add replace list-id-to-follow with the list id you wish to follow.
@list_id = { "list_id": "list-id-to-follow" }

consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
:site => 'https://api.twitter.com',
:authorize_path => '/oauth/authenticate',
:debug_output => false)

def get_request_token(consumer)

request_token = consumer.get_request_token()

return request_token
end

def get_user_authorization(request_token)
puts "Follow this URL to have a user authorize your app: #{request_token.authorize_url()}"
puts "Enter PIN: "
pin = gets.strip

return pin
end

def obtain_access_token(consumer, request_token, pin)
token = request_token.token
token_secret = request_token.secret
hash = { :oauth_token => token, :oauth_token_secret => token_secret }
request_token = OAuth::RequestToken.from_hash(consumer, hash)

# Get access token
access_token = request_token.get_access_token({:oauth_verifier => pin})

return access_token
end


def follow_list(url, oauth_params)
options = {
:method => :post,
headers: {
"User-Agent": "v2followListRuby",
"content-type": "application/json"
},
body: JSON.dump(@list_id)
}
request = Typhoeus::Request.new(url, options)
oauth_helper = OAuth::Client::Helper.new(request, oauth_params.merge(:request_uri => url))
request.options[:headers].merge!({"Authorization" => oauth_helper.header}) # Signs the request
response = request.run

return response
end



# PIN-based OAuth flow - Step 1
request_token = get_request_token(consumer)
# PIN-based OAuth flow - Step 2
pin = get_user_authorization(request_token)
# PIN-based OAuth flow - Step 3
access_token = obtain_access_token(consumer, request_token, pin)

oauth_params = {:consumer => consumer, :token => access_token}


response = follow_list(following_url, oauth_params)
puts response.code, JSON.pretty_generate(JSON.parse(response.body))
Loading