Yandex Cloud
Search
Discuss with expertTry it for free
  • Customer Stories
  • Documentation
  • Blog
  • All Services
  • System Status
  • Marketplace
    • Featured
    • Infrastructure & Network
    • Data Platform
    • AI for business
    • Security
    • DevOps tools
    • Serverless
    • Monitoring & Resources
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Start testing with double trial credits
    • Cloud credits to scale your IT product
    • Gateway to Russia
    • Cloud for Startups
    • Center for Technologies and Society
    • Yandex Cloud Partner program
    • Price calculator
    • Pricing plans
  • Customer Stories
  • Documentation
  • Blog
© 2026 Direct Cursus Technology L.L.C.
Yandex Object Storage
    • All tutorials
    • Getting statistics on object queries with S3 Select
    • Getting website traffic statistics with S3 Select
    • Getting statistics on object queries using Yandex Query
    • Cost analysis by resource
    • Server-side encryption
    • Blue-green and canary deployment of service versions
    • Analyzing logs in DataLens
    • Mounting buckets to Yandex Data Processing host filesystems
    • Using Object Storage in Yandex Data Processing
    • Importing, processing, and exporting Object Storage data to Managed Service for ClickHouse®
    • Connecting a bucket as a disk in Windows
    • Migrating data from Yandex Data Streams using Yandex Data Transfer
    • Using hybrid storage in Yandex Managed Service for ClickHouse®
    • Loading data from Yandex Managed Service for OpenSearch to Yandex Object Storage using Yandex Data Transfer
    • Automatically copying objects from one bucket to another
    • Regular asynchronous recognition of audio files in a bucket
    • Training a model in Yandex DataSphere on data from Object Storage
    • Connecting to Object Storage from VPC
    • Migrating data to Yandex Managed Service for PostgreSQL using Yandex Data Transfer
    • Uploading data to Yandex MPP Analytics for PostgreSQL using Yandex Data Transfer
    • Uploading data to Yandex Managed Service for ClickHouse® using Yandex Data Transfer
    • Uploading data to Yandex Managed Service for YDB using Yandex Data Transfer
    • Exchanging data between Yandex Managed Service for ClickHouse® and Yandex Data Processing
    • Uploading data from Yandex Managed Service for YDB using Yandex Data Transfer
    • Hosting a static Gatsby website in Object Storage
    • Installing WordPress High Availability using Cloud Apps
    • Installing WordPress using Cloud Apps
    • Installing Ghost CMS High Availability using Cloud Apps
    • Migrating a database from Managed Service for PostgreSQL to Object Storage
    • Exchanging data between Yandex Managed Service for ClickHouse® and Yandex Data Processing
    • Importing data from Yandex Managed Service for PostgreSQL to Yandex Data Processing using Sqoop
    • Importing data from Yandex Managed Service for MySQL® to Yandex Data Processing using Sqoop
    • Migrating data from Yandex Object Storage to Yandex Managed Service for MySQL® using Yandex Data Transfer
    • Migrating a database from Yandex Managed Service for MySQL® to Yandex Object Storage
    • Exporting Greenplum® data to a cold storage in Yandex Object Storage
    • Loading data from Yandex Direct to a Yandex Managed Service for ClickHouse® data mart using Yandex Cloud Functions, Yandex Object Storage, and Yandex Data Transfer
    • Uploading Terraform states to Object Storage
    • Locking Terraform states using Managed Service for YDB
    • Visualizing Yandex Query data
    • Publishing game updates
    • Developing a custom integration in API Gateway
    • Storing application runtime logs
    • Building a skill for Alice and a website with authorization
    • Building an interactive serverless application using WebSocket
    • Deploying a web application using the Java Servlet API
      • Overview
      • Management console
      • Terraform
    • Replicating logs to Object Storage using Fluent Bit
    • Replicating logs to Object Storage using Data Streams
    • Uploading audit logs to ArcSight SIEM
    • Uploading audit logs to Splunk SIEM
    • Creating an MLFlow server for logging experiments and artifacts
    • Operations with data in Yandex Query
    • Federated data queries using Query
    • Recognizing text in image archives using Vision OCR
    • Scheduled image and PDF recognition in an Object Storage bucket
    • Automating tasks using Managed Service for Apache Airflow™
    • Processing files with usage details in Yandex Cloud Billing
    • Deploying a web app with JWT authorization in API Gateway and Firebase authentication
    • Searching for Yandex Cloud events in Yandex Query
    • Searching for Yandex Cloud events in Object Storage
    • Creating an external table from a bucket table using a configuration file
    • Migrating databases from Google BigQuery to Managed Service for ClickHouse®
    • Using Object Storage in Yandex Managed Service for Apache Spark™
  • Pricing policy
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Bucket logs
  • Release notes
  • FAQ

