Skip to content

Instantly share code, notes, and snippets.

@backmeupplz
Created May 17, 2020 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save backmeupplz/b767175efc93ebb09a11d26aa595845d to your computer and use it in GitHub Desktop.
Save backmeupplz/b767175efc93ebb09a11d26aa595845d to your computer and use it in GitHub Desktop.
Todorant Telegram bot upload and download scripts to localize.todorant.com
const dotenv = require('dotenv')
dotenv.config({ path: `${__dirname}/../.env` })
const axios = require('axios')
const unflatten = require('flat').unflatten
const fs = require('fs')
const jsyaml = require('js-yaml')
;(async function getTranslations() {
console.log('==== Getting localizations')
const translations = (
await axios.get('https://localizer.todorant.com/localizations?tag=telegram')
).data.filter((l) => {
return l.tags.indexOf('telegram') > -1
})
console.log('==== Got localizations:')
console.log(JSON.stringify(translations, undefined, 2))
// Get flattened map
const flattenedMap = {} // { key: {en: '', ru: ''}}
translations.forEach((t) => {
const key = t.key
const variants = t.variants.filter((v) => !!v.selected)
flattenedMap[key] = variants.reduce((p, c) => {
p[c.language] = c.text
return p
}, {})
})
console.log('==== Decoded response:')
console.log(flattenedMap)
// Reverse the map
const reversedMap = {}
Object.keys(flattenedMap).forEach((k) => {
const internals = flattenedMap[k]
for (const language in internals) {
const text = internals[language]
if (!reversedMap[language]) {
reversedMap[language] = {}
}
reversedMap[language][k] = text
}
})
const unflattened = unflatten(reversedMap)
console.log('==== Reversed and unflattened map')
console.log(unflattened)
for (const language in unflattened) {
const obj = unflattened[language]
const yaml = jsyaml.safeDump(obj, {
lineWidth: -1,
noCompatMode: true,
})
fs.writeFileSync(`${__dirname}/../locales/${language}.yaml`, yaml)
}
console.log('==== Saved object to the file')
})()
name: English
help: |
Hi there! You can use this bot to quickly add new todos to todorant.com.
/help — this message
/todo — add a todo like <code>/todo Buy milk</code>
/frog — add a frog like <code>/frog Buy milk</code>
/done — log a task that is done like <code>/done Buy milk</code>
/timezone — set up timezone like <code>/timezone -8</code>
/current — see the current task
/zen — turn on zen mode
/login — login to todorant.com
/language — change language
/qr — generate a QR code to login on mobile
Find the commands examples at the end of this message. Cheers!
/frog Answer the gym membership email
/todo Buy milk
/todo 2025-01 Celebrate New Year on my private island
/todo 2020-04-20 Buy cookies
/todo tomorrow: Get magicians together
/todo this wednesday: Fill in Todorant
/done Procrastinate for 20 minutes
/timezone +3
/timezone -8
/timezone 0
language: 'Please, select the language.'
language_selected: '@todorant_bot now speaks English.'
login: 'Please, login to todorant.com using the button below.'
zen_on: 'Welcome to the zen mode! Anything you send me will be handled as if you had <code>/todo</code> command prepended. So do not bother sending <code>/todo Clean fridge</code> or <code>/todo 2020 Watch all of the House MD</code>, just do <code>Clean fridge</code> and <code>2020 Watch all of the House MD</code>. Use /zen to turn this mode off.'
zen_off: You turned off zen mode.
timezone_help: |
Please, use this command like shown below. Thank you!
/timezone +3
/timezone -8
/timezone 0
timezone_success: |
Your timezone was set to UTC${timezone}. Please, check if the time below is your current time.
${time}
all_done: "\U0001F44D You did it! All the tasks for today are done, go get rest or maybe dance a little \U0001F483"
no_todo_text: |
Please, provide text for this todo as shown below.
/todo Buy milk
subscribe_error: 'Please, subscribe at todorant.com to keep using the service.'
past_date_error: Date cannot be in the past.
add_todo_error: 'Oopsie, something went wrong! Make sure to tell us at @todorant_feedback about it!'
name: Русский
help: |
Привет! Используйте этого бота для быстрого добавления задач в todorant.com.
/help — это сообщение
/todo — добавить задачу в формате <code>/todo Купить молоко</code>
/frog — добавить лягушку в формате <code>/frog Купить молоко</code>
/done — добавить выполненную задачу в формате <code>/done Купить молоко</code>
/timezone — установить часовую зону в формате <code>/timezone -8</code>
/current — посмотреть текущую задачу
/zen — включить дзен режим
/login — войти в todorant.com
/language — сменить язык
/qr — сгенерировать QR код для логина на мобильных
Примеры использования команд в конце этого сообщения. Удачи!
/frog Ответить имеил по поводу тренажерки
/todo Купить молоко
/todo 2025-01 Отметить Новый Год на личном острове
/todo 2020-04-20 Купить печенек
/todo завтра: Собрать вместе магов
/todo эта пятница: Заполнить Тудурант
/done Прокрастинировать 20 минут
/timezone +3
/timezone -8
/timezone 0
language: 'Пожалуйста, выберите язык.'
language_selected: '@todorant_bot теперь говорит по-русски.'
login: 'Пожалуйста, зайдите на todorant.com, используя кнопку ниже.'
zen_on: 'Добро пожаловать в дзен-режим! Все, что вы мне пошлете, будет обрабатываться, как будто вы написали перед этим <code>/todo</code>. Не нужно присылать <code>/todo Почистить холодильник</code> или <code>/todo 2020 Посмотреть всего Доктора Хауса</code>, просто пришлите <code>Почистить холодильник</code> или <code>2020 Посмотреть всего Доктора Хауса</code>. Воспользуйтесь командой /zen, чтобы отключить этот режим.'
zen_off: Вы выключили дзен-режим.
timezone_help: |
Пожалуйста, используйте эту команду, как показано ниже. Спасибо!
/timezone +3
/timezone -8
/timezone 0
timezone_success: |
Ваш часовой пояс был установлен на UTC${timezone}. Пожалуйста, проверьте, что время ниже — это ваше текущее время.
${time}
all_done: "\U0001F44D Вы это сделали! Все задачи на сегодня выполнены, идите отдохните — ну или потанцуйте немного \U0001F483"
no_todo_text: |
Пожалуйста, добавьте к этой задаче текст, как показано ниже.
/todo Купить молока
subscribe_error: 'Пожалуйста, подпишитесь на todorant.com, чтобы продолжить пользование сервисом.'
past_date_error: Дата не может быть в прошлом.
add_todo_error: Упс! Что-то пошло не так. Обязательно напишите нам в @todorant_feedback об этом!
const dotenv = require('dotenv')
dotenv.config({ path: `${__dirname}/../.env` })
const axios = require('axios')
const flatten = require('flat')
const fs = require('fs')
const jsyaml = require('js-yaml')
const files = fs.readdirSync(`${__dirname}/../locales`)
const localizations = {}
for (const fileName of files) {
localizations[fileName.split('.')[0]] = jsyaml.safeLoad(
fs.readFileSync(`${__dirname}/../locales/${fileName}`, 'utf8')
)
}
const flattenedLocalizations = {}
Object.keys(localizations).forEach((language) => {
flattenedLocalizations[language] = flatten(localizations[language])
})
const result = {}
const firstLanguage = Object.keys(flattenedLocalizations)[0]
Object.keys(flattenedLocalizations[firstLanguage]).forEach((key) => {
const keyObject = {}
for (const language in flattenedLocalizations) {
if (flattenedLocalizations[language][key]) {
keyObject[language] = flattenedLocalizations[language][key]
}
}
result[key] = keyObject
})
;(async function postLocalizations() {
console.log('==== Posting body:')
console.log(JSON.stringify(result, undefined, 2))
try {
await axios.post(`https://localizer.todorant.com/localizations`, {
localizations: result,
password: process.env.PASSWORD,
username: 'borodutch',
tags: ['telegram'],
})
console.error(`==== Body posted!`)
} catch (err) {
console.error(`==== Error posting: ${err.message}`)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment