Yandex Cloud
  • Services
  • Solutions
  • Why Yandex Cloud
  • Pricing
  • Documentation
  • Contact us
Get started
Language / Region
© 2022 Yandex.Cloud LLC
Yandex Cloud Functions
  • Comparison with other Yandex Cloud services
  • Getting started
    • Overview
    • Creating a function
      • Overview
      • Node.js
      • Python
      • Go
      • PHP
      • Bash
      • Java
    • Creating a trigger
      • Overview
      • Timer
      • Trigger for Message Queue
      • Trigger for Object Storage
      • Trigger for Container Registry
      • Trigger for Cloud Logs
      • Trigger for Cloud Logging
      • Trigger for Yandex IoT Core
      • Trigger for budgets
      • Trigger for Data Streams
  • Step-by-step instructions
    • All instructions
    • Using functions to get an IAM token for a service account
    • Connecting to managed databases from functions
    • Managing rights to access functions
    • Managing functions
      • Creating a function
      • Managing function versions
      • Working in the code editor
      • Invoking a function
      • Updating a function
      • Scaling a function
      • Function monitoring
      • Viewing the execution log
      • Deleting a function
    • Managing triggers
      • Getting information about a trigger
      • Creating a timer
      • Creating a trigger for Message Queue
      • Creating a trigger for Object Storage
      • Creating a trigger for Container Registry
      • Creating a trigger for Cloud Logs
      • Creating a trigger for Cloud Logging
      • Creating a trigger for Yandex IoT Core
      • Creating a trigger for budgets
      • Creating a trigger for Data Streams
      • Updating a trigger
      • Trigger monitoring
      • Deleting a trigger
  • Concepts
    • Overview
    • Function
    • Invoking a function
    • Runtime environment
      • Overview
      • Environment
      • Execution context
      • Preloaded runtime environment
    • Builder
    • Trigger
      • Overview
      • Timer
      • Trigger for Message Queue
      • Trigger for Object Storage
      • Trigger for Container Registry
      • Trigger for Cloud Logs
      • Trigger for Cloud Logging
      • Trigger for Yandex IoT Core
      • Trigger for budgets
      • Trigger for Data Streams
    • Dead Letter Queue
    • Log groups
    • Backups
    • Quotas and limits
  • Developing in Node.js
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in Python
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in Go
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in PHP
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
  • Developing in Bash
    • Overview
    • Request handler
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in Java
    • Overview
    • Programming model
      • Overview
      • Function interface
      • YcFunction interface
      • HttpServlet class
      • Spring Boot
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in R
    • Overview
    • Programming model
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
  • Developing in C#
    • Overview
    • Programming model
      • Overview
      • Function interface
      • YcFunction interface
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Practical guidelines
    • Creating skills for Alice
    • Deploying a web application
    • Developing a skill for Alice and a website with authorization
    • Writing data from a device to Managed Service for PostgreSQL
    • Developing a Slack bot
    • Developing a Telegram bot
    • Connecting to a YDB database from a Python function
    • Connecting to a YDB database from a function in Node.js
    • Converting a video to a GIF in Python
    • Building Node.js function using TypeScript
  • Pricing policy
  • Access management
  • API Functions reference
    • Authentication in the API
    • gRPC
      • Overview
      • FunctionService
      • OperationService
    • REST
      • Overview
      • Function
        • Overview
        • create
        • createVersion
        • delete
        • get
        • getVersion
        • getVersionByTag
        • list
        • listAccessBindings
        • listOperations
        • listRuntimes
        • listScalingPolicies
        • listTagHistory
        • listVersions
        • removeScalingPolicy
        • removeTag
        • setAccessBindings
        • setScalingPolicy
        • setTag
        • update
        • updateAccessBindings
  • API Triggers reference
    • Authentication in the API
    • gRPC
      • Overview
      • TriggerService
      • OperationService
    • REST
      • Overview
      • Trigger
        • Overview
        • create
        • delete
        • get
        • list
        • listOperations
        • pause
        • resume
        • update
  • Questions and answers
  1. Practical guidelines
  2. Developing a Telegram bot

How to create a Telegram bot

Written by
Yandex Cloud
  • Prepare the environment
    • Required paid resources
  • Register the Telegram bot
  • Post a bot image
    • Create a bucket in Object Storage
    • Upload the image to the bucket
    • Obtain a link to the uploaded image
  • Create an API gateway
  • Create a function
  • Configure a link between the function and the Telegram bot
  • Check that the Telegram bot work
  • How to delete created resources

Using serverless technologies, you can create a Telegram bot that will respond to chat messages.

To create a bot:

  1. Prepare the environment.
  2. Register the Telegram bot.
  3. Post a bot image.
  4. Create an API gateway.
  5. Create a function.
  6. Configure a link between the function and the Telegram bot.
  7. Check that the Telegram bot work.

If you no longer need these resources, delete them.

Prepare the environment

  1. Before creating a Telegram bot, sign up for Yandex Cloud and create a billing account:

    1. Go to the management console. Then log in to Yandex Cloud or sign up if don't already have an account.
    2. On the billing page, make sure you linked a billing account, and it has the ACTIVE or TRIAL_ACTIVE status. If you don't have a billing account, create one.
  2. Download the file archive needed to create the bot.

  3. If you don't have a folder, create one.

  4. Create a service account and assign it the editor and the serverless.functions.invoker roles for your folder.

Required paid resources

The cost of Telegram bot support includes:

  • Payment for the number of function calls, computing resources allocated to executing the function, and outgoing traffic (see Cloud Functions pricing).
  • Payment for the amount of stored data, the number of data transactions, and outgoing traffic (see Object Storage pricing).
  • Payment for the number of requests to the API gateway and outgoing traffic (see Yandex API Gateway pricing).

Register the Telegram bot

Register your bot in Telegram and get a token.

  1. To register the new bot, launch the BotFather bot and run the command below:

    /newbot
    
  2. In the name field, enter a name for the bot being created, such as Serverless Hello Telegram Bot. This is the name users will see when communicating with the bot.

  3. In the username field, enter the username for the bot being created, such as ServerlessHelloTelegramBot. You can use the username to search for the bot in Telegram. The user name must end with ...Bot or ..._bot.

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

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

    /setuserpic
    

Post a bot image

For the bot to respond to user messages with an image, create a bucket in Object Storage and upload sayhello.png from the saved archive to the bucket.

Create a bucket in Object Storage

Management console
  1. In the management console, select the folder where you want to create a bucket.
  2. Open the Object Storage service.
  3. Click Create bucket.
  4. On the bucket creation page:
    1. Enter a name for the bucket, such as for-serverless-hello-telegram-bot. Save the bucket name. You will need it later.
    2. Specify the bucket settings:
      • Max size: 1 GB.
      • Object read access: Public.
      • Storage class: Standard.
    3. Click Create bucket.

Upload the image to the bucket

Management console
  1. In the management console, select the folder that contains the previously created bucket.
  2. Open the Object Storage service.
  3. Select a previously created bucket.
  4. Click Upload.
  5. In the resulting window, select sayhello.png from the saved archive and click Open. The management console will display the file selected for upload.
  6. Click Upload.

Obtain a link to the uploaded image

Management console
  1. In the management console, select the folder that contains the previously created bucket.
  2. Open the Object Storage service.
  3. Select a previously created bucket.
  4. Select sayhello.png.
  5. Click Get link.
  6. Check that the image is available in your browser.

Create an API gateway

Create and configure an API Gateway.

Management console
  1. In the management console, select the folder where you wish to create an API gateway.

  2. Open API Gateway.

  3. Click Create API gateway.

  4. Enter a name for the gateway: for-serverless-hello-telegram-bot.

  5. Clear the contents of the Specification field and replace them with the code below. In the bucket field, enter a name for the bucket. In the service_account field, enter the service account ID.

    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: <service account ID>
          operationId: static
    
  6. Click Create.

  7. Select the created API gateway. Save the name of the Service domain field from the General information section. You will need it later.

Create a function

To have the Telegram bot respond to the /start and /help commands and send an image in response to any other text, create a function.

Management console
  1. In the management console, select the folder where you wish to create the function.

  2. Open Cloud Functions.

  3. Click Create function.

  4. Enter a name for the function: fshtb-function.

  5. Click Create.

  6. Under Editor, select the Node.js runtime environment and click Continue.

  7. Under Function code, replace the contents of the index.js file with the code below: Replace <API gateway domain> with the API gateway's service domain.

    const { Telegraf } = require('telegraf');
    
    const bot = new Telegraf(process.env.BOT_TOKEN);
    bot.start((ctx) => ctx.reply(`Hello. \nMy name is Serverless Hello Telegram Bot \nI'm working on Cloud Function in 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('<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: '',
        };
    };
    
  8. Under Function code, create a file called package.json with the code below:

    {
      "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": "^3.38.0"
      }
    }
    
  9. Indicate the following:

    • Runtime environment: nodejs12.
    • Entry point: index.handler.
    • Timeout: 5 seconds.
  10. Add the BOT_TOKEN variable to the environment. In the Value field, specify the Telegram bot token.

  11. Click Create version.

  12. Make sure that the function is public. To do this, go to the Overview page and, under General information, switch the Public function option to on.

  13. Save your function ID. You will need it later.

Configure a link between the function and the Telegram bot

Management console
  1. In the management console, select the appropriate folder.

  2. Open API Gateway.

  3. Select the for-serverless-hello-telegram-bot API gateway.

  4. Edit the API gateway specification by adding a fshtb-function section. Use the function_id field to specify the fshtb-function function ID.

      /fshtb-function:
        post:
          x-yc-apigateway-integration:
            type: cloud-functions
            function_id: <function ID>
          operationId: fshtb-function
    
  5. Click Save.

  6. Run the request replacing <bot token> with that of the Telegram bot and the <API gateway domain> with the API gateway service domain:

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

Check that the Telegram bot work

Talk to the bot:

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

  2. Send the message /start in the chat.

    The bot must respond with:

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

    The bot must respond with:

    Hello, <username>.
    I can say Hello and nothing more
    
  4. Send any text message in the chat. The bot must respond with an image and Hello, <username>.

How to delete created resources

To stop paying for the resources created, delete them:

  1. Delete the function.
  2. Delete the API gateway.
  3. Delete the bucket.

Was the article helpful?

Language / Region
© 2022 Yandex.Cloud LLC
In this article:
  • Prepare the environment
  • Required paid resources
  • Register the Telegram bot
  • Post a bot image
  • Create a bucket in Object Storage
  • Upload the image to the bucket
  • Obtain a link to the uploaded image
  • Create an API gateway
  • Create a function
  • Configure a link between the function and the Telegram bot
  • Check that the Telegram bot work
  • How to delete created resources