关键词:
昨天突然想在Android下调用图灵机器人API实现聊天的功能。说干就干,虽然过程中遇见一些问题,但最后解决了的心情真好。
API接口是(key值可以在图灵机器人网站里注册得到)
www.tuling123.com/openapi/api?key=1702c05fc1b94e2bb4de7fb2e61b21a3&info=hello
最后hello是讲的话,访问这个网站会访问一个JSON格式的内容。
text关键字就是访问的内容,只要把这个关键字的内容截取下列就行了。
下面开始写代码。
首先布个局,丑丑的别介意。
一个TextView在上面,用来显示内容,一个EditView在下面用来输入内容,然后一个按钮实现点击事件。
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/rl" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:background="@drawable/background1" 7 tools:context=".MainActivity" > 8 9 <TextView 10 android:id="@+id/tv_out" 11 android:layout_width="match_parent" 12 android:layout_height="wrap_content" 13 android:textColor="#ff0000" 14 android:textIsSelectable="true" 15 android:textSize="25sp" /> 16 17 <LinearLayout 18 android:id="@+id/ll" 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content" 21 android:layout_alignParentBottom="true" 22 android:orientation="horizontal" > 23 24 <EditText 25 android:id="@+id/et_input" 26 android:layout_width="0dp" 27 android:layout_height="wrap_content" 28 android:layout_weight="4" 29 android:hint="@string/et_input" 30 android:textSize="20sp" /> 31 32 <Button 33 android:layout_width="0dp" 34 android:layout_height="wrap_content" 35 android:layout_weight="1" 36 android:background="@drawable/button1" 37 android:onClick="click" /> 38 </LinearLayout> 39 40 </RelativeLayout>
关键是点击事件的实现:
当按钮被点击时,就获取EditView上的内容。然后用InputUtils.getString(question)封装一个方法,传一个输入的内容用来返回网页关键字"text"里的内容。
这个地方需要注意下,在调试的时候,到int code = connection.getResponseCode();这一步就不运行了,获取不了状态码,百度了下。
需要在onCreate里加上:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() .penaltyLog().penaltyDeath().build());
1 package cn.starry.gangchat.utils; 2 3 import java.io.InputStream; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 import java.net.URLEncoder; 7 8 import org.json.JSONObject; 9 10 public class InputUtils { 11 private static String APIKEY = "1702c05fc1b94e2bb4de7fb2e61b21a3"; 12 13 public static String getString(String question) { 14 String out = null; 15 try { 16 String info = URLEncoder.encode(question, "utf-8"); 17 System.out.println(info); 18 URL url = new URL("http://www.tuling123.com/openapi/api?key=" 19 + APIKEY + "&info=" + info); 20 System.out.println(url); 21 HttpURLConnection connection = (HttpURLConnection) url 22 .openConnection(); 23 connection.setConnectTimeout(10 * 1000); 24 connection.setRequestMethod("GET"); 25 int code = connection.getResponseCode(); 26 if (code == 200) { 27 InputStream inputStream = connection.getInputStream(); 28 String resutl = StreamUtils.streamToString(inputStream); 29 JSONObject object = new JSONObject(resutl); 30 out = object.getString("text"); 31 } 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } 35 return out; 36 37 } 38 }
在InputUtils.java里用到了:
StreamUtils.streamToString(inputStream)
这个是我定义。是在一个输入流里获取内容,用utf-8编码返回。
1 package cn.starry.gangchat.utils; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 7 public class StreamUtils { 8 public static String streamToString(InputStream in) { 9 String result = ""; 10 try { 11 // 创建一个字节数组写入流 12 ByteArrayOutputStream out = new ByteArrayOutputStream(); 13 byte[] buffer = new byte[1024]; 14 int length = 0; 15 while ((length = in.read(buffer)) != -1) { 16 out.write(buffer, 0, length); 17 out.flush(); 18 } 19 result = new String(out.toByteArray(), "utf-8"); 20 out.close(); 21 } catch (IOException e) { 22 e.printStackTrace(); 23 } 24 return result; 25 } 26 }
最后还实现了一个点击按钮就让软键盘隐藏的功能。
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); if(imm.isActive()&&getCurrentFocus()!=null){ if (getCurrentFocus().getWindowToken()!=null) { imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }
1 package cn.starry.gangchat; 2 3 import java.util.Random; 4 5 import cn.starry.gangchat.utils.InputUtils; 6 7 import android.os.Bundle; 8 import android.os.StrictMode; 9 import android.view.View; 10 import android.view.inputmethod.InputMethodManager; 11 import android.widget.EditText; 12 import android.widget.LinearLayout; 13 import android.widget.RelativeLayout; 14 import android.widget.TextView; 15 import android.widget.Toast; 16 import android.annotation.SuppressLint; 17 import android.app.Activity; 18 import android.content.Context; 19 20 public class MainActivity extends Activity { 21 22 private EditText et_input; 23 private TextView tv_out; 24 private RelativeLayout rl; 25 26 @SuppressLint("NewApi") 27 @Override 28 protected void onCreate(Bundle savedInstanceState) { 29 super.onCreate(savedInstanceState); 30 setContentView(R.layout.activity_main); 31 int[] arr = { 0x7f020001, 0x7f020002, 0x7f020003, 0x7f020004, 32 0x7f020005 }; 33 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 34 .detectDiskReads().detectDiskWrites().detectNetwork() 35 .penaltyLog().build()); 36 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 37 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() 38 .penaltyLog().penaltyDeath().build()); 39 Random random = new Random(); 40 int ran = random.nextInt(5); 41 et_input = (EditText) findViewById(R.id.et_input); 42 tv_out = (TextView) findViewById(R.id.tv_out); 43 rl = (RelativeLayout) findViewById(R.id.rl); 44 rl.setBackgroundResource(arr[ran]); 45 } 46 47 public void click(View v) { 48 String question = et_input.getText().toString().trim(); 49 if (question == null || "".equals(question)) { 50 Toast.makeText(getApplicationContext(), "请输入内容哦!", 51 Toast.LENGTH_SHORT).show(); 52 return; 53 } 54 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 55 if(imm.isActive()&&getCurrentFocus()!=null){ 56 if (getCurrentFocus().getWindowToken()!=null) { 57 imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 58 } 59 } 60 String result = InputUtils.getString(question); 61 tv_out.setText(result); 62 et_input.setText(""); 63 } 64 65 }
安装包下载地址:http://123.207.118.162/downloads/Starry.apk
GitHub上有完整项目,可以直接导入在Eclipse里:https://github.com/Starry0/chat
如何在本地通过weixin4japi和第三方图灵机器人api搭建java聊天机器人
1、首先我们需要下载natapp,一个本地实现外网调用,需要调用微信接口,要联网,你有服务器域名是最好的到natapp官网上注册一个账号吧设置参数2、下载natapp.exe,编辑一个bat文件。一个开机启动本地网络化,完成一个网络映射... 查看详情
python使用图灵机器人实现微信聊天功能(代码片段)
首先需要去图灵官网创建一个属于自己的机器人然后得到apikey。一、自动与指定好友聊天#-*-coding:utf-8-*-"""Createdat2019-3-2611:50:49"""fromwxpyimportBot,Tuling,embed,ensure_onebot=Bot()my_friend=ensure_one(bot.search(‘张三‘))#想和机器人聊天的好... 查看详情
题目:用python3实现微信聊天机器人(代码片段)
做微信聊天机器人,实现步骤:获取微信的使用权,即python脚本能控制微信收发信息。python脚本收到聊天信息后,要对该信息进行处理,返回机器人的回应信息。一二两步要用到wxpy库里的各种组件来收发信息&... 查看详情
有哪些api接口可以用来做聊天机器人?
有哪些API接口可以用来做聊天机器人?1.海知智能:1.海知智能第三方技能插件开放平台概述·ruyi.ai开发者文档·看云docs.ruyi.ai不光能聊天,还可以在网站里内置技能,实现(翻译,成语接龙等)数十项功能2.天行机器人:白嫖用户... 查看详情
基于itchat定制聊天机器人
...nse(msg): #这里我们就像在“3.实现最简单的与图灵机器人的交互”中做的一样 #构造了要发送给服务器的数据 apiUrl 查看详情
简单的调用图灵机器人(代码片段)
1、去http://www.tuling123.com网址创建账号,创建机器人重点2、上代码 winform界面如上HttpRequestHelper.PostAsync方法具体如下///<summary>///使用post方法异步请求///</summary>///<paramname="url">目标链接</param>///<p 查看详情
python如何使用图灵的apikey搭建聊天机器人?
...+info response=getHtml(request) dic_json=json.loads(response) print'机器人:'.decode('utf-8')+dic_json['text'] 查看详情
如何优雅的用python玩转语音聊天机器人
...莓派免驱淘宝链接)申请API:百度语音api图灵api语音聊天机器人实现原理:当有人来到跟前时--》触发聊天功能,开始以每2s检测录制语音--》通过百度语音api合成文字--》传递给图灵api返回回答信息--》通过百度语音合成播放【... 查看详情
使用python实现一个简单的智能聊天机器人(代码片段)
...明最近两天需要做一个python的小程序,就是实现人与智能机器人(智能对话接口)的对话功能,目前刚刚测试了一下可以实现,就是能够实现个人与机器的智能对话(语音交流)。总体的思路大家可以设想一下,如果要... 查看详情
自然语言处理(nlp)聊天机器人模块实现(代码片段)
【自然语言处理(NLP)】聊天机器人模块实现(文章目录)前言(一)、任务描述使用PaddleNLP内置的生成式API的功能和用法,并使用PaddleNLP内置的plato-mini模型和配置的生成式API实现一个简单的闲聊机器人。(二)、环境配置本示例基于... 查看详情
用python配合微信api接口将微信个人号变为聊天机器人(代码片段)
操作系统:Ubuntu16.04 首先我们先安装itchat:这里我之前安装过了,先在又安装了一边使用 python3-c"importitchat"检查是否安装成功了如果没有任何输出,则表明安装成功了然后我们需要去图灵注册一个账号,来获取key,这里... 查看详情
小程序智能聊天机器人(代码片段)
ChatGPT小程序实战背景准备工作申请小程序并认证申请聊天接口秘钥申请微信支付商户号编写代码用户管理小程序授权登录获取用户信息更新用户头像和昵称结合第三方聊天平台API调用聊天接口的api会员支付福利背景最近ChatGPT特... 查看详情
【5g消息】啥是chatbot?
chatbot聊天机器人聊天机器人(Chatterbot)是经由对话或文字进行交谈的计算机程序。能够模拟人类对话,通过图灵测试。聊天机器人可用于实用的目的,如客户服务或资讯获取。参考技术Achatbot是面向行业客户开放的一种5g消息的... 查看详情
用go语言实现一个简单的聊天机器人(代码片段)
一、介绍目的:使用Go语言写一个简单的聊天机器人,复习整合Go语言的语法和基础知识。软件环境:Go1.9,Goland2018.1.5。 二、回顾Go语言基本构成要素:标识符、关键字、字面量、分隔符、操作符。它们可以组成各种表达式... 查看详情
nlp开发python实现聊天机器人(alice)(代码片段)
1、简介简单来说,聊天机器人是一种可以模拟和处理人类会话(无论是书面还是口头会话)的计算机程序,让人能够与数字设备交互,就像和真人交流一样。不同聊天机器人的复杂度各不相同,简单如通过单行响应回答简单查... 查看详情
自己动手写个聊天机器人吧
...源于Sirajology的视频BuildaChatbot昨天写LSTM的时候提到了聊天机器人,今天放松一下,来看看chatrobot是如何实现的。前天和一个小伙伴聊,如果一个机器人知道在它通过图灵测试后可能会被限制,那它假装自己不能通过然后逃过一劫... 查看详情
python快速搭建自动回复微信公众号(代码片段)
...信公众号在之前的一篇文章Python利用AIML和Tornado搭建聊天机器人微信订阅号中用aiml实现了一个简单的英文聊天机器人订阅号。但是只能处理英文消息,现在用图灵机器人来实现一个中文的聊天机器人订阅号。这里主要介绍如... 查看详情
自己动手做个微信聊天机器人
长夜慢慢无人聊天,自己动手做个微信聊天机器人陪自己。 智力太低,还是让他调戏别人吧。 看了上面的动画图片是不是有人好奇程序是怎么实现的?解决方案其实很简单:1.通过微信的web接口可以实现自动回复、登录... 查看详情