簡體   English   中英

如何使用 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

任何建議或幫助表示贊賞,謝謝!

為此,您需要一個數據庫將用戶設置為“已訂閱”或“未訂閱”。

我會給你一個商店包的例子你需要以下包:

  • 店鋪
  • 節點電報機器人 api
store 包為本地存儲,應用重啟時可能會重置
下面給出的代碼可能會給你一個想法,它只是使你能夠創建訂閱和取消訂閱的功能,你可以使用循環方法向“數組”中的用戶發送消息
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!")
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM