-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
99 lines (86 loc) · 2.61 KB
/
index.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
87
88
89
90
91
92
93
94
95
96
97
98
99
require('dotenv').config();
const argv = require('yargs')
.usage('Usage: $0 [options]')
.alias('d', 'date')
.nargs('d', 1)
.describe('d', 'date used to delete tweets in yyyy-mm-dd')
.alias('n', 'number')
.nargs('n', 1)
.describe('n', 'number of tweets to delete')
.default('n', 100)
.demand(['d'])
.help('h')
.alias('h', 'help')
.argv;
const fs = require('fs');
const Twitter = require('twitter');
console.log("Reading tweet.js file");
let tweetData;
try {
tweetData = JSON.parse(readJson('tweet.js'));
} catch (e) {
console.error("tweet.js not found or invalid format", e);
process.exit();
}
let results = [];
try {
results = JSON.parse(readJson('deleted.js'));
} catch (e) {
writeResult(results)
}
let count = 0;
const cutOffDate = Date.parse(argv.d);
const client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
console.log(`Deleting tweets before ${argv.d}`);
console.log(`Found ${tweetData.length} tweets in total`);
tweetData.forEach(({tweet}) => {
const id_str = tweet.id;
const created_at = new Date(tweet.created_at);
if (!results.includes(id_str) && count < argv.n && created_at < cutOffDate) {
client.post(`statuses/destroy/${id_str}.json`, function (error) {
if (error && error.length > 0) {
const {code, message} = error[0]
if (code === 144) {
results.push(id_str);
} else {
console.error(`Error deleting tweet id: ${id_str}, created at ${created_at}, reason: ${message}`)
}
} else {
results.push(id_str);
count++;
console.log(`Deleted tweet id: ${id_str}, created at ${created_at}`)
}
});
}
});
writeResult(results);
console.log("Finish deleting tweets");
/**
* Reads the JSON file (tweets.js) without variable name
*
* @param filename
* @returns {string}
*/
function readJson(filename) {
return fs.readFileSync(`./${filename}`, 'utf8', function (err, data) {
if (err) throw err;
return data;
}).replace(/window.YTD.tweets.part0 = /g, '');
}
/**
* Output script results to system
*
* @param results
*/
function writeResult(results) {
const file = fs.createWriteStream('deleted.js');
file.on('error', function (err) { /* error handling */
});
file.write(JSON.stringify(results));
file.end();
}