Send Message BOT Telegram NodeJs

ilhamsabir

ilhamsabir

Posted on March 13, 2024

Send Message BOT Telegram NodeJs

Send Message BOT Telegram NodeJs

Intruduction

Create telegram bot to send message from NODEJS Apps.

Create BOT Telegram

  • Goto BotFather
  • Open it from mobile device or web.telegram.org
  • type
  \newbot
Enter fullscreen mode Exit fullscreen mode
  • Follow instruction
  • When completed youll get API Token, copy it to somewhere saved.

Test BOT

  • Open Postman/Insomnia or anything like that.
  • Create GET request sample.
    # HTTP request format
    # https://api.telegram.org/bot<token>/METHOD_NAME

    # our first method /getMe
    https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getMe
Enter fullscreen mode Exit fullscreen mode
  • Now you can see your user data

Building NodeJS

  • Init nodejs app
    # configure as needed
    npm init;

    # install dependencies
    npm i express axios body-parser --save;

    # create main file
    touch index.js;
Enter fullscreen mode Exit fullscreen mode
  • Create index.js
    // Dependencies
    const express = require('express');
    const app = express();
    const axios = require('axios');
    const bodyParser = require('body-parser');
    const port = 80;
    const url = 'https://api.telegram.org/bot';
    const apiToken = '{api-token-given-by-BotFather}';
    // Configurations
    app.use(bodyParser.json());
    // Endpoints
    app.post('/', (req, res) => {
        // console.log(req.body);
        const chatId = req.body.message.chat.id;
        const sentMessage = req.body.message.text;
        // Regex for hello
        if (sentMessage.match(/hello/gi)) {
            axios.post(`${url}${apiToken}/sendMessage`,
                {
                        chat_id: chatId,
                        text: 'hello back 👋'
                })
                .then((response) => {
                        res.status(200).send(response);
                }).catch((error) => {
                        res.send(error);
                });
        } else {
            // if no hello present, just respond with 200
            res.status(200).send({});
        }
    });
    // Listening
    app.listen(port, () => {
        console.log(`Listening on port ${port}`);
    });
Enter fullscreen mode Exit fullscreen mode
  • Try access route and it will send notif to your telegram

Reference

💖 💪 🙅 🚩
ilhamsabir
ilhamsabir

Posted on March 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related