Skip to content

Commit 0d2ff81

Browse files
author
Suhem Parack
committed
Added the code samples for Quote Tweets
1 parent 50a0e42 commit 0d2ff81

File tree

4 files changed

+240
-0
lines changed

4 files changed

+240
-0
lines changed

Quote-Tweets/QuoteTweetsDemo.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import org.apache.http.HttpEntity;
2+
import org.apache.http.HttpResponse;
3+
import org.apache.http.NameValuePair;
4+
import org.apache.http.client.HttpClient;
5+
import org.apache.http.client.config.CookieSpecs;
6+
import org.apache.http.client.config.RequestConfig;
7+
import org.apache.http.client.methods.HttpGet;
8+
import org.apache.http.client.utils.URIBuilder;
9+
import org.apache.http.impl.client.HttpClients;
10+
import org.apache.http.message.BasicNameValuePair;
11+
import org.apache.http.util.EntityUtils;
12+
13+
import java.io.IOException;
14+
import java.net.URISyntaxException;
15+
import java.util.ArrayList;
16+
17+
/*
18+
* Sample code to demonstrate the use of the v2 Quote Tweets endpoint
19+
* */
20+
public class QuoteTweetsDemo {
21+
22+
// To set your environment variables in your terminal run the following line:
23+
// export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+
public static void main(String args[]) throws IOException, URISyntaxException {
26+
final String bearerToken = System.getenv("BEARER_TOKEN");
27+
if (null != bearerToken) {
28+
//Replace with Tweet ID below
29+
String response = getTweets(20, bearerToken);
30+
System.out.println(response);
31+
} else {
32+
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
33+
}
34+
}
35+
36+
/*
37+
* This method calls the v2 Quote Tweets endpoint by Tweet ID
38+
* */
39+
private static String getTweets(int tweetId, String bearerToken) throws IOException, URISyntaxException {
40+
String tweetResponse = null;
41+
42+
HttpClient httpClient = HttpClients.custom()
43+
.setDefaultRequestConfig(RequestConfig.custom()
44+
.setCookieSpec(CookieSpecs.STANDARD).build())
45+
.build();
46+
47+
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/tweets/%s/quote_tweets", tweetId));
48+
ArrayList<NameValuePair> queryParameters;
49+
queryParameters = new ArrayList<>();
50+
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
51+
uriBuilder.addParameters(queryParameters);
52+
53+
HttpGet httpGet = new HttpGet(uriBuilder.build());
54+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
55+
httpGet.setHeader("Content-Type", "application/json");
56+
57+
HttpResponse response = httpClient.execute(httpGet);
58+
HttpEntity entity = response.getEntity();
59+
if (null != entity) {
60+
tweetResponse = EntityUtils.toString(entity, "UTF-8");
61+
}
62+
return tweetResponse;
63+
}
64+
}

Quote-Tweets/quote_tweets.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Get Quote Tweets by Tweet ID
2+
// https://developer.twitter.com/en/docs/twitter-api/tweets/quote-tweets-lookup/quick-start
3+
4+
const needle = require('needle');
5+
6+
const tweetId = 20;
7+
const url = `https://api.twitter.com/2/tweets/${tweetId}/quote_tweets`;
8+
9+
// The code below sets the bearer token from your environment variables
10+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
11+
// export BEARER_TOKEN='YOUR-TOKEN'
12+
const bearerToken = process.env.BEARER_TOKEN;
13+
14+
// this is the ID for @TwitterDev
15+
const getQuoteTweets = async () => {
16+
let quoteTweets = [];
17+
let params = {
18+
"max_results": 100,
19+
"tweet.fields": "created_at"
20+
}
21+
22+
const options = {
23+
headers: {
24+
"User-Agent": "v2QuoteTweetsJS",
25+
"authorization": `Bearer ${bearerToken}`
26+
}
27+
}
28+
29+
let hasNextPage = true;
30+
let nextToken = null;
31+
console.log("Retrieving quote Tweets...");
32+
while (hasNextPage) {
33+
let resp = await getPage(params, options, nextToken);
34+
if (resp && resp.meta && resp.meta.result_count && resp.meta.result_count > 0) {
35+
if (resp.data) {
36+
quoteTweets.push.apply(quoteTweets, resp.data);
37+
}
38+
if (resp.meta.next_token) {
39+
nextToken = resp.meta.next_token;
40+
} else {
41+
hasNextPage = false;
42+
}
43+
} else {
44+
hasNextPage = false;
45+
}
46+
}
47+
48+
console.dir(quoteTweets, {
49+
depth: null
50+
});
51+
52+
console.log(`Got ${quoteTweets.length} quote Tweets for Tweet ID ${tweetId}!`);
53+
54+
}
55+
56+
const getPage = async (params, options, nextToken) => {
57+
if (nextToken) {
58+
params.pagination_token = nextToken;
59+
}
60+
61+
try {
62+
const resp = await needle('get', url, params, options);
63+
64+
if (resp.statusCode != 200) {
65+
console.log(`${resp.statusCode} ${resp.statusMessage}:\n${resp.body}`);
66+
return;
67+
}
68+
return resp.body;
69+
} catch (err) {
70+
throw new Error(`Request failed: ${err}`);
71+
}
72+
}
73+
74+
getQuoteTweets();

