node.jstelegramtelegram-botnode-telegram-bot-api

How to subscribe and unsubscribe a user from a telegram bot using Node.js node-telegram-bot-api?


I'm writing a program to develop a telegram chatbot using Node.js and node-telegram-bot-api module. I want to set command such that when received /unsubscribe the user should be unsubscribed from the bot. I read the github document for the module but couldn't find a method to achieve this. https://github.com/yagop/node-telegram-bot-api/blob/master/doc/api.md

In this doc, there's a method deleteChat available, but I'm not sure it will work with the module. https://core.telegram.org/methods#working-with-chatssupergroupschannels

Any advice or help is appreciated, Thank you!


Solution

  • You'd need a database to set user as 'subscribed' or 'unsubscribed' for that.

    I'll give you an example with store package You'll need the following packages:

    store package is local storage, may reset when the app restarts
    The code given below may give you an idea, it just enables you to create the functionality of Subscribe and Unsubscribe, you may use loop methods to send news to users in 'array'
    const TelegramBot = require('node-telegram-bot-api');
    
    // replace the value below with the Telegram token you receive from @BotFather
    const token = 'YOUR_TELEGRAM_BOT_TOKEN';
    var store = require('store')
    var subscribed_users = store.get('subscribed')
    // Create a bot that uses 'polling' to fetch new updates
    const bot = new TelegramBot(token, {polling: true});
    
    // Matches "/echo [whatever]"
    bot.onText('/start', (msg) => {
      // 'msg' is the received Message from Telegram
    const chatId = msg.chat.id;
      bot.sendMessage(chatId, 'Welcome!\nUser /subscribe to subscribe to newsletter or /unsubscribe to unsubscribe to news letter');
    });
    bot.onText('/subscribe', (msg) => {
      if(!susbcribed_users){
      var subscribed_users = []
    }
      const chatId = msg.chat.id;
      //retrive subscribed users array data
    if(subscribed_users.includes(msg.chat.id)){
        bot.sendMessage(chatId, "You're already subscribed to newsletter!")
        return
    }
    var new_data = subscribed_users.push(msg.chat.id)
    store.set('subscribed', new_data)
      bot.sendMessage(chatId, "You're subscribed to newsletter!")
     
    })
    
    bot.inText('/unsubscribe', (msg) => {
      const chatId = msg.chat.id;
      if(!subscribed_users.includes(msg.chat.id)){
        bot.sendMessage(chatId, "You're not subscribed to newsletter!")
        return
    }
      const newArr = arr.filter(object => {
      return object !== msg.chat.id;
    });
    store.set('subscribed', newArr)
    bot.sendMessage(chatId, "You're subscribed to newsletter!")
    })