📜  如何使用BrainShop API在Android中创建聊天机器人?

📅  最后修改于: 2021-05-08 20:50:12             🧑  作者: Mango

我们已经看到了许多应用程序和网站,在这些应用程序和网站中,我们将看到一个聊天机器人,在这里我们可以与该聊天机器人一起聊天,并且可以轻松地从该聊天机器人中获得有关我们的问题的解决方案。在本文中,我们将介绍在Android构建聊天机器人的方法

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在该应用程序中,我们将构建一个简单的聊天机器人,在这里我们可以向我们的机器人提问,然后该机器人将回答我们的问题。下面是视频,我们将在其中观看我们将要构建的内容。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

导航至应用程序> Gradle脚本> build.gradle文件,然后在“依赖项”部分中将以下依赖项添加到该文件中。

添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中向Internet添加权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML



XML


  
    
    
  
    
  
        
        
  
        
        
  
    
      


Java
public class MessageModal {
  
    // string to store our message and sender
    private String message;
    private String sender;
  
    // constructor.
    public MessageModal(String message, String sender) {
        this.message = message;
        this.sender = sender;
    }
  
    // getter and setter methods.
    public String getMessage() {
        return message;
    }
  
    public void setMessage(String message) {
        this.message = message;
    }
  
    public String getSender() {
        return sender;
    }
  
    public void setSender(String sender) {
        this.sender = sender;
    }
}


XML


  
    
  
        
        
  
        
        
          
    
  


XML


  
    
  
        
        
  
        
        
          
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MessageRVAdapter extends RecyclerView.Adapter {
      
    // variable for our array list and context.
    private ArrayList messageModalArrayList;
    private Context context;
  
    // constructor class.
    public MessageRVAdapter(ArrayList messageModalArrayList, Context context) {
        this.messageModalArrayList = messageModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        // below code is to switch our 
        // layout type along with view holder.
        switch (viewType) {
            case 0:
                // below line we are inflating user message layout.
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg, parent, false);
                return new UserViewHolder(view);
            case 1:
                // below line we are inflating bot message layout.
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg, parent, false);
                return new BotViewHolder(view);
        }
        return null;
    }
  
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        // this method is use to set data to our layout file.
        MessageModal modal = messageModalArrayList.get(position);
        switch (modal.getSender()) {
            case "user":
                // below line is to set the text to our text view of user layout
                ((UserViewHolder) holder).userTV.setText(modal.getMessage());
                break;
            case "bot":
                // below line is to set the text to our text view of bot layout
                ((BotViewHolder) holder).botTV.setText(modal.getMessage());
                break;
        }
    }
  
    @Override
    public int getItemCount() {
        // return the size of array list
        return messageModalArrayList.size();
    }
  
    @Override
    public int getItemViewType(int position) {
        // below line of code is to set position.
        switch (messageModalArrayList.get(position).getSender()) {
            case "user":
                return 0;
            case "bot":
                return 1;
            default:
                return -1;
        }
    }
  
    public static class UserViewHolder extends RecyclerView.ViewHolder {
          
        // creating a variable 
        // for our text view.
        TextView userTV;
  
        public UserViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing with id.
            userTV = itemView.findViewById(R.id.idTVUser);
        }
    }
  
    public static class BotViewHolder extends RecyclerView.ViewHolder {
          
        // creating a variable
        // for our text view.
        TextView botTV;
  
        public BotViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing with id.
            botTV = itemView.findViewById(R.id.idTVBot);
        }
    }
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our
    // widgets in xml file.
    private RecyclerView chatsRV;
    private ImageButton sendMsgIB;
    private EditText userMsgEdt;
    private final String USER_KEY = "user";
    private final String BOT_KEY = "bot";
  
    // creating a variable for
    // our volley request queue.
    private RequestQueue mRequestQueue;
  
    // creating a variable for array list and adapter class.
    private ArrayList messageModalArrayList;
    private MessageRVAdapter messageRVAdapter;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // on below line we are initializing all our views.
        chatsRV = findViewById(R.id.idRVChats);
        sendMsgIB = findViewById(R.id.idIBSend);
        userMsgEdt = findViewById(R.id.idEdtMessage);
  
        // below line is to initialize our request queue.
        mRequestQueue = Volley.newRequestQueue(MainActivity.this);
        mRequestQueue.getCache().clear();
  
        // creating a new array list
        messageModalArrayList = new ArrayList<>();
  
        // adding on click listener for send message button.
        sendMsgIB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking if the message entered
                // by user is empty or not.
                if (userMsgEdt.getText().toString().isEmpty()) {
                    // if the edit text is empty display a toast message.
                    Toast.makeText(MainActivity.this, "Please enter your message..", Toast.LENGTH_SHORT).show();
                    return;
                }
  
                // calling a method to send message
                // to our bot to get response.
                sendMessage(userMsgEdt.getText().toString());
  
                // below line we are setting text in our edit text as empty
                userMsgEdt.setText("");
            }
        });
  
        // on below line we are initialing our adapter class and passing our array lit to it.
        messageRVAdapter = new MessageRVAdapter(messageModalArrayList, this);
  
        // below line we are creating a variable for our linear layout manager.
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
  
        // below line is to set layout
        // manager to our recycler view.
        chatsRV.setLayoutManager(linearLayoutManager);
  
        // below line we are setting
        // adapter to our recycler view.
        chatsRV.setAdapter(messageRVAdapter);
    }
  
    private void sendMessage(String userMsg) {
        // below line is to pass message to our
        // array list which is entered by the user.
        messageModalArrayList.add(new MessageModal(userMsg, USER_KEY));
        messageRVAdapter.notifyDataSetChanged();
  
        // url for our brain
        // make sure to add mshape for uid.
        // make sure to add your url.
        String url = "Enter you API URL here" + userMsg;
  
        // creating a variable for our request queue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
  
        // on below line we are making a json object request for a get request and passing our url .
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    // in on response method we are extracting data 
                    // from json response and adding this response to our array list.
                    String botResponse = response.getString("cnt");
                    messageModalArrayList.add(new MessageModal(botResponse, BOT_KEY));
                     
                    // notifying our adapter as data changed.
                    messageRVAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                      
                    // handling error response from bot.
                    messageModalArrayList.add(new MessageModal("No response", BOT_KEY));
                    messageRVAdapter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error handling.
                messageModalArrayList.add(new MessageModal("Sorry no response found", BOT_KEY));
                Toast.makeText(MainActivity.this, "No response from the bot..", Toast.LENGTH_SHORT).show();
            }
        });
          
        // at last adding json object 
        // request to our queue.
        queue.add(jsonObjectRequest);
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
  
        
        
  
        
        
  
    
      

