In this simple tutorial, we will explore creating a Telegram Bot using Node JS. We will Create a Telegram Bot that will send a random Chuck Norris Joke. By following along, you'll learn how to use Node.js, connect to APIs, and add some fun to your Telegram chats.
First and Foremost step, we need to create a Telegram bot in the telegram App. Follow the below steps to create the Telegram bot.
@BotFather
and open it. It is like the bot admin for the whole of Telegram./start
./newbot
and follow the on-screen instructions to create the bot.Next, let's set up our development environment.
mkdir chuck-norris-telegram-bot
npm init -y
Let’s install the necessary dependencies from npm
npm i node-telegram-bot-api dotenv axios
Let’s add the API key to the .env
file
TELEGRAM_BOT_API_KEY=<Your_API_Key>
We will be using ES6 modules to code the bot. So add the below line in package.json
{
// rest of the package.json
"type": "module" // Add this line to use ES6 modules in our code
// rest of the package.json scripts and dependencies
}
Create an index.js
file and copy the contents below
import dotenv from "dotenv";
import TelegramBot from "node-telegram-bot-api";
dotenv.config();
const TELEGRAM_BOT_API_KEY = process.env.TELEGRAM_BOT_API_KEY;
const telegramBot = new TelegramBot(TELEGRAM_BOT_API_KEY, { polling: true });
telegramBot.onText(/\/start/, (msg) => {
telegramBot.sendMessage(msg.chat.id, `Welcome ${msg.chat.first_name}`);
});
In the above code, we are loading the env keys from the .env
file using dotenv
library. Then we are creating an instance of Telegram Bot passing the api key.
The onText()
function of the telgram api takes in two arguments, where the first argument is a regular expression that matches the input command. The second argument is a callback function that executes when the regExp is matched.
Here we are just greeting the user once they click start in the bot.
Let’s test it. Start our bot running the below command
npm start
Now, Head over to Telegram and Open the Bot that we created and click start.
As expected, our bot responded with a Welcome message. Now Let’s move on to creating the bot command for getting the Jokes.
Now, let’s create a bot command that will be used by the users to send commands to the bot. To create a command, open the BotFather App in Telegram.
/mybot
command to the BotFather and Select your father in the button displayed.Edit Bot
→ Edit Commands
.
That’s it. The /joke
command is created. Now let’s move on to create the bot response for that command.
Open index.js
in vs code and add the below code to it.
telegramBot.onText(/\/joke/, async (mesg) => {
// To implement the functionality to fetch the Joke from the API
});
Whenever the user sends the /joke
command this function will be executed. Let’s move into implementing the functionality now.
Let’s create a separate file api.js
that will be used to fetch Jokes from the Chuck Norris API.
import axios from "axios";
export const getJoke = async () => {
try {
const response = await axios.get("https://api.chucknorris.io/jokes/random");
const data = response.data;
return data.value;
} catch (error) {
console.log(error);
return "No Jokes";
}
};
The getJoke()
function will fetch a random Joke by hitting the Chuck Norris API.
Let’s import this function in index.js
and use it as our bot response.
// Import it at the top
import { getJoke } from "./api.js";
// let's complete the bot response
telegramBot.onText(/\/joke/, async (msg) => {
const joke = await getJoke();
telegramBot.sendMessage(msg.chat.id, joke);
});
So, whenever the user sends the /joke
command, our bot will fetch a random Joke from the Chuck Norris API and send the response back to the user.
Note: We need to import the *getJoke*
from *./api.js*
(with extension) not just *./api*
. Else it will throw an error
Let’s test it. Open the Command Prompt and start the app by running the below command.
npm start
Now, open our bot and send the /joke
command.
Yes! As you can see, the bot responds with a funny(?) Chuck Norris joke.
That’s it. Our Bot is ready. Feel free to add more bot commands and play around. To summarize, In this tutorial, we learned how to create a telegram bot using Node.JS and also how to create bot commands and how to send bot responses back to the user. You can find the source code of this article in my GitHub.
Also published here.