-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
451 lines (395 loc) · 12.6 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
require("dotenv").config()
const Twitter = require("twitter")
const TelegramBot = require("node-telegram-bot-api")
const { getUnixTime, endOfMonth, startOfMonth } = require("date-fns")
const REPO_GITHUB_ACTIONS_LINK =
"https://github.com/jsjoeio/twitter-stripe-mrr/actions"
const EXPECTED_ENV_VARS = [
"TWITTER_CONSUMER_KEY",
"TWITTER_CONSUMER_SECRET",
"TWITTER_ACCESS_TOKEN_KEY",
"TWITTER_ACCESS_TOKEN_SECRET",
"STRIPE_API_KEY",
"GOAL",
]
let dryRun = false
const args = process.argv.slice(2)
if (args.includes("--dry-run")) {
dryRun = true
}
// use --dry-run here
// credit: https://stackoverflow.com/a/5767589/3015595
//////////////////////////////
// Main script call
/////////////////////////////
main(dryRun)
//////////////////////////////
// Main script call (end)
/////////////////////////////
/**
* The main function which starts the script
*
* @param {boolean?} dryRun optional param to run the script without updating bio/location on Twitter
*
* @returns {undefined}
*/
async function main(dryRun = false) {
const DRY_RUN_IS_ENABLED = dryRun
try {
// Verify that all the environment variables are set
console.log(`LOG: Verifying environment variables...\n`)
const ACTUAL_ENV_VARS = EXPECTED_ENV_VARS.map((envVar) =>
getEnvironmentVariable(envVar)
)
if (EXPECTED_ENV_VARS.length === ACTUAL_ENV_VARS.length) {
console.log(`\nLOG: Found all expected environment variables\n`)
}
// Use array destructuring to grab the environment variables
const [
TWITTER_CONSUMER_KEY,
TWITTER_CONSUMER_SECRET,
TWITTER_ACCESS_TOKEN_KEY,
TWITTER_ACCESS_TOKEN_SECRET,
STRIPE_API_KEY,
GOAL,
] = ACTUAL_ENV_VARS
let bot
const TELEGRAM_BOT_TOKEN = getEnvironmentVariable(
"TELEGRAM_BOT_TOKEN",
false
)
const TELEGRAM_CHAT_ID = getEnvironmentVariable("TELEGRAM_CHAT_ID", false)
if (TELEGRAM_BOT_TOKEN) {
bot = new TelegramBot(TELEGRAM_BOT_TOKEN)
}
// Create the Twitter client
const twitter = new Twitter({
consumer_key: TWITTER_CONSUMER_KEY,
consumer_secret: TWITTER_CONSUMER_SECRET,
access_token_key: TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: TWITTER_ACCESS_TOKEN_SECRET,
})
await verifyTwitterCredentials(twitter)
// Create the Stripe client
const stripe = require("stripe")(STRIPE_API_KEY)
await verifyStripeCredentials(stripe)
// get Stripe revenue for month (make sure it works)
// Remember January is 0
// Get total for current month
const startRangeTimestamp = getUnixTime(new Date(startOfMonth(new Date())))
const endRangeTimestamp = getUnixTime(new Date(endOfMonth(new Date())))
const totalRevenueForMonth = await getStripeRevenue(
stripe,
startRangeTimestamp,
endRangeTimestamp
)
console.log(`💰 Total revenue for month: ${totalRevenueForMonth}`)
// let's assume my goal is $2k
// and there are 10 squares to fill
// this number should be something like 2000, 5000, etc.
const goalInThousands = parseInt(GOAL)
console.log(
`\nLOG: Calculating MRR squares using goal of ${goalInThousands}\n`
)
const numOfTenRounded = ((totalRevenueForMonth / GOAL) * 10).toPrecision(1)
const mrrIcons = buildMRRIconsForTwitter(numOfTenRounded, GOAL)
console.log(`⬜ ${mrrIcons}`)
const twitterProfileParams = {
location: mrrIcons,
}
if (DRY_RUN_IS_ENABLED) {
console.log(`\nLOG: Script run with --dry-run`)
console.log(`LOG: Skipping Twitter bio/location update`)
sendTelegramMessage(
bot,
TELEGRAM_CHAT_ID,
`It's me again old sport.
A dry-run of your twitter-stripe-mrr script ran with flying colors! 🚀
— Efron 🤵🏻♂️`
)
return 0
}
await updateTwitterBioLocation(
twitter,
twitterProfileParams,
() => {
sendTelegramMessage(
bot,
TELEGRAM_CHAT_ID,
`Oh dear sir, you know I don't like bad news.
Something in the twitter-stripe-mrr script went terribly wrong.
Here is a link to check the logs:
${REPO_GITHUB_ACTIONS_LINK}
— Efron 🤵🏻♂️`
)
},
() => {
sendTelegramMessage(
bot,
TELEGRAM_CHAT_ID,
`Hey old sport. You like good news, eh?
Reporting to you that the twitter-stripe-mrr script ran and updated your Twitter bio as requested!
Here's what it used:
${mrrIcons}
— Efron 🤵🏻♂️`
)
}
)
return 0
} catch (error) {
console.error(error)
}
}
//////////////////////////////
// Helper Functions
/////////////////////////////
/**
* Grabs the environment variable based off the name
* @param {string} name - the name of the variable
* @param {boolean} required - whether or not the environment variable is required. Defaults to true
* @returns {string} the variable if it exists or throws an error
*/
function getEnvironmentVariable(name, required = true) {
// Don't throw for optional environment variable
if (required && !process.env[name]) {
throwErrorAndExit(`could not find ${name} in your environment.`)
}
console.log(`✅ Found ${name} in environment.`)
return process.env[name]
}
/**
* Formats a number to have a K or not
* @param {number} num the number to format
* @returns {string} the `num` formatted with "K"
* @example kFormatter(5000) => 5K
* @link https://stackoverflow.com/a/9461657/3015595 for more information
*/
function kFormatter(num) {
return Math.abs(num) > 999
? Math.sign(num) * (Math.abs(num) / 1000).toFixed(1) + "K"
: Math.sign(num) * Math.abs(num)
}
/**
* Verifies your Twitter credentials
* @param client The Twitter client
* @returns {undefined}
*
* See this {@link https://dev.to/deta/how-i-used-deta-and-the-twitter-api-to-update-my-profile-name-with-my-follower-count-tom-scott-style-l1j| Twitter tutorial} for more information about working with the Twitter API
*/
async function verifyTwitterCredentials(client) {
return await client.get("account/verify_credentials", (err, res) => {
if (err) {
console.error(err)
throwErrorAndExit(`ERROR: could not verify your Twitter credentials`)
}
if (res) {
const followerCount = res.followers_count
console.log(`✅ Verified your Twitter credentials using follower count.`)
console.log(`#️⃣ Your current follower count is ${followerCount}`)
}
})
}
/**
* Updates the location in the Twitter bio
*
* @param {any} twitter - the Twitter client
* @param {{location: string}} twitterProfileParams - the twitter profile parameters
* @param {() => void} errCallback - callback function that's called when an error happens
* @param {() => void} successCallback - callback function that's called when it succeeds
* @returns {undefined}
*/
async function updateTwitterBioLocation(
twitter,
twitterProfileParams,
errCallback = () => {},
successCallback = () => {}
) {
// credit here: https://dev.to/deta/how-i-used-deta-and-the-twitter-api-to-update-my-profile-name-with-my-follower-count-tom-scott-style-l1j
return await twitter.post(
"account/update_profile",
twitterProfileParams,
async (err) => {
if (err) {
console.error(err)
await errCallback()
throwErrorAndExit(`\n Failed to update Twitter bio location.`)
}
console.log("\n🎉 Success! Updated Twitter bio/location")
await successCallback()
}
)
}
/**
* Verifies your Stripe credentials
* @param client The Stripe client
* @returns {undefined}
*
* See this {@link https://stripe.com/docs/development/quickstart| Stripe tutorial} for more information
*/
async function verifyStripeCredentials(client) {
return await client.paymentIntents.create(
{
amount: 1000,
currency: "usd",
payment_method_types: ["card"],
receipt_email: "[email protected]",
},
(err, res) => {
if (err) {
console.error(err)
throwErrorAndExit(`could not verify your Twitter credentials`)
}
if (res) {
const { amount, currency } = res
console.log(
`✅ Verified your Stripe credentials by creating a PaymentIntent.`
)
console.log(
`💰 A payment intent of ${amount} ${currency.toUpperCase()} was created`
)
}
}
)
}
const iconsTypes = {
square: { green: "🟩", yellow: "🟨", gray: "⬜" },
circle: { green: "🟢", yellow: "🟡", gray: "⚪" },
}
/**
* @param {number} n - the progress towards goal out of 10
* @param {string} icon - the progress Icon (square or circle)
* @example there are ten squares total, and n is 5, then it should return
* "MRR: 0 🟩🟩🟩🟩🟩🟨⬜⬜⬜⬜ 5K" or "MRR: 0 🟢🟢🟢🟢🟢🟡⚪⚪⚪⚪ 5K"
*/
function buildMRRIconsForTwitter(n, goal, icon = "square") {
const GOAL_AS_K = kFormatter(goal)
let SQUARES = ""
let count = 0
// Add green squares
for (let i = 0; i < n; i++) {
SQUARES += iconsTypes[icon].green
count += 1
}
// Add one after the last green for progress
if (count !== 10) {
SQUARES += iconsTypes[icon].yellow
count += 1
}
// Fill the rest with white squares
if (count !== 10) {
for (let i = count; i < 10; i++) {
SQUARES += iconsTypes[icon].gray
count += 1
}
}
return `MRR: 0 ${SQUARES} ${GOAL_AS_K}`
}
/**
* Calculates the total monthly revenue in Stripe
*
* @param {any} stripe - the stripe client
* @param {number} startRangeTimestamp - the start range of the month
* @param {number} endRangeTimestamp - the end range of the month
* @returns {number} the total
*/
async function getStripeRevenue(
stripe,
startRangeTimestamp,
endRangeTimestamp
) {
// credit here: https://stackoverflow.com/a/53775391/3015595
const paymentIntentsInCents = await stripe.paymentIntents.list({
created: { gte: startRangeTimestamp, lte: endRangeTimestamp },
limit: 100, // Maximum limit (10 is default)
})
if (!paymentIntentsInCents) {
console.log(`LOG: paymentIntentsInCents`, paymentIntentsInCents)
console.error(
`❌ ERROR: either couldn't get payouts from Stripe or none found for this date range`
)
console.log(
`LOG: This may happen if you run this at the start of the month and there are no payouts yet.`
)
console.log(
`LOG: Try changing the startRangeTimestamp or endRangeTimestamp.`
)
return 0
}
// paymentIntents returned by Stripe API are in cents, so we divide by 100
const paymentIntents = paymentIntentsInCents.data
.filter((paymentIntent) => paymentIntent.status === "succeeded")
.map((paymentIntent) => {
return paymentIntent.amount / 100
})
if (!paymentIntents) {
console.error(
`❌ ERROR: Something went wrong converting the paymentIntentsInCents to dollars`
)
console.log(`LOG: paymentIntents`, paymentIntents)
return 0
}
const amountTotal = calculateAmountTotal(paymentIntents)
if (!amountTotal) {
console.error(`❌ ERROR: Something went wrong calculating the total amount`)
console.log(`LOG: paymentIntentsInCents`, paymentIntentsInCents)
console.log(`LOG: amountTotal`, amountTotal)
return 0
}
return amountTotal
}
/**
* Calculates the the total monthly amount based on a Stripe paymentIntents list
* @param {number[]} paymentIntents - list of paymentIntents in number
* @returns {number} the total
*/
function calculateAmountTotal(paymentIntents) {
if (paymentIntents.length === 0) {
return 0
}
// Some months there may have one payout
if (paymentIntents.length === 1) {
return paymentIntents[0]
}
return paymentIntents.reduce((a, b) => a + b)
}
/**
* Throws an error and exists script
* @param {string} message - the error message to throw
* @param {Error?} err - optional Error
* @returns {void}
*/
function throwErrorAndExit(message, err) {
if (err) {
console.error(err)
}
throw new Error(`❌ ERROR: ${message}`)
process.exit(1)
}
/**
* Sends a Telegram message
* @param {any} bot - the Telegram bot instance
* @param {string} chatId - the chatId to send the message to
* @param {string} message - the message to send
* @returns {Promise<void>} - empty Promise
*/
async function sendTelegramMessage(bot, chatId, message) {
try {
if (bot && chatId) {
const success = await bot.sendMessage(chatId, message)
if (success) {
console.log(`LOG: Telegram Bot sent message, "${message}"`)
}
} else {
console.warn(
`⚠️ WARNING: called "sendTelegramMessage" but missing bot or chatId`
)
}
return null
} catch (error) {
console.error(`❌ ERROR: Telegram Bot failed to send message`)
return null
}
}
//////////////////////////////
// Helper Functions (end)
/////////////////////////////