In this article:

  • Get your cloud ready
  • Required paid resources
  • Create a Telegram bot
  • Create the infrastructure
  • Test your Telegram bot
  • How to delete the resources you created
  1. Tutorials
  2. Developing a Telegram bot
  3. Terraform

How to create a Telegram bot using Serverless and Terraform

Written by
Yandex Cloud
Updated at June 17, 2026
  • Get your cloud ready
    • Required paid resources
  • Create a Telegram bot
  • Create the infrastructure
  • Test your Telegram bot
  • How to delete the resources you created

To create a Telegram bot using Serverless and Terraform:

  1. Get your cloud ready.
  2. Create a Telegram bot.
  3. Create the infrastructure.
  4. Test your Telegram bot.

If you no longer need the resources you created, delete them.

Get your cloud readyGet your cloud ready

Sign up for Yandex Cloud and create a billing account:

  1. Navigate to the management console and log in to Yandex Cloud or create a new account.
  2. On the Yandex Cloud Billing page, make sure you have a billing account linked and it has the ACTIVE or TRIAL_ACTIVE status. If you do not have a billing account, create one and link a cloud to it.

If you have an active billing account, you can create or select a folder for your infrastructure on the cloud page.

Learn more about clouds and folders here.

Required paid resourcesRequired paid resources

The cost of supporting the Telegram bot infrastructure includes:

  • Fee for function calls, computing resources allocated for the function, and outgoing traffic (see Cloud Functions pricing).
  • Fee for data storage in Object Storage, operations with data, and outgoing traffic (see Object Storage pricing).
  • Fee for the number of requests to the API gateway and outgoing traffic (see Yandex API Gateway pricing).

Create a Telegram botCreate a Telegram bot

Create a bot in Telegram and get a token.

  1. To register a new bot, start BotFather and run the below command.

    /newbot
    
  2. 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.

  3. 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.

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

    /setuserpic
    

Create the infrastructureCreate the infrastructure

With Terraform, you can quickly create a cloud infrastructure in Yandex Cloud and manage it using configuration files. These files store the infrastructure description written in HashiCorp Configuration Language (HCL). If you change the configuration files, Terraform automatically detects which part of your configuration is already deployed, and what should be added or removed.

Terraform is distributed under the Business Source License. The Yandex Cloud provider for Terraform is distributed under the MPL-2.0 license.

For more information about the provider resources, see the relevant documentation on the Terraform website or its mirror.

