【问题标题】:Integrate chatbot Dialogflow in react native?将聊天机器人 Dialogflow 集成到 React Native 中?
【发布时间】:2021-10-04 14:10:28
【问题描述】:

我是 react native 的新手,目前,我想将聊天机器人 Dialogflow 集成到 react-native 中,但我没有成功,请逐步给我一些解决方案

【问题讨论】:

    标签: javascript react-native dialogflow-es chatbot


    【解决方案1】:

    这里有教程!以下内容适用于 react native expo 和无 expo。

    https://blog.jscrambler.com/build-a-chatbot-with-dialogflow-and-react-native/

    下面是一些代码:

    import React, { Component } from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    import { GiftedChat } from 'react-native-gifted-chat';
    import { Dialogflow_V2 } from 'react-native-dialogflow';
    
    import { dialogflowConfig } from './env';
    
    const BOT_USER = {
      _id: 2,
      name: 'FAQ Bot',
     avatar: 'https://i.imgur.com/7k12EPD.png'
    };
    
    class App extends Component {
     state = {
       messages: [
        {
        _id: 1,
        text: `Hi! I am the FAQ bot ? from Jscrambler.\n\nHow may I help you with today? 
        `,
         createdAt: new Date(),
        user: BOT_USER
       }
      ] 
    };
    
    componentDidMount() {
     Dialogflow_V2.setConfiguration(
      dialogflowConfig.client_email,
      dialogflowConfig.private_key,
      Dialogflow_V2.LANG_ENGLISH_US,
      dialogflowConfig.project_id
     );
    }
    
    handleGoogleResponse(result) {
     let text = result.queryResult.fulfillmentMessages[0].text.text[0];
     this.sendBotResponse(text);
    }
    
    onSend(messages = []) {
      this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages)
    }));
    
    let message = messages[0].text;
    Dialogflow_V2.requestQuery(
      message,
      result => this.handleGoogleResponse(result),
      error => console.log(error)
     );
    }
    
    sendBotResponse(text) {
      let msg = {
      _id: this.state.messages.length + 1,
      text,
      createdAt: new Date(),
      user: BOT_USER
    };
    
     this.setState(previousState => ({
       messages: GiftedChat.append(previousState.messages, [msg])
      }));
     } 
    
    render() {
     return (
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        <GiftedChat
          messages={this.state.messages}
          onSend={messages => this.onSend(messages)}
          user={{
            _id: 1
          }}
        />
      </View>
        );
      }
     }
    
     export default App;
    

    【讨论】:

    • 感谢您提供此解决方案,但我的任务未完成的原因有些问题
    • 这会公开密钥,并允许有权访问代码的任何人向您的 Dialogflow 代理发出请求。更好的选择是编写一些服务器端代码并​​使用它将用户的消息传递给 Dialogflow。
    • 谢谢,我会尝试写一些服务器端代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2018-11-13
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多