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.
- Set up resources.
- Register the 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).
Create resources
- Download
the archive with the files required to create a bot. - Create a service account and assign it the
editor
andfunctions.functionInvoker
roles for your folder.
Register the 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 bot being created, such asServerless Hello Telegram Bot
. This is the name users will see when communicating with the bot. -
In the
username
field, enter the user name for the bot being created, such asServerlessHelloTelegramBot
. You can use the user name 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.
-
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
-
In the management console
, select the folder where you want to create a bucket. -
Select Object Storage.
-
Click Create bucket.
-
On the bucket creation page:
-
Enter the name of 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 that contains the previously created bucket. - Select Object Storage.
- Select the previously created bucket.
- Click Upload.
- In the window that opens, select
sayhello.png
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 that contains 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.
-
Enter a name for 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 name of the Default domain field. 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.
-
In the management console
, select the folder to create the function in. -
Select Cloud Functions.
-
Click Create function.
-
Enter a name for the function:
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: 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({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
with the following code:{ "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
variable to the environment. 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 appropriate folder. -
Select API Gateway.
-
Select the
for-serverless-hello-telegram-bot
API gateway. -
Edit the API gateway specification by appending a
fshtb-function
section at the end:/fshtb-function: post: x-yc-apigateway-integration: type: cloud_functions function_id: <function_ID> operationId: fshtb-function
Where
function_id
is thefshtb-function
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
as its username. -
Send a message saying
/start
to the chat.The bot must respond with:
Hello. My name is Serverless Hello Telegram Bot I'm working on Cloud Function in the Yandex Cloud.
-
Send the message
/help
in the chat.The bot must respond with:
Hello, <username>. I can say Hello and nothing more
-
Send any text message to the chat. The bot must respond with an image and
Hello, <username>
.
How to delete the resources you created
To stop paying for the resources you created: