Hi there, my name is Alex Nekrashenko; you can think of me as a software architect or a full-stack developer. But actually, this article isn’t about it. It’s about how I created my own Telegram bot for the first time. I wanna share with you how I chose the stack and why I decided to write my own telegram API library with NestJs.
Let’s start this story now, yet it will be updated consistently, as this article will consist of several parts. Here, I will try to explain the basics of the structure and architecture as well as some other important things
To clarify, the Telegram bot is just an API. Creating it is extremely simple. You just need to find the official Telegram bot with the funny name, BotFather, and set up your bot in it using the command.
After you’ve set your bot up, you will get a special key. Exactly this key is the one you will use in your future API, which will control all the conversations in bot chat.
Let’s begin with creating a skeleton for our future application, the base functionality for the standard commands.
To make it easier, I just copy/paste commands from the official website NestJs documentation, just install CLI and execute the command
Well, almost all the work is done! Now, take a look at my project map
It must be easy; you see two folders:
What commands and botUpdates are you asking? Well, I’ll try to be concise, this is what we can find on the official Telegram API documentation here https://core.telegram.org/bots/api#getupdates
As you can see, Telegram will be reacting to every event related to your bot, and then it will make you aware of it with this method. Generally, we get all the info from Telegram using this method.
Getting back to my services in the bot folder
If we have one method, getUpdates from telegram, that’s what I thought about: I will define the special event that I need and implement it, and that’s exactly what I did. I defined the event in botUpdates, and if it is consistent with the command that I also defined myself, then I direct it to the commands folder and make the implementation there.
What about the database? I thought that I would need at least two tables: users and channels. But then I started thinking about userState table.
If everything is clear with users and channels, what is userState. UserState is a special table that can store the state when the user performs some action that isn’t related to a specific event.
Most events look like this, as a bot commands list.
Some events, such as "add words", require the user to enter words.
How can we understand that there is a chain of one event when an event has started and finished? That’s why I use this table to track the user actions.