-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathfollowing_lookup.js
67 lines (56 loc) · 1.78 KB
/
following_lookup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Fetch the users being followed by a specific account, by ID
// https://developer.twitter.com/en/docs/twitter-api/users/follows/quick-start
const needle = require('needle');
// this is the ID for @TwitterDev
const userId = 2244994945;
const url = `https://api.twitter.com/2/users/${userId}/following`;
const bearerToken = process.env.BEARER_TOKEN;
const getFollowing = async () => {
let users = [];
let params = {
"max_results": 1000,
"user.fields": "created_at"
}
const options = {
headers: {
"User-Agent": "v2FollowingJS",
"Authorization": `Bearer ${bearerToken}`
}
}
let hasNextPage = true;
let nextToken = null;
console.log("Retrieving users this user is following...");
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) {
users.push.apply(users, resp.data);
}
if (resp.meta.next_token) {
nextToken = resp.meta.next_token;
} else {
hasNextPage = false;
}
} else {
hasNextPage = false;
}
}
console.log(users);
console.log(`Got ${users.length} users.`);
}
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}`);
}
}
getFollowing();