Earlier, we saw What is a Chatbot and how it works, in that we understood the different types of chatbots like,
- Conversational Chatbots
- AI-powered Chatbots
- Task-Oriented Chatbots
And we also came to know the various platforms that support custom Chatbots. From that, we see a couple of examples of how to create a chatbot for Telegram using Node JS in this article and the SDKs used to develop the same.
Register a bot on the Telegram
- Search for 'BotFather' (bot) in Telegram and type.
/start
-
'BotFather' gives all the options that are available and related to the Telegram bots.
-
The next step is to register a new bot by using the code.
/newbot
-
'BotFather' asks us to name the new bot.
-
I am going to name it as EchoBot; once named, the bot will ask for a username with the 'bot' at the end of it.
-
Alright, I named it as SampleEcho_Bot, and if the username is available, we will get a congratulations message and TOKEN to authorize the chatbot you are creating (otherwise, try with another username).
Please make sure to keep the TOKEN safe, as this can be used for any bot authorization and is prone to attacks.
Create a Node JS project for programming this chatbot
Assuming you have installed the NodeJS runtime environment from --> https://nodejs.org/
-
Initialize a project using the npm command in the right directory.
npm init
-
Install the following packages to run the telegram bot a. node-telegram-bot-api (for accessing the Telegram REST API) b. dotenv (for accessing the token key from the environment variable).
npm i node-telegram-bot-api dotenv
-
Go to 'package.json' under the 'scripts' and add a new script tag.
“dev” : “node index.js”
-
Create a new file called '.env'
-
Add the following token key which you received from the Telegram bot registration.
TOKEN=xxxx
-
Create a new .js file and name it 'index.js'
-
Add the following piece of code
require('dotenv').config()
const {TOKEN} = process.env
const telegramBot = require('node-telegram-bot-api')
const bot = new telegramBot(TOKEN, {polling:true})
bot.on('message',(message) => {
let chat_id = message.from.id;
bot.sendMessage(chat_id,message.text)
})
Now, the coding part is done. Time to run the program.
-
Run the program with the command.
npm run dev
-
Once the program started, go to Telegram. Either ask the 'BotFather' about it.
/mybots
Or simply search in Telegram for the username you have created while registering; in my case, I search for.
@SampleEcho_Bot
Start the conversation using.
/start
And since this is an echo bot, all the messages you enter are echoed by the chatbot.
While this chatbot is a simple echo bot, you can create additional functionalities like weather bots, currency converters, simple calculators, FAQs, and so on.
If you are interested in a more specific solution in this regard, please leave a comment below.
Please see this is a follow-up from the series "Chatbots"
- https://www.c-sharpcorner.com/article/what-is-a-chatbot-and-how-does-it-work/