在Facebook Messenger机器人中保存/跟踪状态的正确方法是什么?

Pir*_*App 10 bots chatbot facebook-chatbot

如果我的机器人提出不同的问题,如果用户回答了每个问题,我如何找出哪个答案与哪个问题相关.有一个称为元数据的字段,您可以将其附加到sendTextMessage API,但是当用户响应时,此元数据将以未定义的形式出现.你们是否使用任何节点缓存来跟踪状态或FSM,如machina.js?我怎样才能最好地弄清楚我们目前陷入的对话?

Dan*_*van 10

当您的应用收到消息时,没有与之关联的有效负载或元数据.这与可以具有有效载荷的快速回复或后回复相反.将响应与问题相关联的唯一方法是按照@ anshuman-dhamoon的建议手动跟踪应用中的会话状态

为此,最好为每个用户维护一个状态,以及每个状态的下一个状态.

// optionally store this in a database
const users = {}

// an object of state constants
const states = {
    question1: 'question1',
    question2: 'question2',
    closing: 'closing',
}

// mapping of each to state to the message associated with each state
const messages = {
    [states.question1]: 'How are you today?',
    [states.question2]: 'Where are you from?',
    [states.closing]: 'That\'s cool. It\'s nice to meet you!',
}

// mapping of each state to the next state
const nextStates = {
    [states.question1]: states.question2,
    [states.question2]: states.closing,
}

const receivedMessage = (event) => {
    // keep track of each user by their senderId
    const senderId = event.sender.id
    if (!users[senderId].currentState){
        // set the initial state
        users[senderId].currentState = states.question1
    } else {
        // store the answer and update the state
        users[senderId][users[senderId].currentState] = event.message.text
        users[senderId].currentState = nextStates[users[senderId.currentState]]
    }
    // send a message to the user via the Messenger API
    sendTextMessage(senderId, messages[users[senderId].currentState])
}
Run Code Online (Sandbox Code Playgroud)

注意如果您需要,您甚至可以将nextStates可调用函数的值设置为获取当前状态的答案,并通过将用户根据他/她的响应传递到不同的状态来分支到不同的会话流中.


Sha*_*han 6

据我所知,在 Facebook 聊天机器人中,您可以将数据从用户发送到聊天机器人,只需API 参考中给出的回发按钮设置有效负载即可

聊天机器人不会存储您的会话或任何状态/标志。您可以设置状态或标志或数组,但是当您更新应用程序或重新启动服务器时,所有这些都会丢失。

所以,如果你真的想设置状态,你应该使用数据库。senderID每次都会保持不变,这样你就可以通过特定用户的特定 id 处理数据库中的数据。

有关更多详细信息,请在此处查看技术参考

我希望这会帮助你。如果是这样,请将其标记为答案。