How to create a Telegram bot
Using serverless technologies, you can create a Telegram bot that will respond to chat messages.
To create a bot:
- Prepare the environment.
- 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 work.
If you no longer need these resources, delete them.
Prepare the environment
-
Before creating a Telegram bot, sign up for Yandex Cloud and create a billing account:
- Go to the management console. Then log in to Yandex Cloud or sign up if don't already have an account.
- On the billing page, make sure you linked a billing account, and it has the
ACTIVE
orTRIAL_ACTIVE
status. If you don't have a billing account, create one.
-
Download the file archive needed to create the bot.
-
If you don't have a folder, create one.
-
Create a service account and assign it the
editor
and theserverless.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.
-
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 username for the bot being created, such asServerlessHelloTelegramBot
. 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.
-
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.
- Open the Object Storage service.
- Click Create bucket.
- On the bucket creation page:
- Enter a name for the bucket, such as
for-serverless-hello-telegram-bot
. 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.
- Enter a name for the bucket, such as
Upload the image to the bucket
- In the management console, select the folder that contains the previously created bucket.
- Open the Object Storage service.
- Select a previously created bucket.
- Click Upload.
- In the resulting window, select
sayhello.png
from the saved archive and click Open. The management console will display the file selected for upload. - Click Upload.
Obtain a link to the uploaded image
- In the management console, select the folder that contains the previously created bucket.
- Open the Object Storage service.
- Select a 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 wish to create an API gateway.
-
Open 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. In the
bucket
field, enter a name for the bucket. In theservice_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
-
Click Create.
-
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.
-
In the management console, select the folder where you wish to create the function.
-
Open 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('<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 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" } }
-
Indicate the following:
- Runtime environment:
nodejs12
. - Entry point:
index.handler
. - Timeout:
5 seconds
.
- Runtime environment:
-
Add the
BOT_TOKEN
variable to the environment. In the Value field, specify the Telegram bot token. -
Click Create version.
-
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.
-
Open API Gateway.
-
Select the
for-serverless-hello-telegram-bot
API gateway. -
Edit the API gateway specification by adding a
fshtb-function
section. Use thefunction_id
field to specify thefshtb-function
function ID./fshtb-function: post: x-yc-apigateway-integration: type: cloud-functions function_id: <function ID> operationId: fshtb-function
-
Click Save.
-
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:
-
Open Telegram and search for the bot using the previously created
username
as its username. -
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.
-
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 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: