Create Your Own Telegram Bot and Send and Receive Messages via NodeJS

Create Your Own Telegram Bot and Send and Receive Messages via NodeJS

An Introduction to Bots in Telegram

Cover Photo by Lenin Estrada on Unsplash

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands, and inline requests. Bots are capable of building anything you require them. From getting customized news to integrating with other services such as IMDB, GIF, etc., bots can help you with a variety of things. If you don't find a bot that does your job, you can create your own bot. You can even accept payment through your bots.

This article will help you with the basics of creating a bot and sending your first message to and from the bot.

Let's get started!

Creating Your Bot

Step 1 — Log in to telegram

First of all, you have to sign in to your telegram account. Use the Telegram app on your phone and sign in to Telegram. Also, sign in to Telegram Web as well, as it will be convenient for us during the development process.

Step 2 — Create your bot

Once you are signed in both your mobile and PC, search for a bot called BotFather.

Make sure you follow the below steps on your mobile as your PC would give you errors. You can either click on this link through your phone or use your mobile and search for '@BotFather'. Click on it, and it will open a chat screen with the bot.

image.png Screenshot of Telegram App by author

At the bottom of the chat screen, you will have a button that says either 'Start' or 'Restart'. Click on that button.

Now you can go back to your PC and use Telegram Web. Inside the conversion with BotFather, type '/newbot'. Answer the questions, and then you will have successfully set up your first telegram bot.

Once you have created your bot, BotFather would give you a token to access the HTTP API. Make sure you have this token stored safely. We will need it when creating our NodeJS application.

Communicating with your bot

Step 3— Create your NodeJS project

Create a folder that would contain your project and open that folder in the terminal. Type npm init and answer the questions to create your package.json file. Once you complete that step, you have to install the library for telegram.

There are many telegram libraries available for many frameworks. There are several available for Node. I choose to install Node-Telegram-bot. Here is its Github repo. You can check out all the libraries here.

Step 4— Install and import your library

Run this command to install the node telegram bot library.

npm install --save node-telegram-bot-api

After you install the library, create an index.js file and import your library into it.

const TelegramBot = require('node-telegram-bot-api');

Step 5— Add your telegram bot token

Now you have to add your telegram bot token we received when creating your bot in step 2.

// replace the value below with the Telegram token you receive from
// @BotFather
const token = "YOUR_TELEGRAM_BOT_TOKEN";

Step 6 — Create your bot instance

Now we create our bot with polling. If we disable polling, our app will not be listening for any inputs from our bot. But we do not want that; we need our app to listen and respond to inputs from the user. Hence we turn on polling.

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, { polling: true });

Step 7 — Listen for user input/messages

Now we must make sure our app can listen to user inputs. This is very easy as it requires a few lines of code.

bot.on("message", (msg) => {
  console.log(msg);
  //type other code here
});

Now run your code by typing node index in your terminal. As the project is running, open Telegram Web and go to your conversation with BotFather. There you will be able to find a message "Done! Congratulations on your new bot. You will find it at t.me/<bot_name>".

Click on that link and open a conversation with your bot. If it the first time you are opening that bot, you will see a 'Start' button at the bottom. Click on that to start your conversation with your bot. If you have already opened the conversation, simply type any text and send it.

If you open your terminal, you will see a log of the message that the user sent. It will contain many properties such as message_id, from, chat, text, date, etc. You might have optional properties such as audio, document, photo, depending on the type of message received. The chat property is very important as it contains the chat id of the conversation. It is important because when you send a message, you should know to which person you are sending it. This is uniquely identified by the chat id. You can access the chat id via msg.chat.id.

Step 8 — Sending a text message to the user

We are able to listen to user inputs by now. Now we are left with the last objective of this tutorial — send messages. This is also quite simple as it requires a few lines of code.

bot.on("message", (msg) => {
  console.log(msg);
  //type other code here**

  const chatId = msg.chat.id;

  const text = msg.text;

  bot.sendMessage(chatId, "Received your message: " + text);
});

As you can see above, we are taking the text sent by the user and sending it back to themselves as a message. Here you must note that the chatId constant is actually the chat id of the message we spoke about earlier. Run the index.js file again.

Now, if you type something from your bot in Telegram, you should receive a message from the bot saying Received your message: Sample Message.

Congratulations!! You have built your first telegram bot and communicated with a user. I have an additional feature in store for you. We are going to send an image to the user at the user request.

Bonus Step — Sending photos to the user

Let's edit the above code to look like this.

bot.on("message", (msg) => {
  const chatId = msg.chat.id;

  console.log(msg);

  const text = msg.text;

  if (text.includes("picture") || text.includes("image")) {
    const imgUrl = "https://picsum.photos/500/700";

    bot.sendPhoto(chatId, imgUrl);
  } else {
    bot.sendMessage(chatId, "Received your message:" + text);
  }
});

If you look at the above code, we are checking whether the text message sent by the user includes the words' picture' or 'image'. If it does, we send the user a random image; else, we send them the text back as we did it before. You must note that the chatId is important even for this step. If you run the above code, you will receive a photo when you send a message that contains the words' picture' or 'image'.

Here is a gist of the final code.

Well Done!! You have learnt quite a few things in this article.

  • What are telegram bots

  • How to create your own simple bot

  • How to listen to messages from your bot

  • How to send messages to your bot

  • Bonus: How to send photos to your bot

You can refer to the below references to know more about telegram bots.

Happy Coding!

References