How to create a Telegram bot
Serverless technologies enable you to create a Telegram bot that will respond to chat messages.
To create a bot:
- Prepare the environment.
- Prepare the resources.
- Register your Telegram bot.
- Post a bot image.
- Create an API gateway.
- Create a function.
- Configure a link between the function and the Telegram bot.
- Check that the Telegram bot works.
If you no longer need the resources you created, delete them.
Getting started
Sign up for Yandex Cloud and create a billing account:
- Go to the management console
and log in to Yandex Cloud or create an account if you do not have one yet. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVE
orTRIAL_ACTIVE
status. If you do not have a billing account, create one.
If you have an active billing account, you can go to the cloud page
Learn more about clouds and folders.
Required paid resources
The cost of Telegram bot support includes:
- Fee for the number of function calls, computing resources allocated to executing the function, and outgoing traffic (see Cloud Functions pricing).
- Fee for the amount of stored data, the number of data transactions, 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).
Prepare the resources
- Download
the file archive required to create a bot. - Create a service account and assign it the
editor
andfunctions.functionInvoker
roles for your folder.
Register your Telegram bot
Register your bot in Telegram and get a token.
-
To register the new bot, launch the BotFather
bot and run the command below:/newbot
-
In the
name
field, enter a name for the new bot, e.g.,Serverless Hello Telegram Bot
. This is the name the bot users will see. -
In the
username
field, specify a username for the new bot, e.g.,ServerlessHelloTelegramBot
. You can use it to locate the bot in Telegram. The username must end with...Bot
or..._bot
.As a result, you will get a token. Save it. You will need it later.
-
Set an icon for the bot using the
sayhello.png
file 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 the sayhello.png
file from the saved archive to the bucket.
Create a bucket in Object Storage
-
In the management console
, select the folder you want to create a bucket in. -
Select Object Storage.
-
Click Create bucket.
-
On the bucket creation page:
-
Enter a name for the bucket. Save the bucket name. You will need it later.
-
Specify the bucket settings:
- Max size:
1 GB
- Object read access:
Public
- Storage class:
Standard
- Max size:
-
Click Create bucket.
-
Upload the image to the bucket
- In the management console
, select the folder containing the previously created bucket. - Select Object Storage.
- Select the previously created bucket.
- Click Upload.
- In the window that opens, select the
sayhello.png
file from the saved archive. The management console will display the file selected for upload. - Click Upload.
Get a link to the uploaded image
- In the management console
, select the folder containing the previously created bucket. - Select Object Storage.
- Select the previously created bucket.
- Select
sayhello.png
. - Click Get link.
- Check that the image is available in your browser.
Create an API gateway
Create and configure an API Gateway.
-
In the management console
, select the folder where you want to create an API gateway. -
Select API Gateway.
-
Click Create API gateway.
-
Name the gateway:
for-serverless-hello-telegram-bot
. -
Clear the contents of the Specification field and replace them with the code below:
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 created when setting up resources.
-
Click Create.
-
Select the created API gateway. Save the Default domain field value. You will need it later.
Create a function
To make the Telegram bot respond to the /start
and /help
commands and send an image in response to any other text, create a function.
-
In the Management console
, select the folder you want to create a function in. -
Select Cloud Functions.
-
Click Create function.
-
Enter the function name:
fshtb-function
. -
Click Create.
-
Under Editor, select the
Node.js
runtime environment and click Continue. -
Under Function code, replace the contents of the
index.js
file with the code below. Instead of<API_gateway_domain>
, specify the API gateway service domain.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: '', }; };
-
Under Function code, create a file named
package.json
and paste the following code into it:{ "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" } }
-
Specify the following parameters:
- Runtime environment:
nodejs16
- Entry point:
index.handler
- Timeout, sec:
5
- Runtime environment:
-
Add the
BOT_TOKEN
environment variable. In the Value field, specify the Telegram bot token. -
Click Save changes.
-
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.
-
Save your function ID. You will need it later.
Configure a link between the function and the Telegram bot
-
In the management console
, select the folder. -
Select API Gateway.
-
Select the
for-serverless-hello-telegram-bot
API gateway. -
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 thefshtb-function
ID. -
Click Save.
-
Run the following request in the terminal:
-
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\" }"'
Where:
<bot_token>
: Telegram bot token.<API_gateway_domain>
: API gateway's service domain.
Result:
{"ok":true,"result":true,"description":"Webhook was set"}
-
Check that the Telegram bot works
Talk to the bot:
-
Open Telegram and search for the bot using the previously created
username
. -
Send the
/start
message 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.
-
Send the
/help
message to the chat.The bot should respond with:
Hello, <username>. I can say Hello and nothing more
-
Send any text message to the chat. The bot should respond with an image and this message:
Hello, <username>
.
How to delete the resources you created
To stop paying for the resources you created: