Building a Telegram bot in Yandex.Cloud

Building a Telegram bot in Yandex.Cloud

Today, from improvised materials, we will collect in Yandex.Cloud Telegram bot using Yandex Cloud Functions (or Yandex functions for brevity) and Yandex Object Storage (or Object Storage - for clarity). The code will be on Node.js. However, there is one piquant circumstance - a certain organization called, let's say, RossKomCensorship (censorship is prohibited by article 29 of the Constitution of the Russian Federation), does not allow Internet providers in Russia to transfer requests to Telegram API by the address: https://api.telegram.org/. Well, we won't - no, no. Indeed, in our bag there are so-called. webhooks - with their help, we do not make requests to a specific address, but only send our request as a response to any request to us. That is, as in Odessa - we answer a question with a question. That's why Telegram API will not appear in our code.

DisclaimerThe names of any state organizations mentioned in this article are fictitious, and possible coincidences with the names of real-life organizations are accidental.

So, we will make a bot that will supply us with smart thoughts. Exactly like in the picture:

Building a Telegram bot in Yandex.Cloud

You can try it in action - here is the name: @SmartThoughtsBot. Notice the button "Alice's Skill"? This is because the bot is a kind of "companion" for the eponymous Alice's skill, i.e. it performs the same functions as Alice's skill and, perhaps, that they can coexist peacefully advertising each other. About how to create Smart Thought skill described in the article Alice gets the skill. Now (after making some changes after the publication of the above article) on a smartphone this skill will look something like this:

Building a Telegram bot in Yandex.Cloud

Bot creation

I would like this tutorial to be useful to everyone, incl. and beginner "bot builders". Therefore, in this section I will describe in some detail how to create in general in Telegram'e bots. For those who do not need this information, proceed to the next sections.

Open the application Telegaram, we call the father of all bots (they have everything like people) - @BotFather - and to begin with, we will give him the / help command to refresh our memory of what we can do. Now we are interested in the team / newbot.

Building a Telegram bot in Yandex.Cloud

Since the bot described here has already been created, for demonstration purposes I will create another bot for a short time (then I will delete it). I'll call him DemoHabrBot. Names (username) all telegram bots must end with a word muzzle, For example: MyCoolBot or my_cool_bot This is for bots. But first, give the bot a name (name) is for people. The name can be in any language, contain spaces, does not have to end with a word muzzle, and doesn't even have to be unique. In this example, I called this bot Demo Habr.

Building a Telegram bot in Yandex.Cloud

Now choose a name for the bot (username, the one for bots). Let's call it DemoHabrBot. Everything related to the name of the bot (name) is not related to his name at all - username (or applies, but exactly the opposite). After successfully creating a unique bot name, we need to copy and save (in the strictest confidence!) The token shown in the screenshot with a red arrow. With its help, we will later install the outgoing Telegram'a webhook to our Yandex function.

Building a Telegram bot in Yandex.Cloud

And now we will give the command to the father of all bots: /mybotsand it will show us a list of all the bots we have created. Let's leave the freshly baked bot alone for now Demo Habr (it was created to show how to create bots, but we will use it today for other demonstration purposes), and consider the bot Smart Thoughts (@SmartThoughtsBot). Click the button with its name in the list of bots.

Building a Telegram bot in Yandex.Cloud

This is where we can set up our bot. Pushing a button Edit ... we will move on to editing one or another option. For example, by clicking on the button Edit Name we can change the name of the bot, say instead of Smart Thoughtswrite crazy ideas. Botpic - this is the bot's avatar, must be at least 150 x 150 px. Description is a short description that the user sees when the bot is launched for the first time, as an answer to the question: What can this bot do? About - an even shorter description, which is transmitted with a link to the bot (https://t.me/SmartThoughtsBot) or when viewing information about it.

Building a Telegram bot in Yandex.Cloud

We just need to set up the commands. To do this, press the button Edit Commands. To standardize user practices Telegram recommends always using two commands: / start ΠΈ / help, and if the bot needs settings, an additional /settings command. Our bot is as simple as a ball, so it doesn't need any settings yet. We write the first two commands, which we will then process in the code. Now, if the user enters a slash (slash : /) in the input field, a list of commands will appear for their quick selection. Everything is as in the picture: on the left - we set commands through the bot-father; on the right, these commands are already available to users in our bot.

Building a Telegram bot in Yandex.Cloud

Yandex function

Now that our bot has been created, let's go to Yandex.Cloudto create a function that will execute our bot code. If you have not worked with Yandex.Cloud read the material Alice in the land of Bitrix, and then - Yandex functions send mail. I am almost sure that these two relatively small articles will be enough for you to have a basic understanding of the subject.

So in the console Yandex.Clouds in the left navigation menu, select the item Cloud Functions, and then press the button Create a function. We give it a name, and for ourselves - a brief description.

Building a Telegram bot in Yandex.Cloud

After pressing the Create and after a couple of seconds, the new function will appear in the list of all functions. Click on her name - this will take us to the page Review our function. Here you need to enableOn) switch public functionto make it available from the external (for Yandex.Clouds) of the world, and the value of the fields Link to call ΠΈ Identifier - keep it in deep secret from everyone except yourself and Telegram, so that various swindlers cannot call your function.

Building a Telegram bot in Yandex.Cloud

Now using the left menu go to Editor functions. Let us put aside for a moment our Smart Thoughts, and create a minimal template function to check the performance of our bot ... However, in this context, this function is our bot ... In short, now and right here we will make the simplest bot that will β€œmirror” (i.e. send back ) user requests. This template can always be used when creating new telegram bots to make sure that communication with Telegram'om works fine. Click Create file, call it index.js, and online Code editor paste the following code into this file:

module.exports.bot = async (event) => {
  
  const body = JSON.parse(event.body);

  const msg = {
    'method': 'sendMessage',
    'chat_id': body.message.chat.id,
    'text': body.message.text
  };

  return {
    'statusCode': 200,
    'headers': {
      'Content-Type': 'application/json'
    },
    'body': JSON.stringify(msg),
    'isBase64Encoded': false
  };
};

In the Yandex.Cloud console, it should look something like this:

Building a Telegram bot in Yandex.Cloud

Below, we indicate entry point β€” index.botWhere index this is the filename (index.js), and muzzle - function name (module.exports.bot). Leave all other fields "as is", and in the upper right corner click the button Create Version. After a few seconds, this version of the function will be created. Soon after testing webhook, we will create a new version βˆ’ Smart Thoughts.

Building a Telegram bot in Yandex.Cloud

Object Storage

Now that we have set up Yandex functionlet's go while we're in the console Yandex.Clouds, create a so-called. bucket (bucket, i.e. bucket in Russian, by no means a bouquet) for storing image files that will be used in our bot Smart Thoughts. Select from the left navigation menu object-storage, press the button Create bucket, give it a name, for example, img-bucket, and, most importantly, Read access to objects make it public - otherwise Telegram won't see our pictures. All other fields are left unchanged. We press the button Create bucket.

Building a Telegram bot in Yandex.Cloud

After that, a list of all buckets might look something like this (if this is your only bucket):

Building a Telegram bot in Yandex.Cloud

Now I propose to click on the name of the bucket, and inside it create a folder to organize the storage of pictures for different applications. For example, for a telegram bot Smart Thoughts i created a folder called tg-bot-smart-thoughts (Nothing, I will understand this cipher). Create one too.

Building a Telegram bot in Yandex.Cloud

Now you can click on the folder name, go into it and upload files:

Building a Telegram bot in Yandex.Cloud

And clicking on the file name - get it URL for use in our bot, and in general - anywhere (but, do not publish this URL unnecessarily, since traffic from object storage charged).

Building a Telegram bot in Yandex.Cloud

Here, in fact, that's all object storage. Now you will know what to do when you see the prompt to upload files there.

Webhook

Now we will install webhook β€” i.e. when the bot receives an update (for example, a message from the user), from the server Telegram in our Yandex function request will be sentrequest) with data. Here is a string that you can simply paste into the address field of the browser, and then refresh the page (this only needs to be done once): https://api.telegram.org/bot{bot_token}/setWebHook?url={webhook_url}
Just replace {bot_token} to the token we received from the father bot when creating our bot, and {webhook_url} - on URL our Yandex functions. Wait a minute! But RossKomCensorship prohibits providers in the Russian Federation to serve the address https://api.telegram.org. Yes, that's right. But you can think of something. After all, you can, for example, ask your grandmother about it in Ukraine, Israel or Canada - there are no β€œRussian censorships” there, and only God knows how people live without it. As a result, the request-response when installing the webhook should look like this:

Building a Telegram bot in Yandex.Cloud

Testing. Should be mirrored.

Building a Telegram bot in Yandex.Cloud

This is true. Our congratulations - now Yandex function has become Telegram-bot!

Smart Thoughts

And now we do Smart Thoughts. The code is open and and lies on GitHub. It's pretty well commented, and it's only a hundred lines long. Read it like an opera diva libretto!

Building a Telegram bot in Yandex.Cloud

Clone the project and install the dependencies:

git clone https://github.com/stmike/tg-bot-smart-thoughts.git
cd tg-bot-smart-thoughts
npm i

Make the changes you need to the file index.js (optional; you can not change anything). Create zip-archive, with a file index.js and folder node_modules inside, for example, called smart.zip.

Building a Telegram bot in Yandex.Cloud

Now go in the console to our Yandex functions, select the tab ZIP archive, press the button Select a fileand download our archive smart.zip. Finally, in the upper right corner, click the button Create Version.

Building a Telegram bot in Yandex.Cloud

In a few seconds, when the function is updated, we will test our bot again. Now he no longer β€œmirrors”, but delivers smart thoughts!

Building a Telegram bot in Yandex.Cloud

That's all for today. Other articles follow. If you are interested in reading this, subscribe to notifications of new articles. You can subscribe here or Telegram-channel IT Tutorial Zakhar, or Twitter @mikezaharov.

references

Code on GitHub
Yandex Cloud Functions
Yandex Object Storage
Bots: An introduction for developers
Telegram Bot API

Donuts

Building a Telegram bot in Yandex.Cloud

Source: habr.com

Add a comment