How to create a simple telegram chatbot with Node.js

Hi, I'm Courage and I'd show you how to create a simple chatbot on Telegram.

With the help of telegram, we can create simple to complicated chatbots which help individuals or businesses in different ways. An example would be a chatbot that responds to users on a website with automated responses that help save time and reduce the workload on staff.

Basically, every telegram bot needs a bot-token which is responsible for authenticating the bot admin. You can simply generate one by;

Step 1: Go to the telegram, and search bot father. This is the bot that helps generate a token for every future telegram bot.

Step 2: When the Bot father is open, type /start and click on /newbot.

Step 3: Now type in a unique bot name.

Step 4: The system generates a token for you which you can simply copy from.

We are now done with getting our bot token.

Now we can move over to creating our Node app.

Step 1: Open Visual Studio Code on your laptop and create a folder named "TextBot" or any other name you'd like to call it.

Step 2: Run npm init to create a package.json file.

npm init

Step 3: Install dependencies

npm install node-telegram-bot-api

Step 4: Normally, we'd install the dotenv dependency to help mask our token but we'd skip that. Create a bot.js file and input the below;

var token = 'Enter the token generated from Botfather';

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

const bot = new TelegramBot(token, {polling: true});

// Matches "/echo [whatever]"
bot.onText(/\/echo(.+)/, (msg, match) => {

// The 'msg' is the received Message from Telegram
// 'Match' is the result of executing the regexp
// above on the text content of the message

const chatId = msg.chat.id;

// The captured message
const resp = match[1];

// sends back the exact message to the chat
bot.sendMessage(chatId,resp);

});

Step 5: Type the below code to run your application and test.

node bot.js

And that's it! We've successfully created a simple chatbot.

It's my first time writing on Hashnode and I'd love your feedback on how to improve and if there are any corrections to be made.

Thanks for reading. Until next time.