This repository has been archived by the owner on Feb 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
twitter.js
75 lines (65 loc) · 1.87 KB
/
twitter.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
const Twitter = require("twitter-lite");
const TwitterText = require("twitter-text");
const clipboardy = require("clipboardy");
const {
consumer_key,
consumer_secret,
access_token_key,
access_token_secret,
node_env,
} = require("./keys");
// bot twitter account handle
const handle = "@PreprintBot";
// create twitter api client
client = new Twitter({
consumer_key,
consumer_secret,
access_token_key,
access_token_secret,
});
// reliably calculate tweet length
// (accounts for link shortening, emojis, non-english chars, etc)
function tweetLength(message) {
return TwitterText.parseTweet(message).weightedLength;
}
// publish tweet statuses
async function sendTweets(statuses) {
if (node_env === "test") {
// copy tweet to clipboard for more accurate testing on twitter.com
clipboardy.writeSync(statuses.join("\n\nREPLY\n\n"));
return new Error(
"In test mode. Tweet copied to clipboard instead of sending."
);
} else {
try {
let responses = [];
let in_reply_to_status_id = "";
for (const status of statuses) {
// send tweet
const response = await client.post("statuses/update", {
status,
in_reply_to_status_id,
});
// collect all responses
responses.push(response);
// get id of posted tweet
in_reply_to_status_id = response.id_str;
}
return responses;
} catch (error) {
return apiCatch(error);
}
}
}
// handle api error catch
// https://github.com/draftbit/twitter-lite#api-errors
function apiCatch({ errors }) {
let message;
// API error
if (errors) message = errors.map((error) => error.message).join(" | ");
// other error (network problem, invalid JSON, etc)
else message = "Non-api error sending tweet.";
// return error message
return new Error(message);
}
module.exports = { handle, tweetLength, sendTweets };