I created a telegram bot using Node.js

I created a telegram bot using Node.js

Table of contents

No heading

No headings in the article.

Automating tasks as a developer is a cool thing to do, yeah you have the super power so why shouldn't you do it?.

We'll be creating a Telegram Bot that sends random jokes to us using Node.js now!!, Are you ready?

Before moving to the code part let's set some basic things up, things like

  • Finding BotFather in Telegram app
  • Starting BotFather with the /start command

startbot.jpg

  • Creating a new bot with the /newbot command

newbot.jpg

  • Creating a name for your bot, I'll name mine "Joke bot"

  • Creating a unique username for your bot, I'll name mine "mukhtar_hashnode_bot"

mukhtar_hashnode_bot.jpg

The response above includes an API token that you can use to control your bot, it is advisable you store it safely

Yay, we are done with setting the basic things up, now let's continue.

I assume you have basic knowledge of setting up node.js server with express

The Dependencies we need are

  1. axios
  2. dotenv
  3. express
  4. nodemon

We'll be adding the Token Telegram gave us, Server URL which is where you will be hosting your server, I'm using render to host mine and the last one is the PORT number.

TELEGRAM_TOKEN=123456:THETELEGRAMTOKENYOUGOT_WHENYOUCREATEDUNIQUEUSERNAME
SERVER_URL=https://telegram-bot-cmxz.onrender.com/
PORT=5000

Now let's continue.

Our Basic declaration to create an express app.


require("dotenv").config()
const express = require('express')
const axios = require("axios")
const app = express()

We need to access our token and server URL in the .env file, the code below is meant for that.

const { TELEGRAM_TOKEN, SERVER_URL } = process.env

Now the next thing we want to do is inserting our Telegram API token into Telegram API URL this way.

const TELEGRAM_API = `https://api.telegram.org/bot${TELEGRAM_TOKEN}`

Now let's declare our URI, we'll be using webhook, you can check more about it here

const URI = `/webhook/${TELEGRAM_TOKEN}`

Now we want to create a webhook url

const WEBHOOK_URL = SERVER_URL+URI

To be able to process data sent in the request body we'll be adding this below

app.use(express.urlencoded({ 
    extended: false 
}))

app.use(express.json())

Now the next thing we want to do is create a function where we'll be sending a get request to the telegram API setting a webhook and using the webhook url this way, we'll log the response data to the console this is to be sure webhook is set

const init = async () => {
    const res = await axios.get(`${TELEGRAM_API}/setWebhook?url=${WEBHOOK_URL}`)
    console.log(res.data)
}

If webhook is set we should get this

{ ok: true, result: true, description: 'Webhook is already set' }

Now to the more interesting and main part, what we want our bot to do, well I want mine to tell you random chuck Norris joke.

I'll be getting the jokes from https://api.chucknorris.io/jokes/random

const joke_api = await axios.get(`https://api.chucknorris.io/jokes/random`)
const joke = joke_api.data.value

But before that we'll be sending a post request to the URI we defined above, we need to get the telegram chatID, username and then use axios to send message with telegram /sendMessage endpoint this way.

app.post(URI, async (req, res) =>{

    const chatId = req.body.message.chat.id
    const user = req.body.message.chat.username

    const joke_api = await axios.get(`https://api.chucknorris.io/jokes/random`)
    const joke = joke_api.data.value

    await axios.post(`${TELEGRAM_API}/sendMessage`, {
        chat_id: chatId,
        text: `hello ${user}, ${joke}`
    })
    return res.send()
})

And now we'll listen to the port and we're done.

app.listen(process.env.PORT || 5000, async () =>{
    console.log(`app is running on port`, process.env.PORT  || 5000);
    await init()
})

you can have fun with my bot here, the complete code can be found in my Github, To learn more about Telegram API you can check Here, I hope you enjoyed it, Follow me for more backend development tips.