visit
@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.mkdir chuck-norris-telegram-bot
npm init -y
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>
{
// 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.
npm start
/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("//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
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.