-
Notifications
You must be signed in to change notification settings - Fork 0
/
X_hashtag_search.js
86 lines (75 loc) · 2.36 KB
/
X_hashtag_search.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
75
76
77
78
79
80
81
82
83
84
85
86
searchPosts()
function writeToSheet(posts, users) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
if (!posts) {
return
}
posts.forEach(function(post) {
const user = users.find(u => u.id === post.author_id);
const userId = user ? user.id : 'Unknown';
const username = user ? user.name : 'Unknown';
const screenName = user ? '@' + user.username : 'Unknown';
const followersCount = user ? user.public_metrics.followers_count : 'Unknown';
const followingCount = user ? user.public_metrics.following_count : 'Unknown';
const likeCount = post.public_metrics ? post.public_metrics.like_count : 'Unknown';
const row = [
userId,
screenName,
username,
followersCount,
followingCount,
likeCount
];
sheet.appendRow(row);
});
}
function fetchPosts(hashtag, bearerToken, nextToken) {
const twitterEndpoint = 'https://api.twitter.com/2/posts/search/recent';
const params = {
query: encodeURIComponent(hashtag),
'post.fields': 'author_id,created_at,public_metrics',
'expansions': 'author_id',
'user.fields': 'id,name,username,public_metrics',
max_results: 20
};
if (nextToken) {
params['next_token'] = nextToken;
}
const options = {
method: 'get',
headers: {
'Authorization': 'Bearer ' + bearerToken,
'Content-Type': 'application/json'
},
muteHttpExceptions: true
};
const queryString = Object.keys(params).map(function(key) {
return key + '=' + params[key];
}).join('&');
const response = UrlFetchApp.fetch(twitterEndpoint + '?' + queryString, options);
const responseCode = response.getResponseCode();
const responseBody = response.getContentText();
if (responseCode === 200) {
return JSON.parse(responseBody);
} else {
Logger.log('Error: ' + responseCode + '\n' + responseBody);
return null;
}
}
function searchPosts() {
const hashtag = '#your hashtag here';
const bearerToken = 'your bearer token here';
let nextToken = null;
do {
const json = fetchPosts(hashtag, bearerToken, nextToken);
if (json) {
writeToSheet(json.data, json.includes.users);
// Logger.log(json);
nextToken = json.meta && json.meta.next_token ? json.meta.next_token : null;
console.log(json.data.length)
console.log(nextToken)
} else {
break;
}
} while (nextToken);
}