From 800af40c9230c42d45f682180428a1c2c2f0f4f8 Mon Sep 17 00:00:00 2001 From: sheychen Date: Sun, 28 Apr 2019 14:44:56 +0200 Subject: [PATCH] Cleanup --- index.js | 49 ++++++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/index.js b/index.js index 7ec20e1..6b4a55b 100644 --- a/index.js +++ b/index.js @@ -2,36 +2,43 @@ require('dotenv').config() const database = require('./database.json') const Mastodon = require('mastodon-api') +function getSubKey(arr, key, lang) { + return arr[`${key}_${lang}`] || arr[lang] +} +function randomValue(arr) { + return arr[Math.floor(Math.random() * arr.length)] +} + const TOKEN = 'ACCESS_TOKEN' const URL = 'API_URL' const VISIBILITY = 'VISIBILITY' -Object.entries(process.env) +const CONF = process.env + +Object.keys(CONF) .filter(e => e[0].startsWith(TOKEN)) - .forEach(e => { - const lang = e[0].substring(TOKEN.length + 1) - const visi = process.env[`${VISIBILITY}_${lang}`] || process.env[VISIBILITY] + .map(key => key.substring(TOKEN.length + 1)) + .forEach(async (lang) => { + const getOption = (key) => getSubKey(CONF, key, lang) + + const visi = getOption(VISIBILITY) const M = new Mastodon({ - access_token: process.env[`${TOKEN}_${lang}`] || process.env[TOKEN], - api_url: `${process.env[`${URL}_${lang}`] || process.env[URL]}/api/v1/`, + access_token: getOption(TOKEN), + api_url: `${getOption(URL)}/api/v1/`, timeout_ms: 60 * 1000 }) - M.get('accounts/verify_credentials').then( - me => { - if (me.data.error) { - console.error(me.data.error) - return - } + const me = await M.get('accounts/verify_credentials') + if (me.data.error) throw me.data.error - M.get(`accounts/${me.data.id}/followers`, { limit: 9999 }).then(fol => { - for (const follow of fol.data) { - const messages = database[Math.floor(Math.random() * database.length)] - const text = lang.length > 0 ? messages[lang] : '\n' + Object.entries(messages).map(m => `[${m[0]}] ${m[1]}`).join('\n\n') - - M.post('statuses', { status: `@${follow.acct} ${text}`, visibility: visi }) - } - }) + const fols = await M.get(`accounts/${me.data.id}/followers`, { limit: 9999 }) + for (const follow of fols.data) { + M.post('statuses', { + status: `@${follow.acct} ${lang.length > 0 ? + randomValue(database)[lang] : + '\n' + Object.entries(randomValue(database)).map(m => `[${m[0]}] ${m[1]}`).join('\n\n') + }`, visibility: visi }) - }) + } + }) \ No newline at end of file