Create a Telegram Bot with Node.js
Tags: node, telegrambot, api, bot
Published: 2023-10-09 15:25:14

## Introduction

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.

## Prerequisites:

- You should have Node.JS installed in your system, preferably the LTS version.
- A Telegram account so you can create a Bot

## Creating the Telegram Bot:

First and Foremost step, we need to create a Telegram bot in the telegram App. Follow the below steps to create the Telegram bot.

- Open the Telegram App.
- Now Search for `@BotFather` and open it. It is like the bot admin for the whole of Telegram.
- If you are creating a bot for the first time, Click on `/start`.
- Next, click on `/newbot` and follow the on-screen instructions to create the bot.
- Once the bot has been created, copy the Bot API key and save it for later.

## Setting up the Bot in Node JS:

Next, let's set up our development environment.

```bash
mkdir chuck-norris-telegram-bot
npm init -y
```

Let’s install the necessary dependencies from npm

```bash
npm i node-telegram-bot-api dotenv axios
```

- node-telegram-bot-api - This provides all the necessary API functions to set up and run our telegram bot.
- dotenv - To read the .env file secret keys.
- axios - To make HTTP Rest API calls with the chuck norris jokes API.

## Coding the Bot:

Let’s add the API key to the `.env` file

```bash
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

```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

```javascript
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

```bash
npm start
```

Now, Head over to Telegram and Open the Bot that we created and click start.

![Telegram Bot Intro](https://i.imgur.com/E1jHONd.png)

As expected, our bot responded with a Welcome message. Now Let’s move on to creating the bot command for getting the Jokes.

## Creating the Bot Command:

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.

- Send `/mybot` command to the BotFather and Select your father in the button displayed.
- Then Click on `Edit Bot` → `Edit Commands`.
- Create the following command as shown below and send it to the bot.
  joke - Send a random Chuck Norris Joke

That’s it. The `/joke` command is created. Now let’s move on to create the bot response for that command.

## Creating the Bot Response:

Open `index.js` in vs code and add the below code to it.

```javascript
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.

```javascript
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.

```javascript
// 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.

```bash
npm start
```

Now, open our bot and send the `/joke` command.

![Telegram bot response joke](https://i.imgur.com/Xi0PXpu.png)

Yes! As you can see, the bot responds with a funny(?) Chuck Norris joke.

## Conclusion:

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](https://github.com/nirmal1064/chuck-norris-telegram-bot).