首页 > 解决方案 > 如果我使用 node-telegram-bot-api 创建一个电报机器人对象,为什么对话流机器人停止在电报中响应?

问题描述

我已经构建了一个带有电报集成的对话流聊天机器人,我需要获取用户在电报聊天中发送的图像的路径。据我所知,dialogflow bot 不侦听图像,因此我使用电报 bot 对象来轮询消息以获取图像,但这样,即使在电报 bot 的轮询停止后,dialogflow bot 也会停止响应。两个机器人之间存在一些冲突。“复苏”对话流机器人的唯一方法是在对话流 UI 中手动重新启动电报集成。有一种方法可以解决两个机器人之间的冲突,以便在电报机器人获取图像后对话流机器人继续响应?这是我写的代码:

const TG = require('node-telegram-bot-api');

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });

function takeImagePath() {
    agent.add(`send an image/photo`);   // work
    const token = 'my telegram bot token';
    let telegramBot = new TG(token, {polling: true});
    agent.add(`tg bot created`);  // work

    telegramBot.on('message',  async function (msg) {
        const chatId = msg.chat.id;
        agent.add('bot dialogflow in the listener');   // don't work

        if (msg.photo) {
            let ImgID = msg.photo[msg.photo.length - 1].file_id;
            let imgPath = "";

            if (ImgID) {
                telegramBot.getFile(ImgID).then((fileObject) => {
                    imgPath = fileObject.file_path;
                }).then(() => telegramBot.sendMessage(chatId, 'image taken'))   //work
                  .catch(error => console.log("error: " + error.message));
            }
        }
        else { await telegramBot.sendMessage(chatId, "it's not an image, telegram bot shutting down");   //work
               await telegramBot.stopPolling();
               agent.add("bot dialogflow active");   // don't work
        }
    });

}

let intentMap = new Map();
intentMap.set('Image intent', takeImagePath);
agent.handleRequest(intentMap);
});

标签: node.jstelegram-botdialogflow-es-fulfillment

解决方案


解决了。问题在于 webhook 和 polling 是两种相互排斥的获取消息的方法。因此,虽然 dialogflow-telegram bot 使用 webhook,但我创建的电报 bot 对象使用 let telegramBot = new TG(token, {polling: true}); 自动删除 webhook 的轮询。要解决此问题,必须在停止轮询后重新设置 webhook:await bot.stopPolling(); bot.setWebHook("your webhook url").then(r => console.log("webhook response: "+r)).catch(err => console.log("webhook error: "+err.message));

您可以在此处找到您的 dialogflow-telegram 机器人正在使用的 webhook url:

https://api.telegram.org/botYourTelegramBotToken/getWebhookInfo

希望它可以帮助某人。


推荐阅读