Начало работы
![]()
В первую очередь нужно зарегистрировать бота. Сделать это можно в приложении Telegram через BotFather.
Нажмите Start в чате и просмотрите доступные варианты. Вам понадобится выбрать название для бота и имя пользователя, а затем можно сохранять ключ.
После этого бот начнет отображаться в поиске Telegram — для этого просто введите @<bot-username> . Однако пока никаких действий выполнять он не будет.
Переходим к коду. Для работы с API Telegram воспользуемся пакетом NPM. Устанавливаем его с помощью команды yarn add node-telegram-bot-api .
Пакет готов к работе. Добавляем токен в переменную:
Теперь можно приступать к настройке бота. Ниже показан простой пример:
onText позволяет реагировать на сообщения, соответствующие регулярным выражениям. В этом варианте /\/echo (.+)/ означает, что вам нужно написать /echo , а следом за ним какой-либо текст.
Переменная chatId представляет ID пользователя, который используется для отправки сообщения. Чтобы бот мог самостоятельно выполнять эту функцию, ID должны где-то храниться.
bot.sendMessage применятся для отправки сообщений. Строка resp посылается после команды echo . Бот отправляет обратно то, что он получает.
Запускаем node app.js , открываем чат с ботом и отправляем ему следующее.
Автоматическая отправка сообщений
Как было сказано выше, чтобы отправлять пользователям сообщения, понадобится chatId , который нужно где-то хранить. В приложениях для этого стоит выбрать энергонезависимые хранилища, такие как MySQL, MongoDB и любые другие базы данных.
В этом примере мы будем хранить идентификаторы в массиве. Пользователь может зарегистрироваться в боте с помощью /register . После этого он будет получать сообщения.
Бот отправляет сообщение каждому пользователю один раз в секунду. Для этого достаточно пройтись по массиву с циклом for .
После отправки /register боту мы начинаем получать много спама.
Реакция на все сообщения
bot.onText позволяет реагировать на сообщения, соответствующие регулярному выражению. Чтобы обрабатывать любой входящий текст, нужно воспользоваться bot.on("message") — он запускается каждый раз, когда кто-то отправляет сообщение.
Вот простой пример. Бот реагирует на каждое сообщение, но отвечает, только когда пользователь присылает текст “dog”.
Отправка опросов
В Telegram можно обменивать не только стикерами, видео и текстом, но и опросами. Создавать их очень просто.
Сразу после ID мы передаем вопрос, а затем идет массив возможных вариантов ответов. Вы можете добавить больше опций по желанию.
Building your First Telegram Bot using Node.js and Telegraf
What are telegram bots? Bots are third-party application accounts that run inside the Telegram application. Users can interact with bots by sending them messages, commands, and inline requests. You control your bots using HTTPS requests from the Telegram Bot API.
Telegram bots have made it easy to automate tasks in telegram channels and groups. You can even build your own telegram bot to curate news or monitor cryptocurrencies trend for you.
In this tutorial, you will learn how to build telegram bots using Node.js runtime environment and Telegraf library from scratch.
This will act as an introduction to the Telegram bot environment that will enable you to build weather bot, vendor bots, e-commerce bot, or even dictionary bot. This tutorial will be as beginner-friendly as possible.
Prerequisite
Before you begin this guide you’ll need the following:
-
installed.
- npm installed. installed.
- Basic knowledge of using the CLI.
- A Telegram account .
Setting up your bot
First, go to the telegram search bar and search @botfather (this is a special telegram bot that controls all others). We are going to use this to get a token for our new bot.
There are several commands associated with @botfather, we are going to start with /newbot then provide the desired name for the bot. The name must always end with ‘bot’. Now that we have the token we can write the code.
The coding
Let’s first create a folder for our new project, i.e: myfirstbot. Open the command line and navigate to the folder. Initialize the project by running the following commands to install telegraf:
Create a javascript file, app.js
Let’s write a simple script that will welcome us every time we start the bot.
To add more functionality let’s write code that shows you images of animals when you click inline keyboard buttons. Create a res folder and add images into it.
We have seen how to use inline keyboard, let’s now try to use the one time reply keyboard feature to share our location or phone number with the bot.
Note: Sharing location feature is only available for telegram mobile application.
Finally, write the following code at the end to launch the bot.
Using the bot
We have successfully written three blocks of codes, one that welcomes you when you start the bot.
One that sends you images when you click inline keyboard buttons and finally one that allows the user share their phone number or location when they click reply keyboard button.
Run the bot in the terminal and then go to the telegram search bar and search the name of your bot.
Here are the results from telegram.
Starting the bot

Requesting for a dog photo

Requesting for a cat photo

Requesting phone number

Requesting location

Kindly check the source code in my GitHub repository here.
Summary
In this article we have gone through how to get your telegram bot token, setting up your environment and writing a simple bot for displaying images of animals using the inline keyboard feature and also share your location and phone number using reply keyboard feature.
Follow this series of articles over the coming days as we will code bots that have more functionality.
Простой Telegram-бот на JavaScript за 10 минут

Тарас Голомозый, fullstack web-разработчик и преподаватель в школе программирования Elbrus Bootcamp, написал инструкцию по созданию простого бота на JavaScript с возможностью расширения функционала. В базовом варианте его задача — показывать текущую погоду по геолокации пользователя.
Пару слов об уровне знаний, на который рассчитан этот текст. Для создания бота достаточно иметь базовое представления о JavaScript, а также знать, как работает API. Перед началом работы нужно установить библиотеку telegraf.js, которая работает на базе официального API Telegram, и библиотеку для выполнения HTTP-запросов (например, axios).
Шаг первый: базовый функционал
Откроем редактор кода и инициализируем проект через терминал с помощью команды npm -y. После этого в проекте появится файл package.json. Теперь мы можем добавить все необходимые библиотеки командой npm i, после которой через пробел прописываются названия необходимых нам библиотек. Все названия можно посмотреть в документации: в этом примере это будут telegraf и axios.
Стоит отметить, что API погоды отдельно устанавливать не нужно — она работает по архитектуре клиент-сервер, что позволяет просто отправлять запросы и получать ответы.
Пока устанавливаются библиотеки, можно прочитать документацию к ним. У telegraf.js есть несколько примеров готового бота. Можно взять первый пример и посмотреть, как он работает.
Для этого создадим новый файл с именем bot.js и добавим в него следующий код:
В package.json пропишем стартовый скрипт для этого файла. Для этого в разделе scripts добавим новый пункт со следующим содержанием:
Если мы запустим проект в терминале командой npm start, то увидим сообщение «Bot token is required». Получить токен можно через Telegram BotFather — официального бота мессенджера, который создает другие боты и управляет ими. В интерфейсе выбираем /start, затем — /newbot, и следом задаем имя и адрес. В этой инструкции это будет elbrusbootcampweatherbot.
После этого BotFather пришлет сообщение с токеном и ссылкой на бот. Копируем токен и вставляем его в третью строчку примера:
Для проверки находим бота в поиске в Telegram по имени. Теперь бот запускается, но пока не выполняет никаких полезных функций. Чтобы разобраться, что именно нужно добавить, построчно разберем код из примера.
Первая строка отвечает за подключение библиотеки telegraf, которая непосредственно взаимодействует с API Telegram и позволяет нам использовать определенные методы для работы с ботом. В следующей строке создаем нового бота и указываем ключ доступа к нему.
Далее указано, как бот будет реагировать на различные команды: при нажатии /start он отправит сообщение welcome, при отправке стрикера — эмодзи и так далее. Последние две строчки нужны для того, чтобы выполнение ботом команд правильно завершалось в облачных сервисах.
Другие методы кроме /start нам не понадобятся, поэтому их можно смело удалить:
Добавим собственные методы: при отправке геолокации бот отвечает актуальном прогнозом погоды для этой территории. Первым делом напишем обработчик, который будет принимать сообщение от пользователя и выводить его в консоль.
Теперь при отправке боту геолокации в консоли мы увидим объект location, в котором содержится широта и долгота. Добавим проверку: если в сообщении пользователя содержится объект location, данные из него отправляются на сервер через API агрегатора прогнозов погоды.
Шаг второй: подключаем API
Как и в предыдущем случае, используем пример из официальной документации OpenWeather. Нам нужно обратиться на специальный адрес и передать туда широту, долготу и API-ключ. В ответ мы получим текущую погоду.
Вставим пример в код, используя результат проверки ctx.message.location с указанием широты и долготы:
API-ключ можно создать в личном кабинете на сайте OpenWeather. Ключ указывается как параметр appid.
Следующим шагом нужно обратиться по адресу, предоставленному OpenWeather, и получить данные. Для этого используем библиотеку axios. Функция для подключения библиотеки указана в ее официальной документации и выглядит следующим образом:
Поскольку все операции со сторонним сервером выполняются асинхронно, добавим async и await в метод bot.on:
Теперь при отправке боту геолокации в консоли мы увидим информацию о погоде в текущем месте расположения пользователя. Остается только сформировать сообщение, которое бот отправит пользователю в качестве ответа. В тексте укажем название района и температуру в градусах Цельсия:
Заключение
На этом все: итоговый код проекта можно найти в репозитории на GitHub.
При желании можно указать дополнительные параметры, которые бот будет выводить в сообщении. Например, облачно на улице или солнечно, есть осадки или нет и другие. Также к боту можно подключить переводчика и переводить состояние погоды на русский язык.
How to create a Telegram Bot using NodeJS
In this tutorial, we will create a simple bot that will send a random joke from a list of jokes and a random cat image to your chat.
Prerequisites
You should have NodeJS installed for this tutorial. If you don’t have it, you can download it from here.
Creating the bot
First, you need to create a bot. Telegram make it really easy, and all you need to do is to talk to the BotFather. Send a message, and then follow the instructions. You can find the BotFather here.
When you open it, click on the start button, and then send the /newbot command. Follow the instructions, and you will get a token for your bot. Save it, you will need it later.
Creating the NodeJS project
Create a new folder for your project, and open it in the terminal.
To create a NodeJS project, you can use the npm init command. This will create a package.json file, that will contain all the information about your project. You can also use the -y flag to skip the questions.
Exit fullscreen mode
Installing the dependencies
In this project we will use the Telegraf library to create the bot. To install it, you can use the npm install command.
Exit fullscreen mode
This will install the library and all the dependencies.
There are other libraries that you can use to create a bot, but I prefer Telegraf because it is really easy to use.
We also will use the folowing libraries:
- dotenv to load the environment variables
- axios: to make HTTP requests
- express: to create the server
We can install all of them using the npm install command.
Exit fullscreen mode
If you do not know any of those libraries, that is okay and we are going very light on them. You can read more about them in the documentation.
Creating the server
First, we need to create a server to run our bot. We will use the express library to create it.
In the root of your project, create a new file called index.js and add the following code:
Exit fullscreen mode
This will create a server that will listen on port 3000. You can change it if you want.
To run the server, you can use the node command.
Exit fullscreen mode
Or you can use the nodemon library to run it. This will restart the server every time you make a change.
Exit fullscreen mode
If you open your browser and go to http://localhost:3000 , you should see the Hello World! message. If you don’t, check the console for errors.
This endpoint will be used only for this test, so you can remove it later.
Creating the bot
At the root of your project, create a new file called .env and add the following
Exit fullscreen mode
Add your token that you got from BotFather.
Import the dotenv library and Telegraf at the top of your index.js .
Exit fullscreen mode
Then, create a new instance of the class, passing the token as a parameter.
Exit fullscreen mode
This part can be a bit confusing, so let’s break it down.
Ngrok
We need to create a Webhook to receive the messages from Telegram.
First, install Ngrok. You can find the instructions here.
Then, run it with the following command:
Exit fullscreen mode
This will create a tunnel to your local server. It should be running on the same port that your node server is running. You should see something like this on the console:
Copy the URL that is in the Forwarding section. On the index create a const called WEBHOOK_URL and add the URL.
Exit fullscreen mode
Setting the Webhook
Telegraf does have a method to set the Webhook, but I found it easier to set it using a request. So, we will use the setWebhook method from Telegram API.
To use it, first you should create const with the link to the API, token and URL of the Webhook.
Import the axios library at the top of your index.js .
Exit fullscreen mode
Create a const called TELEGRAM_API and add the following code:
Exit fullscreen mode
And create a function to set the Webhook that makes a post to the setWebhook endpoint.
Exit fullscreen mode
Call the function to set the Webhook inside the app.listen function.
Exit fullscreen mode
This function will make a POST request to the API, passing the URL of the Webhook. If everything goes well, you should see the following message on the console:
Exit fullscreen mode
Starting the bot
To start the bot, you can use the bot.launch method.
Exit fullscreen mode
This will start the bot and listen for messages.
Your index.js should look like this:
Exit fullscreen mode
Sending a message
We can set a command that when you type /start the bot will send a message.
Exit fullscreen mode
If you go to Telegram and type /start , you should see the message.
Random Joke
To send a random joke, we will use the Official Joke API. It is a free API that returns a random joke. To use it, we need to make a GET request to the API and get the joke from the response.
Exit fullscreen mode
If you go to Telegram and type /joke , you should see a random joke.
Sending a photo
To send a photo, we will use the Cat API. It is a free API that returns a random cat image. To use it, we need to make a GET request to the API and get the image from the response.
Exit fullscreen mode
Same trick, if you send a message to your bot with /cat , you should see a random cat image.
Conclusion
Congratulations! You have created your first Telegram bot.
You can find the code on GitHub.