第5步:创建一个Modal类来存储我们的消息

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为MessageModal,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

public class MessageModal {
  
    // string to store our message and sender
    private String message;
    private String sender;
  
    // constructor.
    public MessageModal(String message, String sender) {
        this.message = message;
        this.sender = sender;
    }
  
    // getter and setter methods.
    public String getMessage() {
        return message;
    }
  
    public void setMessage(String message) {
        this.message = message;
    }
  
    public String getSender() {
        return sender;
    }
  
    public void setSender(String sender) {
        this.sender = sender;
    }
}

步骤6:为用户消息创建布局文件

此文件中使用的图标位于drawable文件夹中。导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将文件命名为user_msg ,并将以下代码添加到其中。

XML格式



  
    
  
        
        
  
        
        
          
    
  

第7步:为漫游器消息创建布局文件

此文件中使用的图标位于drawable文件夹中。导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将文件命名为bot_msg,然后将以下代码添加到其中。

XML格式



  
    
  
        
        
  
        
        
          
    
  

步骤8:使用Adapter类

为了将数据设置到Chat RecyclerView的项目中,我们必须创建一个Adapter类。导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将您的类命名为MessageRVAdapter,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MessageRVAdapter extends RecyclerView.Adapter {
      
    // variable for our array list and context.
    private ArrayList messageModalArrayList;
    private Context context;
  
    // constructor class.
    public MessageRVAdapter(ArrayList messageModalArrayList, Context context) {
        this.messageModalArrayList = messageModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        // below code is to switch our 
        // layout type along with view holder.
        switch (viewType) {
            case 0:
                // below line we are inflating user message layout.
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg, parent, false);
                return new UserViewHolder(view);
            case 1:
                // below line we are inflating bot message layout.
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg, parent, false);
                return new BotViewHolder(view);
        }
        return null;
    }
  
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        // this method is use to set data to our layout file.
        MessageModal modal = messageModalArrayList.get(position);
        switch (modal.getSender()) {
            case "user":
                // below line is to set the text to our text view of user layout
                ((UserViewHolder) holder).userTV.setText(modal.getMessage());
                break;
            case "bot":
                // below line is to set the text to our text view of bot layout
                ((BotViewHolder) holder).botTV.setText(modal.getMessage());
                break;
        }
    }
  
    @Override
    public int getItemCount() {
        // return the size of array list
        return messageModalArrayList.size();
    }
  
    @Override
    public int getItemViewType(int position) {
        // below line of code is to set position.
        switch (messageModalArrayList.get(position).getSender()) {
            case "user":
                return 0;
            case "bot":
                return 1;
            default:
                return -1;
        }
    }
  
    public static class UserViewHolder extends RecyclerView.ViewHolder {
          
        // creating a variable 
        // for our text view.
        TextView userTV;
  
        public UserViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing with id.
            userTV = itemView.findViewById(R.id.idTVUser);
        }
    }
  
    public static class BotViewHolder extends RecyclerView.ViewHolder {
          
        // creating a variable
        // for our text view.
        TextView botTV;
  
        public BotViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing with id.
            botTV = itemView.findViewById(R.id.idTVBot);
        }
    }
}

