---
title: How to Use the Serverless Function with a Telegram Chatbot
description: Would you like to find a scalable and affordable solution for handling asynchronous processing? Serverless functions may be the answer.
image: https://blog.avenuecode.com/hubfs/alex-knight-199368-unsplash.jpg
---

[AvenueCode.com](https://avenuecode.com) [News](https://avenuecode.com/news) [Contact](https://avenuecode.com/contact)

[![Avenue Code Snippets Logo](https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/AC-Snippets---Black.png)](https://blog.avenuecode.com/?hsLang=en-us) *menu*

- Technology
  
  [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us) [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us) [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us) [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us) [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
  
  [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us) [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us) [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us) [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

- [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us)
- [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us)
- [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us)
- [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us)
- [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us)
- [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us)
- [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us)
- [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

# [How to Use the Serverless Function with a Telegram Chatbot](https://blog.avenuecode.com/how-to-use-the-serverless-function-with-a-telegram-chatbot)

- [Tweet](https://twitter.com/share)

*perm\_identity* [Cristiano Piccin](https://blog.avenuecode.com/how-to-use-the-serverless-function-with-a-telegram-chatbot/author/cristiano-piccin?hsLang=en-us)

*schedule* 3/14/18 4:00 PM

In this post, we will briefly introduce Serverless architecture and discuss how it is an optimal solution for handling event-driven processing.

Serverless is an architectural paradigm in which either a function or a microservice can be hosted on a cloud server without the server running continuously; it is an event-driven approach where each execution starts, runs a small process to meet the request, and stops at the end. Some of its defining characteristics are:

- - It does not require administration (users can operate it without having to manage a server or a run-time environment)
- - Users pay per execution (users are not billed by idle server time)
- - It is event-driven (executions are asynchronous)
- - It is tightly coupled with a Cloud provider (there is no "free lunch")
- - It is ephemeral (it may only last for one invocation)
- - It can be categorized as FaaS (Function as a Service) when it executes code in ephemeral containers
- - It can be categorized as BaaS (Backend as a Service) when it executes code that depends on third-party services

 

##### Serverless in Action

To explain how Serverless architecture works, let's consider an example where we create a Serverless function that calculates BMI (Body Mass Index) through a Telegram chatbot. Passing aleatory commands to the bot, we will receive the right command syntax to write in order to tell the bot to calculate BMI. When the user enters his weight and height information, the bot will convey this to the Serverless function; the function will then calculate the BMI and send the result back to the user, as depicted in the chart below:

![sequence-chatbot.png](https://blog.avenuecode.com/hs-fs/hubfs/cpiccin/servless/sequence-chatbot.png?width=664&height=457&name=sequence-chatbot.png)

Chatbot flow

##### Chatbot

With this "big picture" chart in mind, let's examine the individual components involved in this process. First, we have created a Telegram chatbot following [these steps](https://core.telegram.org/bots). The bot's function is to receive a request and pass it along either through a pre-configured webhook or through a pooling model, which makes background requests for the chatbot server.

In our case, we are using the webhook mechanism. This means that when a message is sent, the Telegram chatbot server will redirect the request to a specific endpoint already configured in the webhook. This request then goes with the chatbot payload so that our FaaS can receive and process the message.

![](https://blog.avenuecode.com/hs-fs/hubfs/cpiccin/setWebhook.png?width=1080&height=182&name=setWebhook.png "setWebhook.png")

Setting webhook 

##### Serverless Function

For this example, we have used [Google Functions](https://cloud.google.com/functions/) as our FaaS provider, which requires a valid Google Account in Google Cloud. We access Google Cloud through the dashboard panel, where we click "Main Menu" - "Cloud Functions." 

![](https://blog.avenuecode.com/hs-fs/hubfs/cpiccin/servless/Screen%20Shot%202018-03-07%20at%2015.45.44.png?width=921&name=Screen%20Shot%202018-03-07%20at%2015.45.44.png "Screen Shot 2018-03-07 at 15.45.44.png")Dashboard

We then create a function called "function-bot," exposing an HTTP endpoint, but we can also choose other trigger types, such as pub/sub or Cloud storage buckets. When creating a function, users can specify the memory size to be allocated as well as the code that will be the main execution function. The code must be in Node.js at this time and can be put into an inline editor, zip package upload, or Cloud repository. The function follows the Express.js framework standards, receiving a request and response as input parameters. The Serverless function code that receives the chatbot webhook request operates as follows:

```
    
const request = require('request').defaults({
    encoding: null
  });

let url = "https://api.telegram.org/token/sendMessage?chat_id=chat_id&text=$message";
/**
 * Responds to any HTTP request that can provide a "message" field in the body.
 *
 * @param {!Object} req Cloud Function request context.
 * @param {!Object} res Cloud Function response context.
 */
exports.bmi = (req, res) => {
   
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);
    let message = req.body.message.text;
        
    let re = /\d\d\/\d\d\d/;
    if(!message.match(re)) {
      sendMessage("Put Weight in Kilograms/Height in centimeters to calculate your BMI. Ex 87/188");
      return res.status(200).end();
    }
   
    let weight = message.split("/")[0];
    let height = message.split("/")[1]/100;
    
    let num_result =  weight/Math.pow(height,2);
    console.log(num_result)
    if(num_result >= 25) {
    	sendMessage("You are in overweight range."); 
    } else if(num_result > 18.5 && num_result < 25) {
      	sendMessage("You are in healthy range");
    } else {
        sendMessage("You are in underweight range.");
    }
    
    return res.status(200).end();            
  }
};

function sendMessage(message) {
  let newUrl = url.replace("$message", message)
  request.get(newUrl, (error, response, body) => {
      let json = JSON.parse(body);
      console.log(json);
    });
}
```

The above code illustrates how, after this BMI processing, we must call the Telegram chatbot URL with the BMI level as the payload message. Once all configurations have been completed, we can publish our function. At this point, our system is able to execute through the HTTP endpoint. Since we have completed all the steps to execute our chatbot, we can access the bot, which we named "myhealthybot," through the Telegram interface. We can start the chat by listing weight and height information.

![Screen Shot 2018-03-07 at 16.55.03.png](https://blog.avenuecode.com/hs-fs/hubfs/cpiccin/servless/Screen%20Shot%202018-03-07%20at%2016.55.03.png?width=666&name=Screen%20Shot%202018-03-07%20at%2016.55.03.png)

The chatbot response is instantaneous.

##### Conclusion

In the example above, we've created a simple chatbot to illustrate how quickly and simply you can create Serverless functions, which are scalable and affordable options for handling asynchronous processing. The market at large is utilizing tools like Serverless more and more, so be sure to take some time to explore [all the uses of this architecture](https://serverless.com/) for your own business. 

Cheers!

 

##### References:

[https://core.telegram.org/bots/api](https://core.telegram.org/bots/api)

[https://martinfowler.com/articles/serverless.html](https://martinfowler.com/articles/serverless.html)

[https://aws.amazon.com/lambda/](https://aws.amazon.com/lambda/)

[https://azure.microsoft.com/en-us/services/functions/](https://azure.microsoft.com/en-us/services/functions/)

[https://cloud.google.com/functions/](https://cloud.google.com/functions/) 

 

---

[![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png)](https://www.linkedin.com/in/crspiccin/)

### Author

# Cristiano Piccin

 Cristiano Piccin is a Software Engineer at Avenue Code. He has more than 14 years of experience in software development, and he is always contemplating how to create value for society with new technologies.

---

### Related Posts

### Asymmetric Cryptography

[READ MORE](https://blog.avenuecode.com/asymmetric-cryptography?hsLang=en-us)

### Improving the developer experience when documenting

[READ MORE](https://blog.avenuecode.com/improving-the-developer-experience?hsLang=en-us)

### How to Run Rust from Python

[READ MORE](https://blog.avenuecode.com/how-to-run-rust-from-python?hsLang=en-us)

### How to Create a Tic-Tac-Toe Board Using React.js

[READ MORE](https://blog.avenuecode.com/how-to-create-a-tic-tac-toe-board-using-react.js?hsLang=en-us)

### Leave a Comment!

### Avenue Code Social

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Blog/facebook.png?t=1486470796564)](https://www.facebook.com/avenuecode)

[![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Blog/twitter.png?t=1486470796842)](https://twitter.com/AvenueCode)

[![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png?t=1486470796556)](https://www.linkedin.com/company/avenue-code)

### Newsletter

Want to stay on top of all tips and news from Avenue Code?

### Popular Snippets

![Primary Logo AvenueCode Inverted.png](https://blog.avenuecode.com/hs-fs/hubfs/Images/Logos/Primary%20Logo%20AvenueCode%20Inverted.png?width=1104&name=Primary%20Logo%20AvenueCode%20Inverted.png "Primary Logo AvenueCode Inverted.png")

### About Us

- [Who We Are](https://www.avenuecode.com/who-we-are)
- [What We Do](https://www.avenuecode.com/what-we-do)
- [Portfolio](https://www.avenuecode.com/portfolio)
- [Partners](https://www.avenuecode.com/partners)
- [News](https://www.avenuecode.com/news)
- [Events](https://www.avenuecode.com/events)
- [Blog](https://blog.avenuecode.com/)
- [Contact](https://www.avenuecode.com/contact)

### Our Offices

San Francisco

[+1 415 766 4178](tel:+553125161448) [ac.inquiries@avenuecode.com](mailto:brazil.info@avenuecode.com)

Belo Horizonte

[+55 31 2516 1448](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

São Paulo

[+55 11 3205 3232](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

### We're Hiring!

- [Belo Horizonte](https://www.avenuecode.com/who-we-are)
- [New York](https://www.avenuecode.com/what-we-do)
- [San Francisco](https://www.avenuecode.com/portfolio)
- [São Paulo](https://www.avenuecode.com/partners)

---

©2015 - 2017 Avenue Code

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Icons/facebook-2.png)](https://www.facebook.com/avenuecode) [![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Icons/twitter-2.png)](https://twitter.com/AvenueCode) [![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Icons/linkedin-2.png)](https://www.linkedin.com/company/avenue-code) [![Glassdoor Icon](https://blog.avenuecode.com/hubfs/Images/Icons/glassdoor-icon-1.png)](https://www.glassdoor.com/Overview/Working-at-Avenue-Code-EI_IE456173.11,22.htm) [![YouTube Icon](https://blog.avenuecode.com/hubfs/Images/Icons/youtube-2.png)](https://www.youtube.com/user/AvenueCodePlay)

Please enable JavaScript to view the [comments powered by Disqus.](http://disqus.com/?ref_noscript)

© 2026 Avenue Code

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Cristiano Piccin",
    "url" : "https://blog.avenuecode.com/author/cristiano-piccin"
  },
  "datePublished" : "2018-03-14T19:00:00.000Z",
  "headline" : "How to Use the Serverless Function with a Telegram Chatbot",
  "image" : [ "https://blog.avenuecode.com/hubfs/alex-knight-199368-unsplash.jpg" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.avenuecode.com/how-to-use-the-serverless-function-with-a-telegram-chatbot",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_LOGO%20HORIZONTAL%20group%201-7.png"
    },
    "name" : "Avenue Code"
  }
}
```