簡體   English   中英

使用node-telegram-bot-api順序執行功能

[英]Sequential execution of functions with node-telegram-bot-api

當我嘗試發送有關我的年齡的信息時,它詢問的是我的Gen,然后是我的身高。 如果我要寫我的身高,那是我的年齡是我的2倍和1倍。 如何使它像這樣工作:它應該問一些問題。 然后,如果我回答了某件事,但回答不好,則應該再次詢問該問題;如果回答是好的,則應使用相同的算法詢問新問題。

let weight, height, age, dailyNorm, A, proteine, fat, glucide, gen;
let low=1.2, small=1.4, middle=1.6, big=1.7;


const TelegramBot = require('node-telegram-bot-api');
const token = '734206894:... '; 
const bot = new TelegramBot(token, {polling: true, 
                                       onlyFirstMatch:true, }); 

bot.onText(/\/start/, (msg) => { 
    bot.sendMessage(msg.chat.id,"Bot activated🤖" , { "reply_markup": { 
        "keyboard":[["Calculate🍎" ], ["Report🐞"]] 
    }});
    console.log (msg.text);
});

function dataGen(a){
    bot.sendMessage(a.chat.id,"Your gen(👦-m,👧-f)?"); console.log (1)
    bot.on("message", (msg) => { 
     if (msg.text=="m"){ gen="m"; dataAge(msg);}  
     else if (msg.text=="f"){ gen="f"; dataAge(msg);} 
     else { dataGen(msg);} 
     console.log (2)
    });
} 

function dataAge(b){
    bot.sendMessage(b.chat.id,"Your age👶?");

發送順序問題:

var answerCallbacks = {};

bot.on('message', function (message) {
    var callback = answerCallbacks[message.chat.id];
    if (callback) {
        delete answerCallbacks[message.chat.id];
        return callback(message);
    }
});

bot.onText(/questions/, function (message,match) {
    bot.sendMessage(message.chat.id, "Enter your name").then(function () {
        answerCallbacks[message.chat.id] = function (answer) {
            var name = answer.text;
            bot.sendMessage(message.chat.id, "Enter your address").then(function () {
                answerCallbacks[message.chat.id] = function (answer) {
                    var address = answer.text;
                    bot.sendMessage(message.chat.id, "Enter your phone ").then(function () {
                        answerCallbacks[message.chat.id] = function (answer) {
                            var phone = answer.text;
                            bot.sendMessage(message.chat.id, name + address + phone + " saved!");
                        }
                    });
                }
            });
        }
    });
});

或作為功能:

const answerCallbacks = {};

bot.on("message", function(msg) {
  const callback = answerCallbacks[msg.chat.id];
  if (callback) {
    delete answerCallbacks[msg.chat.id];
    return callback(msg);
  }
});

const askQuestion = async (chatId, question) => {
  await bot.sendMessage(chatId, question);
  return new Promise(fullfill => {
    answerCallbacks[chatId] = msg => {
      if (msg.text[0] !== "/") {
        fullfill(msg);
      }
    };
  });
};

然后,您可以簡單地使用:

const answer = await askQuestion(chatId, 'Tell me something good!')

暫無
暫無

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

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