步骤9:生成API密钥以使用chatbot服务

转到Brainshop.ai,使用您的用户名和密码生成您的简单帐户。只需在此网站上创建您的帐户即可。创建新帐户后,您将看到以下屏幕。创建帐户后,您必须从“请求密码”选项中请求一个新密码,然后输入您的电子邮件地址。添加电子邮件地址后,您必须将密码添加到您的帐户中。现在,我们可以很好地生成我们的API密钥了。

请按照上述步骤为您的聊天机器人生成新的大脑。生成您的漫游器之后,我们现在将获得此大脑的API URL。导航到您创建的大脑内部的设置选项卡,您将看到如下所示的机器人详细信息。

步骤10:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our
    // widgets in xml file.
    private RecyclerView chatsRV;
    private ImageButton sendMsgIB;
    private EditText userMsgEdt;
    private final String USER_KEY = "user";
    private final String BOT_KEY = "bot";
  
    // creating a variable for
    // our volley request queue.
    private RequestQueue mRequestQueue;
  
    // creating a variable for array list and adapter class.
    private ArrayList messageModalArrayList;
    private MessageRVAdapter messageRVAdapter;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // on below line we are initializing all our views.
        chatsRV = findViewById(R.id.idRVChats);
        sendMsgIB = findViewById(R.id.idIBSend);
        userMsgEdt = findViewById(R.id.idEdtMessage);
  
        // below line is to initialize our request queue.
        mRequestQueue = Volley.newRequestQueue(MainActivity.this);
        mRequestQueue.getCache().clear();
  
        // creating a new array list
        messageModalArrayList = new ArrayList<>();
  
        // adding on click listener for send message button.
        sendMsgIB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking if the message entered
                // by user is empty or not.
                if (userMsgEdt.getText().toString().isEmpty()) {
                    // if the edit text is empty display a toast message.
                    Toast.makeText(MainActivity.this, "Please enter your message..", Toast.LENGTH_SHORT).show();
                    return;
                }
  
                // calling a method to send message
                // to our bot to get response.
                sendMessage(userMsgEdt.getText().toString());
  
                // below line we are setting text in our edit text as empty
                userMsgEdt.setText("");
            }
        });
  
        // on below line we are initialing our adapter class and passing our array lit to it.
        messageRVAdapter = new MessageRVAdapter(messageModalArrayList, this);
  
        // below line we are creating a variable for our linear layout manager.
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
  
        // below line is to set layout
        // manager to our recycler view.
        chatsRV.setLayoutManager(linearLayoutManager);
  
        // below line we are setting
        // adapter to our recycler view.
        chatsRV.setAdapter(messageRVAdapter);
    }
  
    private void sendMessage(String userMsg) {
        // below line is to pass message to our
        // array list which is entered by the user.
        messageModalArrayList.add(new MessageModal(userMsg, USER_KEY));
        messageRVAdapter.notifyDataSetChanged();
  
        // url for our brain
        // make sure to add mshape for uid.
        // make sure to add your url.
        String url = "Enter you API URL here" + userMsg;
  
        // creating a variable for our request queue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
  
        // on below line we are making a json object request for a get request and passing our url .
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    // in on response method we are extracting data 
                    // from json response and adding this response to our array list.
                    String botResponse = response.getString("cnt");
                    messageModalArrayList.add(new MessageModal(botResponse, BOT_KEY));
                     
                    // notifying our adapter as data changed.
                    messageRVAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                      
                    // handling error response from bot.
                    messageModalArrayList.add(new MessageModal("No response", BOT_KEY));
                    messageRVAdapter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error handling.
                messageModalArrayList.add(new MessageModal("Sorry no response found", BOT_KEY));
                Toast.makeText(MainActivity.this, "No response from the bot..", Toast.LENGTH_SHORT).show();
            }
        });
          
        // at last adding json object 
        // request to our queue.
        queue.add(jsonObjectRequest);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

在以下链接上查看项目: https : //github.com/ChinmayMunje/GFG-Bot

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!