-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathuser_mentions.js
74 lines (61 loc) · 2.04 KB
/
user_mentions.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
68
69
70
71
72
73
74
// Get User mentions timeline by user ID
// https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/quick-start
const needle = require('needle');
const userId = 2244994945;
const url = `https://api.twitter.com/2/users/${userId}/mentions`;
// 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 getUserMentions = async () => {
let userMentions = [];
let params = {
"max_results": 100,
"tweet.fields": "created_at"
}
const options = {
headers: {
"User-Agent": "v2UserMentionssJS",
"authorization": `Bearer ${bearerToken}`
}
}
let hasNextPage = true;
let nextToken = null;
console.log("Retrieving mentions...");
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) {
userMentions.push.apply(userMentions, resp.data);
}
if (resp.meta.next_token) {
nextToken = resp.meta.next_token;
} else {
hasNextPage = false;
}
} else {
hasNextPage = false;
}
}
console.dir(userMentions, {
depth: null
});
console.log(`Got ${userMentions.length} mentions for user ID ${userId}!`);
}
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}`);
}
}
getUserMentions();