Quote-Tweets/quote_tweets.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import requests
2+
import os
3+
import json
4+
5+
# To set your environment variables in your terminal run the following line:
6+
# export 'BEARER_TOKEN'='<your_bearer_token>'
7+
8+
9+
def auth():
10+
return os.environ.get("BEARER_TOKEN")
11+
12+
13+
def create_url():
14+
# Replace with Tweet ID below
15+
tweet_id = 20
16+
return "https://api.twitter.com/2/tweets/{}/quote_tweets".format(tweet_id)
17+
18+
19+
def get_params():
20+
# Tweet fields are adjustable.
21+
# Options include:
22+
# attachments, author_id, context_annotations,
23+
# conversation_id, created_at, entities, geo, id,
24+
# in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
25+
# possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
26+
# source, text, and withheld
27+
return {"tweet.fields": "created_at"}
28+
29+
30+
def create_headers(bearer_token):
31+
headers = {"Authorization": "Bearer {}".format(bearer_token)}
32+
return headers
33+
34+
35+
def connect_to_endpoint(url, headers, params):
36+
response = requests.request("GET", url, headers=headers, params=params)
37+
print(response.status_code)
38+
if response.status_code != 200:
39+
raise Exception(
40+
"Request returned an error: {} {}".format(
41+
response.status_code, response.text
42+
)
43+
)
44+
return response.json()
45+
46+
47+
def main():
48+
bearer_token = auth()
49+
url = create_url()
50+
headers = create_headers(bearer_token)
51+
params = get_params()
52+
json_response = connect_to_endpoint(url, headers, params)
53+
print(json.dumps(json_response, indent=4, sort_keys=True))
54+
55+
56+
if __name__ == "__main__":
57+
main()
58+

Quote-Tweets/quote_tweets.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# This script uses your bearer token to authenticate and make a request to the Quote Tweets endpoint.
2+
require 'json'
3+
require 'typhoeus'
4+
5+
# The code below sets the bearer token from your environment variables
6+
# To set environment variables on Mac OS X, run the export command below from the terminal:
7+
# export BEARER_TOKEN='YOUR-TOKEN'
8+
bearer_token = ENV["BEARER_TOKEN"]
9+
10+
# Endpoint URL for the Quote Tweets endpoint.
11+
endpoint_url = "https://api.twitter.com/2/tweets/:id/quote_tweets"
12+
13+
# Specify the Tweet ID for this request.
14+
id = 20
15+
16+
# Add or remove parameters below to adjust the query and response fields within the payload
17+
# TODO: See docs for list of param options: https://developer.twitter.com/en/docs/twitter-api/tweets/
18+
query_params = {
19+
"max_results" => 100,
20+
"expansions" => "attachments.poll_ids,attachments.media_keys,author_id",
21+
"tweet.fields" => "attachments,author_id,conversation_id,created_at,entities,id,lang",
22+
"user.fields" => "description"
23+
}
24+
25+
def get_quote_tweets(url, bearer_token, query_params)
26+
options = {
27+
method: 'get',
28+
headers: {
29+
"User-Agent" => "v2RubyExampleCode",
30+
"Authorization" => "Bearer #{bearer_token}"
31+
},
32+
params: query_params
33+
}
34+
35+
request = Typhoeus::Request.new(url, options)
36+
response = request.run
37+
38+
return response
39+
end
40+
41+
endpoint_url = endpoint_url.gsub(':id',id.to_s())
42+
43+
response = get_quote_tweets(endpoint_url, bearer_token, query_params)
44+
puts response.code, JSON.pretty_generate(JSON.parse(response.body))

0 commit comments

Comments
 (0)