Skip to content

Instantly share code, notes, and snippets.

@yagop yagop/Readme.md
Last active Nov 15, 2017

Embed
What would you like to do?
Webtask bot sample

This is a sample Telegram Bot to showcase Webtask.

Hints included

  • Main function promisification through Bluebird.try and asCallback.
  • Query params and body access.
  • Secrets (TG_TOKEN)
  • Get the Webtask runner URL
  • Basic Telegram Bot API usage

Setup

  • Go to https://webtask.io/make and create a new Webtask Function
  • Paste the code
  • Use Botfather to get your Telegram Bot Token
  • Add your token as TG_TOKEN secret on Webtask took icon
  • PROFIT!

Warning

  • Webtask uses Nodejs v4.8.5, so stay aware of some ES6 features
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.