如何使用 Node.js node-telegram-bot-api 从电报机器人订阅和取消订阅用户?

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

我正在编写一个程序,使用 Node.js 和 node-telegram-bot-api 模块开发电报聊天机器人。我想设置命令,以便在收到/取消订阅时,用户应该从机器人中取消订阅。我阅读了该模块的 github 文档,但找不到实现此目的的方法。 https://github.com/yagop/node-telegram-bot-api/blob/master/doc/api.md

在此文档中,有一个 deleteChat 方法可用,但我不确定它是否适用于该模块。 https://core.telegram.org/methods#working-with-chatssupergroupschannels

感谢任何建议或帮助,谢谢!

您需要一个数据库来将用户设置为 'subscribed' 或 'unsubscribed'。

我给你举个例子 store package 您将需要以下软件包:

  • 店铺
  • node-telegram-bot-api
store package is local storage, may reset when the app restarts
下面给出的代码可能会给你一个想法,它只是让你创建订阅和取消订阅的功能,你可以使用循环方法向 '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!")
})