To create your infrastructure via Terraform:

  1. Install Terraform, obtain authentication credentials, and specify the source for installing the Yandex Cloud provider. For details, see Configure your provider, step 1.

  2. Prepare your infrastructure description files:

    Ready-made configuration
    Manually
    1. Clone the repository with the configuration files required to create the bot. Do it by running this git command in the terminal:

      git clone https://git@git.sourcecraft.dev/yandex-cloud-examples/yc-telegram-bot-serverless.git
      
    2. Navigate to the repository directory. It should now contain the following files:

      • telegram-bot.tf: New infrastructure configuration.
      • telegram-bot.auto.tfvars: User data file.
      • telegram-bot-function.tpl: Template for creating a function in Yandex Cloud Functions.
      • telegram-bot-gw-spec.tpl: API gateway specification template.
      • sayhello.png: Your bot image.
      • package.json: Manifest for the Node.js function.
    1. Create a folder for configuration files.

    2. In the folder, create:

      1. telegram-bot.tf configuration file:

        telegram-bot.tf
        # Declaring variables with sensitive data
        
        variable "cloud_id" {
          type = string
        }
        
        variable "folder_id" {
          type = string
        }
        
        variable "bucket_name" {
          type = string
        }
        
        variable "bot_token" {
          type      = string
          sensitive = true
        }
        
        # Configuring the provider
        
        terraform {
          required_providers {
            yandex = {
              source = "yandex-cloud/yandex"
            }
          }
        }
        
        provider "yandex" {
          cloud_id  = var.cloud_id
          folder_id = var.folder_id
        }
        
        # Creating a service account
        
        resource "yandex_iam_service_account" "bot_sa" {
          name        = "telegram-bot-sa"
          description = "Service Account for Telegram bot"
        }
        
        # Assigning roles to a service account
        
        resource "yandex_resourcemanager_folder_iam_member" "sa_editor" {
          folder_id = var.folder_id
          role      = "editor"
          member    = "serviceAccount:${yandex_iam_service_account.bot_sa.id}"
        
          depends_on = [yandex_iam_service_account.bot_sa]
        }
        
        resource "yandex_resourcemanager_folder_iam_member" "sa_invoker" {
          folder_id = var.folder_id
          role      = "functions.functionInvoker"
          member    = "serviceAccount:${yandex_iam_service_account.bot_sa.id}"
        
          depends_on = [yandex_iam_service_account.bot_sa]
        }
        
        # Creating static access keys
        
        resource "yandex_iam_service_account_static_access_key" "bot_sa_key" {
          service_account_id = yandex_iam_service_account.bot_sa.id
          description        = "Static key for bot service account"
        
          depends_on = [
            yandex_resourcemanager_folder_iam_member.sa_editor
          ]
        }
        
        # Creating a bucket
        
        resource "yandex_storage_bucket" "bot_bucket" {
          bucket     = var.bucket_name
          access_key = yandex_iam_service_account_static_access_key.bot_sa_key.access_key
          secret_key = yandex_iam_service_account_static_access_key.bot_sa_key.secret_key
          anonymous_access_flags {
            read = true
          }
        
          depends_on = [
            yandex_iam_service_account_static_access_key.bot_sa_key
          ]
        }
        
        # Uploading an image to a bucket
        
        resource "yandex_storage_object" "sayhello_png" {
          bucket       = yandex_storage_bucket.bot_bucket.bucket
          key          = "sayhello.png"
          source       = "sayhello.png"
          acl          = "public-read"
          access_key   = yandex_iam_service_account_static_access_key.bot_sa_key.access_key
          secret_key   = yandex_iam_service_account_static_access_key.bot_sa_key.secret_key
          content_type = "image/png"
        
          depends_on = [yandex_storage_bucket.bot_bucket]
        }
        
        # Creating a zip archive for a function
        
        data "archive_file" "function" {
          type        = "zip"
          source {
            content  = templatefile("telegram-bot-function.tpl", {
              API_GW_URL = yandex_api_gateway.bot_gateway.domain
            })
            filename = "index.js"
          }
          source {
            content  = "${file("package.json")}"
            filename = "package.json"
          }
          output_path = "function.zip"
        
          depends_on = [yandex_api_gateway.bot_gateway]
        }
        
        # Creating a public function
        
        resource "yandex_function" "telegram_bot_function" {
          name               = "fshtb-function"
          description        = "Serverless Telegram bot on Node.js"
          runtime            = "nodejs22"
          entrypoint         = "index.handler"
          memory             = 256
          execution_timeout  = 5
          service_account_id = yandex_iam_service_account.bot_sa.id
        
          environment = {
            BOT_TOKEN = var.bot_token
          }
        
          content {
            zip_filename = "function.zip"
          }
        
          user_hash = filesha256("telegram-bot-function.tpl")
        
          depends_on = [
            yandex_resourcemanager_folder_iam_member.sa_editor,
            yandex_resourcemanager_folder_iam_member.sa_invoker,
            data.archive_file.function
          ]
        }
        
        resource "yandex_function_iam_binding" "public_invoker" {
          function_id = yandex_function.telegram_bot_function.id
          role        = "functions.functionInvoker"
          members     = ["system:allUsers"]
        }
        
        # Creating an API gateway
        
        resource "yandex_api_gateway" "bot_gateway" {
          name        = "forserverless-hello-telegram-bot"
          description = "API gateway for telegram bot"
        
          spec = templatefile("telegram-bot-gw-spec.tpl", {
            BUCKET_NAME = yandex_storage_bucket.bot_bucket.id
            OBJECT_NAME = yandex_storage_object.sayhello_png.key
            SA_ID       = yandex_iam_service_account.bot_sa.id
          })
        }
        
      2. telegram-bot-function.tpl template for creating a function in Yandex Cloud Functions:

        telegram-bot-function.tpl
        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: 'https://${API_GW_URL}/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: '',
            };
        }; 
        
      3. telegram-bot-gw-spec.tpl API gateway specification template:

        telegram-bot-gw-spec.tpl
        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: ${OBJECT_NAME}
                presigned_redirect: false
                service_account: ${SA_ID}
              operationId: static
        
      4. telegram-bot.auto.tfvars user data file:

        bot_token   = "<Telegram_bot_token>"
        bucket_name = "<bucket_name>"
        cloud_id    = "<cloud_ID>"
        folder_id   = "<folder_ID>"
        
      5. package.json manifest for the Node.js function:

        {
          "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"
          }
        }
        

    For more information about Terraform resource properties, see the relevant provider guides:

    • Service account: yandex_iam_service_account.
    • Assigning a role to a service account: yandex_resourcemanager_folder_iam_member.
    • Static access key: yandex_iam_service_account_static_access_key.
    • Bucket: yandex_storage_bucket
    • Object: yandex_storage_object
    • API gateway: yandex_api_gateway.
    • Function: yandex_function.
    • Assigning roles for a function: yandex_function_iam_binding.
  3. In the telegram-bot.auto.tfvars file, specify these custom settings:

    • bot_token: Telegram bot token.
    • bucket_name: Bucket name.
    • cloud_id: Cloud ID.
    • folder_id: Folder ID.
  4. Create the resources:

    1. In the terminal, navigate to the configuration file directory.

    2. Make sure the configuration is correct using this command:

      terraform validate
      

      If the configuration is valid, you will get this message:

      Success! The configuration is valid.
      
    3. Run this command:

      terraform plan
      

      You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.

    4. Apply the configuration changes:

      terraform apply
      
    5. Type yes and press Enter to confirm the changes.

  5. Configure a link between the function and the Telegram bot.

    1. Update the API gateway specification by adding the fshtb-function section at the end of the code:

        /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.

    2. Apply the configuration changes:

      terraform apply
      
    3. Type yes and press Enter to confirm the changes.

    4. 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:

        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):

        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):

        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:

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

Test your Telegram botTest your Telegram bot

Chat with the bot:

  1. Open Telegram and search for the bot using the previously created username.

  2. Send /start to the chat.

    The bot should respond with:

    Hello.
    My name Serverless Hello Telegram Bot
    I'm working on Cloud Function in the Yandex Cloud.
    
  3. Send /help to the chat.

    The bot should respond with:

    Hello, <username>.
    I can say Hello and nothing more
    
  4. 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 createdHow to delete the resources you created

To stop paying for the resources you created:

  1. Open the telegram-bot.tf file and delete your infrastructure description from it.

  2. Apply the changes:

    1. In the terminal, navigate to the configuration file directory.

    2. Make sure the configuration is correct using this command:

      terraform validate
      

      If the configuration is valid, you will get this message:

      Success! The configuration is valid.
      
    3. Run this command:

      terraform plan
      

      You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.

    4. Apply the configuration changes:

      terraform apply
      
    5. Type yes and press Enter to confirm the changes.

See alsoSee also

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

Was the article helpful?

Previous
Management console
Next
Replicating logs to Object Storage using Fluent Bit
© 2026 Direct Cursus Technology L.L.C.