Skip to content

Add mutes lookup code samples #55

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 1 commit into from
Sep 22, 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
142 changes: 142 additions & 0 deletions Mutes-Lookup/lookup_mutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Retrieve accounts muted by authenticated user
// https://developer.twitter.com/en/docs/twitter-api/users/mutes/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";
const endpointURL = `https://api.twitter.com/2/users/${id}/muting`;

// 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: "GET",
},
token
)
);

const req = await got.get(endpointURL, {
responseType: "json",
headers: {
Authorization: authHeader["Authorization"],
"user-agent": "v2MutesLookupJS",
},
});
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();
})();
79 changes: 79 additions & 0 deletions Mutes-Lookup/lookup_mutes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from requests_oauthlib import OAuth1Session
import os
import json

# To set your enviornment variables in your terminal run the following line:
# 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"

params = {"user.fields": "created_at,description"}


# User fields are adjustable, options include:
# created_at, description, entities, id, location, name,
# pinned_tweet_id, profile_image_url, protected,
# public_metrics, url, username, verified, and withheld

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,
)

response = oauth.get(
"https://api.twitter.com/2/users/{}/muting".format(id),params=params
)

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

print("Response code: {}".format(response.status_code))
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
81 changes: 81 additions & 0 deletions Mutes-Lookup/lookup_mutes.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# This script implements the PIN-based OAuth flow to obtain access tokens for a user context request
# It then makes a Mutes lookup request (by usernames) with OAuth 1.0a authentication (user context)
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"

muting_url = "https://api.twitter.com/2/users/#{id}/muting"

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 users_muted(url, oauth_params)
options = {
:method => :get,
headers: {
"User-Agent": "v2MutesLookupRuby"
}
}
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 = users_muted(muting_url, oauth_params)
puts response.code, JSON.pretty_generate(JSON.parse(response.body))