图灵第三方机器人自动回复

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">在个别APP中需要中,用户遇到问题但是找不到解决的问题,这时候要是有个人可以出现帮助客户解决问题,是不是太炫酷了,而且大幅度增加用户</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">的体验度。今天给大家介绍一个第三方的自动回复机器人,可以解决用户不会或者解决不了的问题。正式开始吧!!</span>


我用的自动回复是图灵机器人,官方网址是:http://www.tuling123.com/

登录注册等基本简单的内容我就不说了,

登录成功之后找到创建机器人选择需要的,我们既不是做QQ也不是微信,所以选择自定义,如下图

当我们选择自定义以后就可以编辑我们自己的机器人了,如下


这只是简单的基本信息,如果想高大上一点,还可以选择知识库,如下


点进去之后就可以控制机器遇到问题要怎么回答了,如下


完成我们需要配置的机器人在在最下面会有一个 “接入”我们只要记住API地址和APIKey,如下图


这样就是机器人就配置完成了,当然了,这是其中的冰山一角,我们可以编辑其他的,比如能力拓展,聪慧度,学习能力等等...因为每个人的需求不一样我就不给大家一一配置了,大家可以根据自己的需求 进行设置,下面是代码部分

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

先给大家看一下我项目枝干,并且说明每个类具体的作用


用到的类和布局已经在图中用红色框标注

ChatMessage:此类是bean有msg,type(枚举类需要自己定义),Date

result:此类是机器人返回内容的实体类,有返回码和返回内容

HttpUtils:此类是根据我们的API地址和APIKey拼接字符串然后发送,并根据返回的josn进行解析

ChatMessageAdapter:此类是自定义适配器,具体内容一会看代码

ManinActivity:是主Activty负责显示,更新UI,发送内容、、、


三个布局文件很好理解就不一一解释了,好了,具体我会用注释方法进行解释,请看代码

ChatMessage代码

public class ChatMessage {
    private String msg;
    private Type type;
    private Date date;

    public enum Type
    {
        INCOMING, OUTCOMING
    }

    public ChatMessage()
    {
    }



    public ChatMessage(String msg, Type type, Date date)
    {
        super();
        this.msg = msg;
        this.type = type;
        this.date = date;
    }





    public String getMsg()
    {
        return msg;
    }

    public void setMsg(String msg)
    {
        this.msg = msg;
    }

    public Type getType()
    {
        return type;
    }

    public void setType(Type type)
    {
        this.type = type;
    }

    public Date getDate()
    {
        return date;
    }
    public void setDate(Date date)
    {
        this.date = date;
    }


}
result代码



public class result {

    //返回码
    private int code;
    //机器人回复的内容
    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}




HttpUtils代码

public class HttpUtil {
    //我们刚才的获取的API地址:
    private static final String URL="http://www.tuling123.com/openapi/api";
    //我们刚才的获取的APIKey:
    private static final String APP_KAY="a97341b1eff7404f898f8a4f75d62c5e";



    public static ChatMessage sendMessage(String msg){
        ChatMessage chatmessage=new ChatMessage();
        String jsonretult = getJosn(msg);
        Gson gson=new Gson();
        result resultjosn =null;
        try {
            resultjosn=gson.fromJson(jsonretult, result.class);
            chatmessage.setMsg(resultjosn.getText());
        } catch (JsonSyntaxException e) {
            chatmessage.setMsg("服务器繁忙,请稍后再试试");
            e.printStackTrace();
        }
        chatmessage.setDate(new Date());
        chatmessage.setType(ChatMessage.Type.INCOMING);
        return chatmessage;
    }



