-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtwitterFollowers.ts
90 lines (81 loc) · 2.62 KB
/
twitterFollowers.ts
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
87
88
89
90
import axios from 'axios';
require('dotenv').config();
const Airtable = require('airtable');
interface Followers {
[username: string]: string;
}
const bearerToken = process.env.TWITTER_BEARER_TOKEN;
const base = new Airtable({ apiKey: process.env.AIRTABLE_API_KEY }).base('appiQY5Sa4fJ0mGYG');
const getFollowers = async (username: string): Promise<number> => {
try {
const res = await axios.get(`https://api.twitter.com/2/users/by/username/${username}`, {
headers: {
Authorization: `Bearer ${bearerToken}`
},
params: {
'user.fields': 'public_metrics'
}
});
const followerCount: number = res.data.data.public_metrics.followers_count;
return followerCount;
} catch (err) {
console.error(`Error fetching followers for Twitter username: ${username}`);
console.error(err);
return 0;
}
};
const fetchAndUpdateTwitterFollowers = async (usernames: Followers): Promise<void> => {
for (const username in usernames) {
const recordId = usernames[username];
try {
const followerCount: number = await getFollowers(username);
base('Countries').update([
{
"id": recordId,
"fields": {
'Twitter': followerCount // Storing the follower count as a number
}
}
], function(err, records) {
if (err) {
console.error(`Error updating followers for Twitter username: ${username}`);
console.error(err);
return;
}
console.log(`Successfully updated follower count for ${username}`);
});
} catch (err) {
console.error(`Error processing Twitter username: ${username}`);
console.error(err);
}
}
};
const usernames: Followers = {};
base('Countries').select({
view: 'Grid view'
}).eachPage(
function page(records, fetchNextPage) {
console.log(`Processing ${records.length} records in this page.`);
records.forEach(function (record) {
const username = record.get('Twitter Username'); // Corrected column name
const recordId = record.id;
console.log(`Found record with ID ${recordId} and username ${username}`);
if (username && recordId) {
usernames[username] = recordId;
}
});
fetchNextPage();
},
function done(err) {
if (err) {
console.error("Error during Airtable fetch:", err);
return;
}
console.log(`Total Twitter usernames fetched: ${Object.keys(usernames).length}`);
if (Object.keys(usernames).length === 0) {
console.log("No usernames found. Please check your Airtable configuration.");
} else {
fetchAndUpdateTwitterFollowers(usernames);
}
}
);