[Yandex Cloud documentation](../../../index.md) > [Yandex API Gateway](../../index.md) > [Tutorials](../index.md) > Serverless-based bots > [Developing a Telegram bot](index.md) > Management console

# How to create a Telegram bot using Serverless in the management console


To [create a Telegram bot](index.md) using Serverless in the Yandex Cloud management console:

1. [Get your cloud ready](#before-begin).
1. [Set up required resources](#create-resources).
1. [Register your Telegram bot](#create-bot).
1. [Publish an image for the bot](#image-publish).
1. [Create an API gateway](#create-gateway).
1. [Create a function](#create-function).
1. [Configure a link between the function and the Telegram bot](#function-bind-bot).
1. [Test your Telegram bot](#test-bot).

If you no longer need the resources you created, [delete them](#clear-out).


## Get your cloud ready {#before-begin}

Sign up for Yandex Cloud and create a [billing account](../../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../../billing/quickstart/index.md) and [link](../../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../../resource-manager/concepts/resources-hierarchy.md).


### Required paid resources {#paid-resources}

The cost of supporting the Telegram bot infrastructure includes:
* Fee for [function calls](../../../functions/concepts/function.md), computing resources allocated for the function, and outgoing traffic (see [Cloud Functions pricing](../../../functions/pricing.md)).
* Fee for [storing data](../../../storage/concepts/bucket.md) in Object Storage, [operations](../../../storage/operations/index.md) with it, and outgoing traffic (see [Object Storage pricing](../../../storage/pricing.md)).
* Fee for the number of requests to the [API gateway](../../concepts/index.md) and outgoing traffic (see [Yandex API Gateway pricing](../../pricing.md)).


## Set up resources {#create-resources}

1. [Download](https://sourcecraft.dev/yandex-cloud-examples/yc-telegram-bot-serverless/browse/sayhello.png?rev=main) an image for the bot.
1. [Create](../../../iam/operations/sa/create.md) a service account and [assign](../../../iam/operations/sa/assign-role-for-sa.md) it the `editor` and `functions.functionInvoker` roles for your folder.


## Create a Telegram bot {#create-bot}

Create a bot in Telegram and get a token.

1. To register a new bot, start [BotFather](https://t.me/BotFather) and run the below command.

    ```text
    /newbot
    ```

1. In the `name` field, enter a name for the bot, e.g., `Serverless Hello Telegram Bot`. This is the name users will see when chatting with the bot.
1. In the `username` field, specify a username for the bot, e.g., `ServerlessHelloTelegramBot`. You can use it to find the bot in Telegram. The username must end with `...Bot` or `..._bot`.

   As a result, you will get a token. Save it, as you will need it later.

1. Set an icon for the bot using `sayhello.png` from the saved archive. Send this command to BotFather:

    ```text
    /setuserpic
    ```


## Publish an image for the bot {#image-publish}

If you want your bot to respond to user messages with an image, create an Object Storage bucket and upload `sayhello.png` from the saved archive to it.


### Create an Object Storage bucket {#create-bucket}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create a [bucket](../../../storage/concepts/bucket.md).
  1. Navigate to **Object Storage**.
  1. Click **Create bucket**.
  1. On the bucket creation page:

      1. Enter a name for the bucket. Save the bucket name. You will need it later.
      1. Specify these bucket settings:

          * **Max size**: `1 GB`.
          * **Read objects**: `For all`.
          * **Storage class**: `Standard`.

      1. Click **Create bucket**.

{% endlist %}


### Upload the image to the bucket {#upload-image}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder containing the created bucket.
  1. Navigate to **Object Storage**.
  1. Select the bucket.
  1. Click **Upload**.
  1. In the window that opens, select `sayhello.png` from the saved archive. The management console will display the file selected for upload.
  1. Click **Upload**.

{% endlist %}


### Get a link to the uploaded image {#get-image-link}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder containing the created bucket.
  1. Navigate to **Object Storage**.
  1. Select the bucket.
  1. Select `sayhello.png`.
  1. Click **Get link**.
  1. Make sure the image is accessible through the link in your browser.

{% endlist %}


## Create an API gateway {#create-gateway}

To enable your bot to work with a function, create and configure an [API gateway](../../concepts/index.md).

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create an API gateway.
  1. Navigate to **API Gateway**.
  1. Click **Create API gateway**.
  1. Name the gateway: `for-serverless-hello-telegram-bot`.
  1. Clear the **Specification** field and paste this code:

      ```yaml
      openapi: 3.0.0
      info:
        title: for-serverless-hello-telegram-bot
        version: 1.0.0
      paths:
        /sayhello.png:
          get:
            x-yc-apigateway-integration:
              type: object_storage
              bucket: <bucket_name>
              object: sayhello.png
              presigned_redirect: false
              service_account_id: <service_account_ID>
            operationId: static
      ```

      Where:
      * `bucket`: Bucket name.
      * `service_account_id`: [ID of the service account](../../../iam/operations/sa/get-id.md) you created when [setting up the resources](#create-resources).

  1. Click **Create**.
  1. Select the previously created API gateway. Save the **Default domain** field value as you will need it to create the function.

{% endlist %}


## Create a function {#create-function}

If you want your Telegram bot to respond to the `/start` and `/help` commands and send an image in response to any other text, create a designated [function](../../../functions/concepts/function.md).

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create a function.
  1. Navigate to **Cloud Functions**.
  1. Click **Create function**.
  1. Enter the function name: `fshtb-function`.
  1. Click **Create**.
  1. Under **Editor**, select `Node.js` as the runtime and click **Continue**.
  1. Under **Function code**, replace the contents of the `index.js` file with the code below. Replace `<API_gateway_domain>` with the API gateway service domain.

      ```javascript
      const { Telegraf } = require('telegraf');

      const bot = new Telegraf(process.env.BOT_TOKEN);
      bot.start((ctx) => ctx.reply(`Hello. \nMy name Serverless Hello Telegram Bot \nI'm working on Cloud Function in the Yandex Cloud.`))
      bot.help((ctx) => ctx.reply(`Hello, ${ctx.message.from.username}.\nI can say Hello and nothing more`))
      bot.on('text', (ctx) => {
          ctx.replyWithPhoto({url: '<API_gateway_domain>/sayhello.png'});
          ctx.reply(`Hello, ${ctx.message.from.username}`);

      });

      module.exports.handler = async function (event, context) {
          const message = JSON.parse(event.body);
          await bot.handleUpdate(message);
          return {
              statusCode: 200,
              body: '',
          };
      };
      ```

  1. Under **Function code**, create a file named `package.json` and paste the following code into it:

      ```json
      {
        "name": "ycf-telegram-example",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "",
        "license": "MIT",
        "dependencies": {
          "telegraf": "^4.12.0"
        }
      }
      ```

  1. Specify the following settings:

      * **Runtime environment**: `nodejs22`.
      * **Entry point**: `index.handler`.
      * **Timeout**: `5`.

  1. Add the `BOT_TOKEN` environment variable. In the **Value** field, specify the Telegram bot token.
  1. Click **Save changes**.
  1. Make sure the function is [public](../../../functions/operations/function/function-public.md). To do this, navigate to the **Overview** page and enable the **General information** toggle under **Public function**.
  1. Save your function ID, as you will need it later.

{% endlist %}


## Configure a link between the function and the Telegram bot {#function-bind-bot}

1. Update the API gateway specification:

    {% list tabs group=instructions %}

    - Management console {#console}

      1. In the [management console](https://console.yandex.cloud), select a folder.
      1. Navigate to **API Gateway**.
      1. Select the `for-serverless-hello-telegram-bot` API gateway.
      1. Update the API gateway specification by adding the `fshtb-function` section at the end of the code:

         ```yaml
           /fshtb-function:
             post:
               x-yc-apigateway-integration:
                 type: cloud_functions
                 function_id: <function_ID>
               operationId: fshtb-function
         ```
         
         Where `function_id` is the `fshtb-function` ID.

      1. Click **Save**.

    {% endlist %}

1. In the terminal, run the following command, with `<bot_token>` replaced with your Telegram bot token, and `<API_gateway_domain>`, with a link to your API gateway's service domain:
   
   * Linux, macOS:
   
      ```bash
      curl \
        --request POST \
        --url https://api.telegram.org/bot<bot_token>/setWebhook \
        --header 'content-type: application/json' \
        --data '{"url": "<API_gateway_domain>/fshtb-function"}'
      ```
   
   * Windows (cmd):
   
      ```bash
      curl ^
        --request POST ^
        --url https://api.telegram.org/bot<bot_token>/setWebhook ^
        --header "content-type: application/json" ^
        --data "{\"url\": \"<API_gateway_domain>/fshtb-function\"}"
      ```
   
   * Windows (PowerShell):
   
      ```powershell
      curl.exe `
        --request POST `
        --url https://api.telegram.org/bot<bot_token>/setWebhook `
        --header '"content-type: application/json"' `
        --data '"{ \"url\": \"<API_gateway_domain>/fshtb-function\" }"'
      ```
   
   Result:
   
   ```text
   {"ok":true,"result":true,"description":"Webhook was set"}
   ```

    Where:

    * `<bot_token>`: Telegram bot token.
    * `<API_gateway_domain>`: API gateway service domain.

    Result:

    ```bash
    {"ok":true,"result":true,"description":"Webhook was set"}
    ```


## Test your Telegram bot {#test-bot}

Chat with the bot:

1. Open Telegram and search for the bot using the previously created `username`.
1. Send `/start` to the chat.

    The bot should respond with:
    
    ```text
    Hello.
    My name Serverless Hello Telegram Bot
    I'm working on Cloud Function in the Yandex Cloud.
    ```

1. Send `/help` to the chat.
    
    The bot should respond with:
    
    ```text
    Hello, <username>.
    I can say Hello and nothing more
    ```

1. Send a text message to the chat. The bot should respond with an image and this message: `Hello, <username>`.


## How to delete the resources you created {#clear-out}

To stop paying for the resources you created:
1. [Delete](../../../functions/operations/function/function-delete.md) the function.
1. [Delete](../../operations/api-gw-delete.md) the API gateway.
1. [Delete](../../../storage/operations/buckets/delete.md) the bucket.


#### Useful links {#see-also}

* [How to create a Telegram bot using Serverless and Terraform](terraform.md)