Search code examples
node.jstelegramwebhookstelebot

How to send message to a telegram bot using telebot api or telegram api


I currently have created a bot in telegram and am using it to perform some action whenever a msg is sent to the bot uisng the telebot api. I now am creating a new app where my back end gets the data from a webhook and I want to directly send that data to the bot after which the bot will perform the pre defined task on it. Is it possible ?. How can I do it?. Links to any guides would also be helpful.

so far I have only ever replied to msg received to the bot direct from the telebot api an have never have sent a msg to the bot from my back end. From what I read you need to get the id of user you want to send msg to how can I get the id for a bot and send data to that id directly.


Solution

  • import express from 'express';
    import TeleBot from 'telebot';
    
    const bot = new TeleBot(process.env.BOT_TOKEN);
    
    bot.on('/start', async (msg) => {
      const chatId = msg.chat.id;
      await bot.sendMessage(chatId, 'Hello world!');
    });
    
    const app = express();
    
    app.use(express.json());
    
    app.post('/webhook', (req, res) => {
      const chatId = process.env.BOT_CHAT_ID;
      const message = req.body.message;
    
      bot.sendMessage(chatId, message);
    
      res.send('Message sent to bot!');
    });
    
    const port = process.env.PORT || 3000;
    
    app.listen(port, () => {
      console.log(`Server listening on port ${port}`);
    });
    

    does this code help?