Build a Telgram Bot using NodeJS and Deploy it on AWS Lambda
Project Walkthrough:
What is AWS Lambda ?
AWS Lambda is an event-driven, serverless Function as a Service provided by Amazon as a part of Amazon Web Services. It is designed to enable developers to run code without provisioning or managing servers. It executes code in response to events and automatically manages the computing resources required by that code.
Why we need an API Gateway ?
Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket APIs at any scale.
It protects you lambda functions from cyber attacks such as
DDOS Attack
Port Flooding
SQL Injection
What are webhooks ?
A webhook is an HTTP-based callback function that allows lightweight, event-driven communication between 2 application programming interfaces (APIs).
Setting up the project:
Steps:
Generate a BOT Token using BotFather
Create a folder and run npm init to create node modules. Also create an index.js file.
Create a Lambda Function.
Create an API gateway to add trigger for you lambda function.
Upload your code on a Lambda Function
Code:
const axios = require("axios");
const handler = async (event) => {
let data = JSON.parse(event.body);
let chat_id = data.message.chat.id;
const bs = await axios.post(
"https://api.telegram.org/bot" + process.env.BOT_TOKEN + "/sendMessage",
{
chat_id: chat_id,
text: "Thank you for contacting",
}
);
const response = {
statusCode: 200,
body: JSON.stringify("Hello from Lambda!"),
};
return response;
};
module.exports = { handler };
// API URL
// set webhook
// https://api.telegram.org/bot{BOT_TOKEN}/setWebhook
// sendMessage
// https://api.telegram.org/bot{BOT_TOKEN}/sendMessage
NOTE:
The index.js files needs to be in the root directory of your lambda function.
Deploy and Test your Lambda Function
Final remarks:
The main aim of this project was to get hands on practice with AWS lambda and API Gateway to handle trigger based events without managning any servers of architecture to get the understanding of serverless technology and how we can leverage cloud to build efficient solutions.