|
const Bluebird = require('bluebird@3.5.0') |
|
const axios = require('axios@0.15.2') |
|
|
|
const TG = (TG_TOKEN) => (path, options) => axios(Object.assign({}, { |
|
method: 'POST', |
|
url: `https://api.telegram.org/bot${TG_TOKEN}/${path}`, |
|
json: true |
|
}, options)) |
|
.then(resp => { |
|
const data = resp.data |
|
console.log('Response from TG %j', data) |
|
return data |
|
}) |
|
|
|
const setWebHook = (tg, url) => { |
|
return tg('setWebHook', {data: {url: url}}) |
|
} |
|
|
|
const sendMessage = (tg, chat_id, text) => { |
|
return tg('sendMessage', {data: {chat_id: chat_id, text: text}}) |
|
} |
|
|
|
const sendDocument = (tg, chat_id, document) => { |
|
return tg('sendDocument', {data: {chat_id: chat_id, document: document}}) |
|
} |
|
|
|
const getOwnURL = (ctx) => { |
|
const wtParams = JSON.parse(Buffer.from(ctx.headers['x-wt-params'], 'base64').toString()); |
|
const subdomain = wtParams.container |
|
const name = wtParams.jtn |
|
return `https://webtask.it.auth0.com/api/run/${subdomain}/${name}` |
|
} |
|
|
|
const randomPhrase = [ |
|
'Sample text', |
|
'https://thecatapi.com/api/images/get' |
|
] |
|
const getRandomPhrase = () => { |
|
return randomPhrase[Math.floor(Math.random() * frasesRandom.length)]; |
|
} |
|
|
|
// Promisified main function |
|
const main = (ctx) => Bluebird.try(() => { |
|
const query = ctx.query |
|
const body = ctx.body |
|
console.log('Query %j', query) |
|
console.log('Body: %j', body) |
|
|
|
const tg = TG(ctx.secrets.TG_TOKEN) |
|
|
|
// If "activate" is provided in query strings, set the webhook |
|
if (query && query.activate) { |
|
const url = getOwnURL(ctx) |
|
console.log('Setting webHook %s', url) |
|
return setWebHook(tg, url) |
|
} else if (body.message) { |
|
// Message comming from Telegram |
|
const text = body.message.text |
|
const chatId = body.message.chat.id |
|
if (text === '/start') { |
|
const frase = getRandomPhrase() |
|
// If its a URL send it as file |
|
if (/^https?:/.test(frase)) { |
|
sendDocument(tg, chatId, frase) |
|
} else { |
|
sendMessage(tg, chatId, frase) |
|
} |
|
} |
|
// Answer the request without waiting TG |
|
return 'OK' |
|
} else { |
|
return 'WTF' |
|
} |
|
}) |
|
|
|
module.exports = (ctx, cb) => main(ctx) |
|
.catch(err => { |
|
console.error('Error on webtask', err) |
|
const e = new Error('Error on request') |
|
e.stack = '' // Clean stack race |
|
throw e |
|
}) |
|
.asCallback(cb) |