Skip to content

Instantly share code, notes, and snippets.

@bLd75
Created May 17, 2023 14:20
Show Gist options
  • Save bLd75/65c0796bf94d22ec7d3652c47466c590 to your computer and use it in GitHub Desktop.
Save bLd75/65c0796bf94d22ec7d3652c47466c590 to your computer and use it in GitHub Desktop.
// Fetch the replies of a tweet
const needle = require('needle');
require('dotenv').config();
const url = `https://api.twitter.com/2/tweets/search/recent`;
// Need to have Twitter bearer token
const bearerToken = process.env.BEARER_TOKEN;
const addrLength = 49;
// read all replies from a Twitter post and extract address of lenght 49
const getReplies = async () => {
let replies = [];
let params = {
'query': 'conversation_id:1568775907309146112',
'tweet.fields': 'in_reply_to_user_id',
'max_results': '100',
"user.fields": "created_at"
}
const options = {
headers: {
"User-Agent": "v2RecentSearchJS",
"authorization": `Bearer ${bearerToken}`
}
}
let hasNextPage = true;
let nextToken = null;
console.log("Retrieving replies...");
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) {
replies.push.apply(replies, resp.data);
}
if (resp.meta.next_token) {
nextToken = resp.meta.next_token;
} else {
hasNextPage = false;
}
} else {
hasNextPage = false;
}
}
for (let i = 0; i < replies.length; i++) {
const regex = /[a-zA-Z1-9]{49}$/
let pos = replies[i].text.search(regex);
let addr = replies[i].text.substr(pos, addrLength);
if (addr.length == addrLength) { console.log(addr); }
}
}
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}`);
}
}
getReplies();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment