How to create a Telegram bot
With serverless technology, you can create a Telegram bot that will respond to chat messages.
To create a bot:
- Set up your environment.
- Set up 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.
- Test your Telegram bot.
If you no longer need the resources you created, delete them.
Getting started
Sign up in Yandex Cloud and create a billing account:
- Navigate to the management console
and log in to Yandex Cloud or register a new account. - 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 and link a cloud to it.
If you have an active billing account, you can navigate to the cloud page
Learn more about clouds and folders.
Required paid resources
The cost of Telegram bot support includes:
- Fee for function invocation count, computing resources allocated to run the function, and outbound traffic (see Cloud Functions pricing).
- Fee for the amount of stored data, number of data operations, and outbound traffic (see Object Storage pricing).
- Fee for the number of requests to the API gateway and outbound traffic (see Yandex API Gateway pricing).
Set up 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.
Create a Telegram bot
Create a bot in Telegram and get a token.
-
To register the new bot, start BotFather
and run this command:/newbot
-
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. -
In the
username
field, specify a username for the bot, e.g.,ServerlessHelloTelegramBot
. This will allow users to find your bot on Telegram. The username must end with...Bot
or..._bot
.Once done, you will get a token. Save it, as you will need it later.
-
Set an icon for the bot using
sayhello.png
from the saved archive. Send this command to BotFather:/setuserpic
Post a bot image
If you want your bot to respond to user messages with an image, create an Object Storage bucket and upload sayhello.png
from the saved archive to it.
Create an Object Storage bucket
-
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 a name for the bucket. Save the bucket name, as you will need it later.
-
Specify these 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 created bucket. - Select Object Storage.
- Select the 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 containing the created bucket. - Select Object Storage.
- Select the bucket.
- Select
sayhello.png
. - Click Get link.
- Make sure the image is accessible through the link 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 Specification field and paste this code:
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 you created when setting up the resources.
-
Click Create.
-
Select the created API gateway. Save the Default domain field value, as you will need it later.
Create a function
If you want your Telegram bot to respond to the /start
and /help
commands and send an image in response to any other text, create a designated function.
-
In the management console
, select the folder where you want to create a function. -
Select Cloud Functions.
-
Click Create function.
-
Enter the function name:
fshtb-function
. -
Click Create.
-
Under Editor, select
Node.js
as the 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 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 settings:
- Runtime environment:
nodejs16
- Entry point:
index.handler
- Timeout:
5
- Runtime environment:
-
Add the
BOT_TOKEN
environment variable. In the Value field, specify the Telegram bot token. -
Click Save changes.
-
Make sure the function is public. To do this, navigate to the Overview page and enable Public function under General information.
-
Save your function ID, as you will need it later.
Configure a link between the function and the Telegram bot
-
In the management console
, select your 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 service domain.
Result:
{"ok":true,"result":true,"description":"Webhook was set"}
-
Test your Telegram bot
Chat with the bot:
-
Open Telegram and search for the bot using the previously created
username
. -
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.
-
Send
/help
to the chat.The bot should respond with:
Hello, <username>. I can say Hello and nothing more
-
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 created
To stop paying for the resources you created: