Created
March 17, 2019 15:41
-
-
Save timfanda35/8ca4b138317198377a0f02f94880bb87 to your computer and use it in GitHub Desktop.
GCP Cloud Functions example - Telegram Chatbot echo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const botTgApiHost = 'api.telegram.org'; | |
const botTgApiSendMessagePath = '/bot' + process.env.BOT_TOKEN + '/sendMessage'; | |
const https = require('https'); | |
const querystring = require('querystring'); | |
// | |
// Push message | |
// | |
function pushMessage(chatId, message) { | |
// Build the post string from an object | |
var post_data = querystring.stringify({ | |
'chat_id' : chatId, | |
'disable_web_page_preview': 1, | |
'text': message | |
}); | |
// An object of options to indicate where to post to | |
var post_options = { | |
host: botTgApiHost, | |
port: 443, | |
path: botTgApiSendMessagePath, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Content-Length': Buffer.byteLength(post_data) | |
} | |
}; | |
// Set up the request | |
var post_req = https.request(post_options, function(res) { | |
res.setEncoding('utf8'); | |
res.on('data', function (chunk) { | |
console.log('Response: ' + chunk); | |
}); | |
}); | |
// post the data | |
post_req.write(post_data); | |
post_req.end(); | |
} | |
// | |
// Endpoint | |
// | |
exports.echo = function echo (req, res) { | |
console.log(JSON.stringify(req.body)); | |
console.log(JSON.stringify(req.headers)); | |
const message = req.body.message; | |
pushMessage(message.chat.id, message.text); | |
res.status(200).end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment