Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

GIRIJANANDA CHOWDHURY INSTITUTE OF

MANAGEMENT AND TECHNOLOGY,

GUWAHATI

PROJECT REPORT

ON

“TELEGRAM BOT USING AWS SERVERLESS ARCHITECTURE”

Submitted in partial fulfilment of the requirement for the degree of

Bachelor of Technology

in
DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING

ASSAM SCIENCE AND TECHNOLOGY UNIVERSITY GUWAHATI

Submitted by: Project Guide:


Mukul Anand Maharaj 170310007030 Dr..L.P.Saikia

Subham Roy 170310007048 Professor

Bizen Singha 170310007012 Department of CSE

GIMT,Azara
DECLARATION

We hereby declare that this project work entitled “TELEGRAM BOT USING AWS
SERVERLESS ARCHITECTURE” was carried out by us under the guidance and
supervision of Dr.L.P.Saikia, Professor, Department of Computer Science and
Engineering, Girijananda Chowdhury Institute of Management and Technology,
Guwahati. This project is submitted to the Department of Computer Science and
Engineering during the academic year 2020-21. The work is never produced before
any authority except Assam Science and Technology University for evaluation.

Name of Project Members Roll N0 Signature

1. Mukul Anand Maharaj 170310007030


2. Subham Roy 170310007048
3. Bizen Singha 170310007012

1
GIRIJANANDA CHOWDHURY INSTITUTE OF

MANAGEMENT AND TECHNOLOGY,

GUWAHATI

SESSION 2017-21

DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

This is to certify that Mukul Anand Maharaj, Subham Roy,Bizen Singha students
of B.Tech 4th Year, 7th Semester, have partially completed the project “TELEGRAM
BOT USING AWS SERVERLESS ARCHITECTURE” during this academic
session 2020-21 under my guidance and supervision.

I approve the project for submission as required for partial fulfilment for the
completion of the Bachelors of Technology Degree.

---------------------------------

(Signature of Project Guide)

Dr.L.P.Saikia

Professor

GIMT, Guwahati.

2
ACKNOWLEDGEMENT

“Gratitude is not only the greatest of virtues, but the parent of all the others.”

We would like to express our heartfelt gratitude to our Principal, Prof. Thuleshwer
Nath, GIMT-Guwahati and to our HOD, Dr. Th. Shanta Kumar, Department of
Computer Science and Engineering, GIMT-Guwahati for giving us the freedom to
work on this project and also for providing occasional guidance when needed. Our
sincere gratitude also goes to our project guide Dr.L.P.Saikia, Professor, Department
of Computer Science and Engineering, GIMT-Guwahati and also to all the faculties of
Department of Computer Science and Engineering, GIMT-Guwahati for being with
us, encouraging us to complete our project with honesty and sincerity. And lastly, we
also convey our sincere thanks to all the lab bearers and office bearers for their active
and enthusiastic co-operation.

Name of Project Members Roll No Signature

1.Mukul Anand Maharaj 170310007030

2.Subham Roy 170310007048

3.Bizen Singha 170310007012

3
ABSTRACT

We have Created a Telegram Bot Using AWS to provide users with flexible
responses to their questions .We used AWS serverless Lambda ARCHITECTURE as
it helps us to store ,manage and process our data ,and here servers are fully run by
third party providers (It is a pay-as-you-go model ).Webhook is used to handle
multiple request concurrently .

A Chatbot is a program that can have a conversation with a person using rules in a
way that mimics human-like conversations and interactions. Chatbots have become
popular in the past few years as businesses discover innovative ways to put them to
use. Having a Chatbot today has numerous benefits for businesses – they make life
easier for customers, are available 24/7, save time (no more long waits to talk to a
service rep) and they are easy to use.

4
CONTENTS
Acknowledgement……………………………….......................... (iii)

Abstract…………………………………………............................ (iv)

SL. NO. CHAPTERS PAGE NO.

1. INTRODUCTION 1

1.1 What is CLOUD COMPUTING? 2

1.2 Scope of the Project 3

2. REQUIREMENT ANALYSIS 4

2.1 Hardware Requirements 4

3.. LITERATURE SURVEY 7

4. BASIC CONCEPTS USED 10

5.1 Amazon Web Service

5.2 lambda

5.3 Java Script

5.4. Telegram Messenger 14

5. ARCHITECTURE OF THE SYSTEMS 15

6. METHODOLOGY

6.1 Bot architecture and workflow 16

6.2 Develelopent Prequisites 17

6.3 Implementing A Lambda Function 21

6.4 Create The TelegramBot Using BotFather 22

6.5 Serverless Deploy 23

7. APPLICATION 31
8. ADVANTAGES 32

9. LIMITATIONS 34

10. CONCLUSION 35

11. FUTURE SCOPE 36

BIBLIOGRAPHY 37
Chapter 1: INTRODUCTION

1.1 What is Cloud Computing

Cloud computing is the delivery of on-demand computing services -- from


applications to storage and processing power -- typically over the internet and on a
pay-as-you-go basis.

Rather than owning their own computing infrastructure or data centers, companies can
rent access to anything from applications to storage from a cloud service provider.

One benefit of using cloud computing services is that firms can avoid the upfront cost
and complexity of owning and maintaining their own IT infrastructure, and instead
simply pay for what they use, when they use it.

In turn, providers of cloud computing services can benefit from significant economies
of scale by delivering the same services to a wide range of customers.

What cloud computing services are available?


Cloud computing services cover a vast range of options now, from the basics of
storage, networking, and processing power through to natural language processing
and artificial intelligence as well as standard office applications. Pretty much any
service that doesn't require you to be physically close to the computer hardware that
you are using can now be delivered via the cloud.

Examples

Cloud computing underpins a vast number of services. That includes consumer


services like Gmail or the cloud back-up of the photos on your smartphone, though to
the services which allow large enterprises to host all their data and run all of their
applications in the cloud. Netflix relies on cloud computing services to run its its
video streaming service and its other business systems too, and have a number of
other organisations.

Cloud computing is becoming the default option for many apps: software vendors are
increasingly offering their applications as services over the internet rather than
standalone products as they try to switch to a subscription model. However, there is a
potential downside to cloud computing, in that it can also introduce new costs and
new risks for companies using it.

Why is it called cloud computing?


A fundamental concept behind cloud computing is that the location of the service, and
many of the details such as the hardware or operating system on which it is running,
are largely irrelevant to the user. It's with this in mind that the metaphor of the cloud
was borrowed from old telecoms network schematics, in which the public telephone

1
network (and later the internet) was often represented as a cloud to denote that the just
didn't matter -- it was just a cloud of stuff. This is an oversimplification of course; for
many customers location of their services and data remains a key issue.

1.2Scope of the project

This project aims to create a telegram bot which helps users to get replies to their
queries and messages,automatically through a bot .

2
Chapter 2: REQUIREMENT ANALYSIS

2.1 Hardware requirements:

⮚ Minimum RAM 8GB, 12GB Recommended.


⮚ 4GB of available disk space minimum, 8GB Recommended.
⮚ 1280*800 minimum screen resolution.
⮚ 64-Bit Operating System.

2.2 Software Requirements:

⮚ Linux/windows
⮚ Telegram Messenger
⮚ Amazon Web Service
⮚ Javascript

Chapter3:Literature survey

3
1.ANALYSIS OF CLOUD COMPUTING SERVICES USING AMAZON EC2
(AUTHOR -Mounika Namburu ,University of Colorado, Colorado Springs).

To understand how to best utilize different cloud computing services to get good
performance for less cost. Amazon EC2 gained popularity in providing good cloud
computing services hence is used here.Cloud computing is best suited for small
organizations which are worried about cost incurred in maintaining the infrastructure.
Security is the main concern of cloud based computing and can be the future work of
this project.

2.DESIGN A TELEGRAM BOT FOR CAMPUS INFORMATION


SHARING .(AUTHOR -Hari Setiaji,Universitias Islam Indonesia).
This paper presents a design of Telegram bot to support Campus information sharing.
The communication method used is Webhooks. Webhooks is able to provide zero
latency and handle multiple requests concurrently during communication within the
Telegram bot. Such bot serves the information via specific commands

3.Cloud Computing (MTECH SEMINAR REPORT)(AUTHOR -Abhirup


Ghosh ,Dept Of Computer Science And Engineering ,IIT BOMBAY).
The project is aimed at showing the dimension of how cloud computing provides IT
as a service to the cloud users on-demand basis with greater flexibility, availability,
reliability and scalability with utility computing models.

Chapter 4: BASIC CONCEPTS USED

4
4.1 Amazon Web Service(AWS)
AWS (Amazon Web Services) is a comprehensive, evolving cloud computing
platform provided by Amazon that includes a mixture of infrastructure as a service
(IaaS), platform as a service (PaaS) and packaged software as a service (SaaS)
offerings. AWS services can offer an organisation tool  such as compute power,
database storage and content delivery services.

AWS launched in 2006 from the internal infrastructure that Amazon.com built to
handle its online retail operations. AWS was one of the first companies to introduce a
pay-as-you-go cloud computing model that scales to provide users with compute,
storage or throughput as needed.

AWS offers many different tools and solutions for enterprises and software
developers that can be used in data centers in up to 190 countries. Groups such as
government agencies, education institutions, nonprofits and private organizations can
use AWS services.

More than 100 services comprise the Amazon Web Services portfolio, including those
for compute, databases, infrastructure management, application development and
security.

4.2 Lambda

AWS Lambda is an event-driven, serverless computing platform provided by Amazon


as a part of Amazon Web Services. Therefore you don't need to worry about which
AWS resources to launch, or how you will manage them. Instead, you need to put the
code on Lambda, and it runs.

In AWS Lambda the code is executed based on the response of events in AWS
services such as add/delete files in S3 bucket, HTTP request from Amazon API
gateway, etc. However, Amazon Lambda can only be used to execute background
tasks.

AWS Lambda function helps you to focus on your core product and business logic
instead of managing operating system (OS) access control, OS patching, right-sizing,
provisioning, scaling, etc.

4.3 Javascript
JavaScript often abbreviated as JS ,is a programming language that conforms to the
ECMAScripts specification. JavaScript is High Level, often just-in-time compiled,
and multi paradigm It has curly bracket syntax, dynamic typing, prototype based
object orientation, and first-class functions.
Alongside HTML and CSS, JavaScript is one of the core technologies of the World
Wide Web.Over 97% of websites use it client-side for web page behavior,often
incorporating third-party libraries.All major webbrowsers have a dedicated JavaScript
engine to execute the code on the user's device.

5
AMulti-paradigm language,JavaScript supports event-driven, functional,
and imperative programming styles. It has application programming interfaces (APIs)
for working with text, dates, regular expressions, standard data structures, and
the Document Object Model (DOM).

5.3 TELEGRAM Messaging


Telegram is a messaging app with a focus on speed and security, it’s super-fast,
simple and free. You can use Telegram on all your devices at the same time — your
messages sync seamlessly across any number of your phones, tablets or computers.
Telegram has over 500 million monthly active users and is one of the 1 most
downloaded app in the world.
With Telegram, you can send messages, photos, videos and files of any type (doc, zip,
mp3, etc), as well as create groups for up to 200,000 people or channels for
broadcasting to unlimited audiences. You can write to your phone contacts and find
people by their usernames. As a result, Telegram is like SMS and email combined —
and can take care of all your personal or business messaging needs. In addition to this,
we support end-to-end encrypted voice and video calls, as well as voice chats in
groups for thousands of participants.

Chapter 6: ARCHITECTURE OF THE SYSTEM

6
Chapter 7: METHODOLOGY
In our Telegram bot implementation, we will use a Function-as-a-Service (FaaS)
model and AWS Lambda.

7
FaaS creates a high level of abstraction and increases development speed: Instead of
thinking about the infrastructure, scalability, environment, etc., developers can focus
only on the code and logic of individual functions, which are run in stateless
containers.

In our case, FaaS is a great fit because the only actions needed to process requests are
making a call to the API, sending a response, and quitting.

Moreover, AWS Lambda pricing is based on the total execution time of the function,
so you will never pay for idle time. AWS also offers a free tier that includes 400,000
GB/seconds per month. This means that the bot will actually operate for free — it’s
literally impossible to exceed the free tier’s limits when working with a light-
functionality app used by only a few people.

7.1 Bot Architecture and Workflow Overview

The bot’s general workflow will look like this:

1.The user sends a message (the URL to be shortened) to the Telegram bot.

2. The Telegram server receives the message and sends it to the Lambda function via
a webhook

3.The Lambda function takes the URL from the message and sends it to the free open
cleanuri API, which will generate the short URL.

4. The Lambda function sends the response to the particular Telegram chat it was
invoked from. This can be achieved by a simple HTTP call to the Telegram API or by
using special library methods.

5.The user receives the shortened URL or an error message if something went wrong.

7.2 Development Prerequisites

In order to start developing the Lambda function, you will need an AWS account. If
you haven’t created one yet, navigate to the AWS Free Tier page and sign up.

We are going to use Serverless Framework, one of the most popular and powerful
tools for developing and maintaining serverless applications. In order to use it on your
machine, install Node.js.

Then run the following command:

8
npm install -g serverless

Lastly, configure Serverless Framework access to your AWS account:

npm install -g serverless serverless config credentials --provider aws --key


xxxxxxxxxxxxxx --secret xxxxxxxxxxxxxx

The hidden parts of the above code (marked by the x’s) are the API and secret keys
from your AWS account.These are used to make AWS services accessible from the
application code, AWS CLI, or tools such as Serverless Framework.

7.3 Implementing a Lambda Function

Start by creating an AWS Lambda function, which will be triggered via Telegram
HTTP webhook. This function will be responsible for making a call to the cleanuri
API and sending the result to the user. To create the Lambda function,simply create a

new folder on your machine, navigate inside of it, open a terminal window, and type
the following:

serverless create --template aws-nodejs

This will create a very simple boilerplate for future Node.js Lambda functions. The
boilerplate actually consists of two files: handler.js and serverless.yml. handler.js is
the function’s code entry point, and serverless.yml is the serverless configuration file,
where the serverless trigger and other settings can be declared.

Replace the content of serverless.yml with the following lines:

service: short-bot

provider:

name: aws

runtime: nodejs10.x

region: eu-west-1

functions:

shortbot:

handler: handler.shortbot

events:

- http:

9
path: short-bot

method: post

cors: true

The above configuration means that:

The new Node.js-based serverless “shortbot” will be created during the next deploy.

The service consists of one AWS Lambda function, which can be triggered with a
POST request to the newly created API Gateway /short-bot path.

The code to execute is located in the shortbot function of the handler.js file.

To simplify the code we’re going to write, install the npm request and request-
promise packages. The below command will create a basic package.json file.

npm init

Simply run the command and press enter each time different prompts appear.Then run
the package’s installation command:

npm install --save request request-promise

Next enter the code of the handler.js file:

const rp = require('request-promise');

const TELEGRAM_TOKEN = ' ';

async function getShortUrl(longUrl) {

const options = {

method: 'POST',

uri: 'https://cleanuri.com/api/v1/shorten',

form: {

url: String(longUrl).trim()

},

json: true

};

10
return rp(options);

async function sendToUser(chat_id, text) {

const options = {

method: 'GET',

uri: `https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`,

qs: {

chat_id,

text

};

return rp(options);

module.exports.shortbot = async event => {

const body = JSON.parse(event.body);

const {chat, text} = body.message;

if (text) {

let message = '';

try {

const result = await getShortUrl(text);

message = `Input: ${text}, \nShort: ${result.result_url}`;

} catch (error) {

message = `Input: ${text}, \nError: ${error.message}`;

await sendToUser(chat.id, message);

} else {

await sendToUser(chat.id, 'Text message is expected.');

11
}

return { statusCode: 200 };

};

The above code exports a “shortbot” function that will handle requests from the
Telegram webhook and read

messages sent by the user; then send requests to the cleanuri API and send the results
to the same chat.

However, before deploying this “shortbot” function, you need to create your bot in
Telegram. You’ll then get

a secret token and paste it to the TELEGRAM_TOKEN variable on the second line
of the JavaScript code above.

7.4 Create the Telegram Bot Using BotFather

According to Telegram, in order to create a new bot, you need to contact another bot,
named BotFather, and follow his instructions.

After BotFather generates your new bot, copy the token provided and paste it to the
variable in the code. Now you can deploy your Lambda function and retrieve the URL
for your bot’s webhook. To do that, run the following command in the projects
directory:

7.5 Serverless deploy

You should see the following result in the console, including the HTTP endpoint
URL.

Result of serverless deployment

The HTTP endpoint URL is the keychain connecting the Telegram servers with the
logic of your bot. Now configure the webhook to make requests via this link each
time users send a new message to the bot. FatherBot’s documentation states that the
/setWebhook endpoint can be used to set up the webhook with a single POST request.
Here is a short snippet you can use to make the request with a curl util:

curl --request POST --url


https://api.telegram.org/bot<TELEGRAM_TOKEN>/setWebhook --header 'content-
type:

12
application/json' --data '{"url":
"<LINK_YOU_GET_FROM_SERVERLESS_DEPLOY>"}'

Chapter 8: APPLICATIONS

13
1.Content Delivery-Media Publishers have realized that chatbots are a powerful way
to engage with their audiences and monitor engagement to gain valuable insights on
reader interests. Chat with the CNN and Wall Street Journal Chatbots on Facebook
Messenger and receive the latest news directly in Messenger, without having to visit
their websites.
A lot of publishers are also harnessing AI and machine learning technology
within their chatbots to anticipate what content their consumers may be interested in.
This is an interesting application of chatbot technology and its sure to lead to
immediate and more personalized content than ever before.

2.Order food-Various fast food giants like KFC and Pizza Hut have invested in
Chatbots that enable customers to place their orders through conversations. Taco Bell
went a step further to improve the conversational experience by giving their Chatbot
named TacoBot some personality. rous leukocytes which can be further used to
identify the type of cancer it falls into.

3.Market research -Researchers get in touch with respondents is changing as many


respondents may prefer to be contacted on WhatsApp or the Facebook messenger.
Instead of having a dedicated survey app, many research firms are developing
Chatbots to have personalized, engaging conversational surveys with respondents to
improve the experience and increase completion rates.

4.Hospitality -Chatbots have been put to use in the hospitality industry in various
ways. Radisson Blu Edwardian hotels use a virtual host called Edward to help guests
with a variety of things from; online check-in, to handling customer inquiries, letting
them know their rooms are ready and more.

5.Healthcare-Chatbots have also made their way into health care by easing the
burden on medical professionals by facilitating faster medical diagnosis, answering
health-related questions, booking appointments and lots more. A Chatbot like Super
Izzy can track menstrual cycles, dates and fertile windows.

Chapter 9: ADVANTAGES

14
1.Benefits to Customers-(24-hour availability)-According to studies, over 50% of
customers expect a business to be available 24/7. Waiting for the next available
operator for minutes is not a solved problem yet, but chatbots are the closest
candidates to ending this problem. Maintaining a 24/7 response system brings
continuous communication between the seller and the customer. Of course, this
benefit is proportional to how well the bots are. Bots that are unable to serve simple
customer queries fail to add value even if they are 24/7 available. The main issue at
this point is how well the chatbots can understand and solve customer problems.
Finally, highlighting 24/7 availability can create backlash when bots are down due to
security issues or maintenance.

2.Instant answers-An operator can concentrate on one customer at a time and answer
one question. However, a chatbot can answer thousands of questions at the same time.
Thanks to the speed of the cloud, internet, and software mechanisms, responses can be
provided instantly.

1.Consistent answers-Talking to a customer service rep, a customer has no assurance


that other reps are also providing similar, consistent responses. If a customer service
rep is not helpful, a customer could be tempted to try calling again to see if the next
rep is better.

2.Recorded answers-Talking to a customer service rep, a customer gets no record of


the conversation and most people would prefer not to record their conversations.
However, a customer can take a screenshot whenever she likes, to remember the
conversation, or to challenge an answer provided by the bot.

3.Endless patience-While customer reps and customers sometimes lose their


patience, that’s something bots are yet incapable of. The impatience of the
representative and the consumer during the solution of a problem is one of the human-
related failures. The representative is expected to be more patient as much as possible
so that the company can keep consumer satisfaction high. Chatbots can show the

15
patience that no human can provide. At this point, a human-sourced consumer service
problem can be resolved directly.

4.Instant transactions-Actions like changing or querying records are almost


instantaneous for bots which can significantly improve customer satisfaction.

5.Programmability-.Since bots are on digital platforms where people spend the


majority of their waking hours working, bots can be used to automate common tasks
such as arranging meetings, providing advanced search functionality. Chatbots do not
just have to be used for shopping. It will be a great convenience to hand over
repetitive tasks such as arranging meetings, researching a topic to chatbots

16
Chapter 10: LIMITATIONS

It’s claimed that chatbots increase customer engagement, improve the brand experience and
deliver actionable insight to the business. So why are so many chatbots failing to deliver on
their potential?

The answer lies in the restrictive nature of most chatbot technology. Few chatbots offer the
rich, humanlike conversation needed to engage users, nor can they guide off-topic users back
to the subject at hand. They can’t ask qualifying questions if clarification is required. And,
they are not able to deliver over the different channels and languages by which customers
want to communicate.

Add in a lack of intelligent interaction by the chatbot and confusion over data ownership and
it’s no wonder Gartner expects that 40% of first-generation chatbot/virtual assistant
applications launched in 2018 will have been abandoned by 2020.

The main issues can be categorized into four main areas:

1. lack of data training

2. Poor conversational understanding

3. Organisation need to support their customers in different languages

4. Regulations Protecting Data.

17
Chapter 11: CONCLUSION

From our perspective, chatbots or smart assistants with artificial intelligence are
dramatically changing businesses. There is a wide range of chatbot building platforms
that are available for various enterprises, such as e-commerce, retail, banking, leisure,
travel, healthcare, and so on.

Chatbots can reach out to a large audience on messaging apps and be more effective
than humans. They may develop into a capable information-gathering tool in the near
future.

18
Chapter 12: FUTURE SCOPE

Artificial intelligence is the hottest talking point for business users looking to improve
their efficiency, deliver new ideas and take the next steps in the transition to a digital
enterprise. AI and chatbots are helping democratise business, empower startups and
help build new partnerships, something that every organisation needs to prepare for.

“Every business is a technology business” was one of the mantras of the decade just
concluded. Every company across every vertical and market started working and
communicating with smartphones, using cloud services to open up their data and
adopted as-a-service solutions to reduce the cost of doing business and broaden their
business base and the opportunities for workers.

19
BIBLIOGRAPHY

1. BOOK -Amazon Web Service in action (Andreas Wittig and Micheal Wittig ).

2. https://www.drift.com/learn/chatbot/

3. https://www.cse.iitb.ac.in/~abhirup09/Docs/cloud_computing_final_report.pdf

4. http://cs.uccs.edu/~cs526/studentproj/projS2010/mnamburu/doc/CS526%20Projec
t%20Report.pdf

5. https://www.youtube.com/watch?v=hqkfHK7-O08

6. http://6.http//www.persistentsys.com/newpspl/pdf/CMS_1741820566_Google
%20Apps%20Engine_WP_010909.pdf

7. P. Kokil. SAP-LAP Analysis: Gyan Ganga, E-Gram and Communication


Information Center .http://www.iceg.net/2007/books/3/29_290_3.pdf.

20

You might also like