Skip to content

Instantly share code, notes, and snippets.

@muhannad0
Last active June 20, 2020 21:55
Show Gist options
  • Save muhannad0/2cc00280e59b34a3693cae2f4bb0bbb1 to your computer and use it in GitHub Desktop.
Save muhannad0/2cc00280e59b34a3693cae2f4bb0bbb1 to your computer and use it in GitHub Desktop.
running a telegram bot on aws lambda
'use strict';
const getResponseHeaders = () => {
return {
'Access-Control-Allow-Origin': '*'
};
}
const helpMsg = `Command reference:
/start - Start bot
/whoami - Show information about the current user
/help - Show this help page`;
const { Telegraf } = require('telegraf');
const bot = new Telegraf(process.env.BOT_TOKEN);
module.exports.hello = async event => {
try {
const body = JSON.parse(event.body);
console.log(body);
bot.start((ctx) => {
return ctx.reply('Hello from Lambda! Use /help to view available commands.');
});
bot.help((ctx) => {
return ctx.reply(helpMsg);
});
bot.command('whoami', (ctx) => {
return ctx.reply(
'Name: ' + body.message.chat.first_name +
'\nUsername: ' + body.message.chat.username +
'\nChat ID: ' + body.message.chat.id);
})
// bot.on('message', (ctx) => {
// console.log(ctx.message);
// return ctx.reply(body.message.text);
// });
await bot.handleUpdate(body);
return {
statusCode: 200,
headers: getResponseHeaders(),
body: JSON.stringify(
{
message: 'Ok',
})
};
} catch (err) {
console.log("Error: ", err);
return {
statusCode: err.statusCode ? err.statusCode : 500,
headers: getResponseHeaders(),
body: JSON.stringify({
error: err.name ? err.name : "Exception",
message: err.message ? err.message : "Unknown error"
})
};
}
};
module.exports.setWebhook = async event => {
try {
let url = 'https://' + event.headers.Host + '/' + event.requestContext.stage + '/webhook';
await bot.telegram.setWebhook(url);
return {
statusCode: 200,
headers: getResponseHeaders(),
body: JSON.stringify({url: url})
};
} catch (err) {
console.log("Error: ", err);
return {
statusCode: err.statusCode ? err.statusCode : 500,
headers: getResponseHeaders(),
body: JSON.stringify({
error: err.name ? err.name : "Exception",
message: err.message ? err.message : "Unknown error"
})
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment