Skip to content

Added the code samples for Quote Tweets #84

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
Mar 17, 2022
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
64 changes: 64 additions & 0 deletions Quote-Tweets/QuoteTweetsDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;

/*
* Sample code to demonstrate the use of the v2 Quote Tweets endpoint
* */
public class QuoteTweetsDemo {

// To set your environment variables in your terminal run the following line:
// export 'BEARER_TOKEN'='<your_bearer_token>'

public static void main(String args[]) throws IOException, URISyntaxException {
final String bearerToken = System.getenv("BEARER_TOKEN");
if (null != bearerToken) {
//Replace with Tweet ID below
String response = getTweets(20, bearerToken);
System.out.println(response);
} else {
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
}
}

/*
* This method calls the v2 Quote Tweets endpoint by Tweet ID
* */
private static String getTweets(int tweetId, String bearerToken) throws IOException, URISyntaxException {
String tweetResponse = null;

HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();

URIBuilder uriBuilder = new URIBuilder(String.format("https://api.twitter.com/2/tweets/%s/quote_tweets", tweetId));
ArrayList<NameValuePair> queryParameters;
queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
uriBuilder.addParameters(queryParameters);

HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
httpGet.setHeader("Content-Type", "application/json");

HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
tweetResponse = EntityUtils.toString(entity, "UTF-8");
}
return tweetResponse;
}
}
74 changes: 74 additions & 0 deletions Quote-Tweets/quote_tweets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Get Quote Tweets by Tweet ID
// https://developer.twitter.com/en/docs/twitter-api/tweets/quote-tweets-lookup/quick-start

const needle = require('needle');

const tweetId = 20;
const url = `https://api.twitter.com/2/tweets/${tweetId}/quote_tweets`;

// The code below sets the bearer token from your environment variables
// To set environment variables on macOS or Linux, run the export command below from the terminal:
// export BEARER_TOKEN='YOUR-TOKEN'
const bearerToken = process.env.BEARER_TOKEN;

// this is the ID for @TwitterDev
const getQuoteTweets = async () => {
let quoteTweets = [];
let params = {
"max_results": 100,
"tweet.fields": "created_at"
}

const options = {
headers: {
"User-Agent": "v2QuoteTweetsJS",
"authorization": `Bearer ${bearerToken}`
}
}

let hasNextPage = true;
let nextToken = null;
console.log("Retrieving quote Tweets...");
while (hasNextPage) {
let resp = await getPage(params, options, nextToken);
if (resp && resp.meta && resp.meta.result_count && resp.meta.result_count > 0) {
if (resp.data) {
quoteTweets.push.apply(quoteTweets, resp.data);
}
if (resp.meta.next_token) {
nextToken = resp.meta.next_token;
} else {
hasNextPage = false;
}
} else {
hasNextPage = false;
}
}

console.dir(quoteTweets, {
depth: null
});

console.log(`Got ${quoteTweets.length} quote Tweets for Tweet ID ${tweetId}!`);

}

const getPage = async (params, options, nextToken) => {
if (nextToken) {
params.pagination_token = nextToken;
}

try {
const resp = await needle('get', url, params, options);

if (resp.statusCode != 200) {
console.log(`${resp.statusCode} ${resp.statusMessage}:\n${resp.body}`);
return;
}
return resp.body;
} catch (err) {
throw new Error(`Request failed: ${err}`);
}
}

getQuoteTweets();
58 changes: 58 additions & 0 deletions Quote-Tweets/quote_tweets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import requests
import os
import json

# To set your environment variables in your terminal run the following line:
# export 'BEARER_TOKEN'='<your_bearer_token>'


def auth():
return os.environ.get("BEARER_TOKEN")


def create_url():
# Replace with Tweet ID below
tweet_id = 20
return "https://api.twitter.com/2/tweets/{}/quote_tweets".format(tweet_id)


def get_params():
# Tweet fields are adjustable.
# Options include:
# attachments, author_id, context_annotations,
# conversation_id, created_at, entities, geo, id,
# in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
# possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
# source, text, and withheld
return {"tweet.fields": "created_at"}


def create_headers(bearer_token):
headers = {"Authorization": "Bearer {}".format(bearer_token)}
return headers


def connect_to_endpoint(url, headers, params):
response = requests.request("GET", url, headers=headers, params=params)
print(response.status_code)
if response.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(
response.status_code, response.text
)
)
return response.json()


def main():
bearer_token = auth()
url = create_url()
headers = create_headers(bearer_token)
params = get_params()
json_response = connect_to_endpoint(url, headers, params)
print(json.dumps(json_response, indent=4, sort_keys=True))


if __name__ == "__main__":
main()

44 changes: 44 additions & 0 deletions Quote-Tweets/quote_tweets.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# This script uses your bearer token to authenticate and make a request to the Quote Tweets endpoint.
require 'json'
require 'typhoeus'

# The code below sets the bearer token from your environment variables
# To set environment variables on Mac OS X, run the export command below from the terminal:
# export BEARER_TOKEN='YOUR-TOKEN'
bearer_token = ENV["BEARER_TOKEN"]

# Endpoint URL for the Quote Tweets endpoint.
endpoint_url = "https://api.twitter.com/2/tweets/:id/quote_tweets"

# Specify the Tweet ID for this request.
id = 20

# Add or remove parameters below to adjust the query and response fields within the payload
# TODO: See docs for list of param options: https://developer.twitter.com/en/docs/twitter-api/tweets/
query_params = {
"max_results" => 100,
"expansions" => "attachments.poll_ids,attachments.media_keys,author_id",
"tweet.fields" => "attachments,author_id,conversation_id,created_at,entities,id,lang",
"user.fields" => "description"
}

def get_quote_tweets(url, bearer_token, query_params)
options = {
method: 'get',
headers: {
"User-Agent" => "v2RubyExampleCode",
"Authorization" => "Bearer #{bearer_token}"
},
params: query_params
}

request = Typhoeus::Request.new(url, options)
response = request.run

return response
end

endpoint_url = endpoint_url.gsub(':id',id.to_s())

response = get_quote_tweets(endpoint_url, bearer_token, query_params)
puts response.code, JSON.pretty_generate(JSON.parse(response.body))