    //发送请求并且获取返回JOSN
    public static String getJosn(String msg)
    {
        String result = "";
        //获取发送的请求字符串
        String url = stitchingString(msg);
        ByteArrayOutputStream baos = null;
        InputStream is = null;
        try
        {
            java.net.URL urlNet = new java.net.URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlNet
                    .openConnection();
            conn.setReadTimeout(5 * 1000);
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            is = conn.getInputStream();
            int len = -1;
            byte[] buf = new byte[128];
            baos = new ByteArrayOutputStream();
            while ((len = is.read(buf)) != -1)
            {
                baos.write(buf, 0, len);
            }
            baos.flush();
            result = new String(baos.toByteArray());
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (baos != null)
                    baos.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            try
            {
                if (is != null)
                {
                    is.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return result;
    }


    //拼接请求字符串并设置请求编码
    private static String stitchingString(String msg)
    {
        String url = "";
        try
        {
            url = URL + "?key=" + APP_KAY + "&info="
                    + URLEncoder.encode(msg, "UTF-8");
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        Log.i("url++++++", "url: "+url);
        return url;
    }

}



ChatMessageAdapter代码

public class ChatMessageAdapter extends BaseAdapter
{
	private LayoutInflater mInflater;
	private List<ChatMessage> mDatas;

	public ChatMessageAdapter(Context context, List<ChatMessage> mDatas)
	{
		mInflater = LayoutInflater.from(context);
		this.mDatas = mDatas;
	}

	@Override
	public int getCount()
	{
		return mDatas.size();
	}

	@Override
	public Object getItem(int position)
	{
		return mDatas.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	@Override
	public int getItemViewType(int position)
	{
		//判断Item类别
		ChatMessage chatMessage = mDatas.get(position);
		if (chatMessage.getType() == ChatMessage.Type.INCOMING)
		{
			return 0;
		}
		return 1;
	}

	@Override
	public int getViewTypeCount()
	{
		return 2;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		ChatMessage chatMessage = mDatas.get(position);
		ViewHolder viewHolder = null;
		if (convertView == null)
		{

			if (getItemViewType(position) == 0)
			{
				convertView = mInflater.inflate(R.layout.item_from_msg, parent,
						false);
				viewHolder = new ViewHolder();
				viewHolder.mDate = (TextView) convertView
						.findViewById(R.id.id_form_msg_date);
				viewHolder.mMsg = (TextView) convertView
						.findViewById(R.id.id_from_msg_info);
			} else
			{
				convertView = mInflater.inflate(R.layout.item_to_msg, parent,
						false);
				viewHolder = new ViewHolder();
				viewHolder.mDate = (TextView) convertView
						.findViewById(R.id.id_to_msg_date);
				viewHolder.mMsg = (TextView) convertView
						.findViewById(R.id.id_to_msg_info);
			}
			convertView.setTag(viewHolder);
		} else
		{
			viewHolder = (ViewHolder) convertView.getTag();
		}

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		viewHolder.mDate.setText(df.format(chatMessage.getDate()));
		viewHolder.mMsg.setText(chatMessage.getMsg());
		return convertView;
	}

	private final class ViewHolder
	{
		TextView mDate;
		TextView mMsg;
	}

}


MainActivity代码

public class MainActivity extends AppCompatActivity {

    private ListView mMsgs;
    private ChatMessageAdapter mAdapter;
    private List<ChatMessage> mDatas;

    private EditText mInputMsg;
    private Button mSendMsg;

    private Handler mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg)
        {
            // 等待接收,子线程完成数据的返回
            ChatMessage fromMessge = (ChatMessage) msg.obj;
            mDatas.add(fromMessge);
            mAdapter.notifyDataSetChanged();
            mMsgs.setSelection(mDatas.size()-1);
        };

    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.rengong_man);

        initView();
        initDatas();
        // 初始化事件
        initListener();
    }

    //当我们点击发送时候触发的事件
    private void initListener()
    {
        mSendMsg.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //将EditText中的内容转化为文本
                final String toMsg = mInputMsg.getText().toString();
                //判断EditText的内容是否为空
                if (TextUtils.isEmpty(toMsg))
                {
                    Toast.makeText(MainActivity.this, "发送消息不能为空!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                ChatMessage toMessage = new ChatMessage();
                toMessage.setDate(new Date());
                toMessage.setMsg(toMsg);
                toMessage.setType(ChatMessage.Type.OUTCOMING);
                mDatas.add(toMessage);
                mAdapter.notifyDataSetChanged();
                mMsgs.setSelection(mDatas.size()-1);

                //情况EditText
                mInputMsg.setText("");

                new Thread()
                {
                    public void run()
                    {
                        ChatMessage fromMessage = HttpUtil.sendMessage(toMsg);
                        Message m = Message.obtain();
                        m.obj = fromMessage;
                        mHandler.sendMessage(m);
                    };
                }.start();

            }
        });
    }

    //设置机器人初始信息
    private void initDatas()
    {
        mDatas = new ArrayList<ChatMessage>();
        mDatas.add(new ChatMessage("你好,我是柳岩", ChatMessage.Type.INCOMING, new Date()));
        mAdapter = new ChatMessageAdapter(this, mDatas);
        mMsgs.setAdapter(mAdapter);
    }

    //初始化控件
    private void initView()
    {
        mMsgs = (ListView) findViewById(R.id.id_listview_msgs);
        mInputMsg = (EditText) findViewById(R.id.id_input_msg);
        mSendMsg = (Button) findViewById(R.id.id_send_msg);
    }

}



item_from_msg.xml代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/id_form_msg_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#bebebe"
        android:text="2012-12-12 12:12:12"
        android:textColor="#f5f5f5"
        android:textSize="12sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <ImageView
                android:layout_width="49dp"
                android:layout_height="49dp"
                android:src="@drawable/icon" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="柳岩"
                android:textSize="18sp" >
            </TextView>
        </LinearLayout>

        <TextView
            android:id="@+id/id_from_msg_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/chatfrom_bg_normal"
            android:gravity="center_vertical"
            android:textSize="16sp"
            android:text="你好" />
    </LinearLayout>


</LinearLayout>




item_to_msg.xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/id_to_msg_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#bebebe"
        android:text="2012-12-12 12:12:12"
        android:textColor="#f5f5f5"
        android:textSize="12sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal" >
        
         <TextView
             android:id="@+id/id_to_msg_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/chatto_bg_normal"
            android:gravity="center_vertical"
              android:textSize="16sp"
            android:text="你好" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <ImageView
                android:layout_width="49dp"
                android:layout_height="49dp"
                android:src="@drawable/me" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="hyman"
                android:textSize="18sp" >
            </TextView>
        </LinearLayout>

       
    </LinearLayout>

</LinearLayout>




rengong_man.xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/id_ly_top"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/title_bar9" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="嘿嘿嘿"
            android:textColor="#ffffff"
            android:textSize="22sp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/id_ly_bottom"
        android:layout_width="fill_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        android:background="@drawable/bottom_bar9" >

        <Button
            android:id="@+id/id_send_msg"
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@drawable/send_btn_bg"
            android:text="发送" />

        <EditText
            android:id="@+id/id_input_msg"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toLeftOf="@id/id_send_msg"
            android:background="@drawable/login_edit_normal"
            android:textSize="18sp" />
    </RelativeLayout>

    <ListView
        android:id="@+id/id_listview_msgs"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/id_ly_bottom"
        android:layout_below="@id/id_ly_top"
        android:divider="@null"
        android:dividerHeight="5dp" >
    </ListView>

</RelativeLayout>

到这里所有代码已经粘完了,如果大家有什么问题或者发现我有什么问题可以回复我。。谢谢



阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页