itchat 调用图灵API

要做一个能够与人交流的机器人有很多种方法,其中最简单的莫过于使用他人提供的接口。下面以图灵机器人为例,演示这一功能。
简单来说,就是我们以一定的规则给图灵的服务器发送数据包,图灵服务器另一端会给予我们相应的应答。为此,你需要一个Tuling Key来告诉服务器有权和它进行对话。

进入图灵机器人官网注册后,会在个人中心自动生成一个apikey。
这里写图片描述

    实现环境:Windows系统;python 3.x;

在开始编写程序之前,需要安装 itchat 包。itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。

下面直接从写入详细注释的代码开始,这样更显得直观。

# coding = utf8
import requests
import itchat
# 去图灵机器人官网注册后会生成一个apikey,可在个人中心查看
KEY = '8edce3ce905a4c1dbb965e6b35c3838f'
def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'   : KEY,
        'info'   : msg,   # 这是要发送出去的信息
        'userid'  : 'wechat-rebot',  #这里随意写点什么都行
    }
    try:
        # 发送一个post请求
        r = requests.post(apiUrl, data =data).json()
        # 获取文本信息,若没有‘Text’ 值,将返回Nonoe
        return r.get('text')
    except:
        return
# 通过定义装饰器加强函数 tuling_reply(msg) 功能,获取注册文本信息
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    # 设置一个默认回复,在出现问题仍能正常回复信息
    defaultReply = 'I received: ' +msg['Text']
    reply = get_response(msg['Text'])
    # a or b 表示,如有a有内容,那么返回a,否则返回b
    return reply or defaultReply
# 使用热启动,不需要多次扫码
itchat.auto_login(hotReload=True)
itchat.run()

 

配置好环境后,在编译器中运行上述程序,扫码登录后就可以正常测试了。之后使用别的手机给自己发消息,便可获得回复。
---------------------
作者:Solarzhou
来源:CSDN
原文:https://blog.csdn.net/zt7524/article/details/81746441
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 引入相关依赖库 在项目的gradle中引入okhttp3和gson的依赖库: ```java dependencies { implementation 'com.squareup.okhttp3:okhttp:3.12.1' implementation 'com.google.code.gson:gson:2.8.5' } ``` 2. 定义接口 定义一个接口类RestApi接收回调 ```java public interface RestApi { void success(ChatResponse response); void failure(Exception e); } ``` 3. 准备提交的数据 首先我们要把url和apiKey作为成员变量定义出来: ```java private static final String BASE_URL = "http://openapi.tuling123.com/openapi/api/v2"; private static final String API_KEY = "*************************"; ``` 接着我们需要定义一个请求的实体类RequestBody,该实体类中包含了请求的参数信息,其中reqType表示请求的方式为0,输入文本类型的请求信息为1,即输入文本。 ```java class RequestBody { private Perception perception; private UserInfo userInfo; public RequestBody(Perception perception, UserInfo userInfo) { this.perception = perception; this.userInfo = userInfo; } static class Perception { private InputText inputText; public Perception(InputText inputText) { this.inputText = inputText; } static class InputText { private String text; public InputText(String text) { this.text = text; } } } static class UserInfo { private String apiKey; private String userId; public UserInfo(String apiKey, String userId) { this.apiKey = apiKey; this.userId = userId; } } } ``` 4. 发送请求到服务器 使用 OkHttp3 发送 POST 请求到服务器,并通过 JSON 格式将 RequestBody 对象以字符串的形式传递给服务器: ```java public void sendRequest(String msg, final RestApi api) { // 请求实体类封装 RequestBody.RequestBodyPerception.RequestBodyInputText inputText = new RequestBody.RequestBodyPerception.RequestBodyInputText(msg); RequestBody.RequestBodyPerception perception = new RequestBody.RequestBodyPerception(inputText); RequestBody.UserInfo userInfo = new RequestBody.UserInfo(API_KEY, "123456"); RequestBody requestBody = new RequestBody(perception, userInfo); // 将 requestbody 转成 json 格式 Gson gson = new Gson(); String json = gson.toJson(requestBody); // 创建请求 Request request = new Request.Builder() .url(BASE_URL) .post(RequestBody.create(MediaType.parse("application/json"), json)) .build(); // 发送请求 OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { api.failure(e); } @Override public void onResponse(Call call, Response response) throws IOException { try { Gson gson = new Gson(); ChatResponse chatResponse = gson.fromJson(response.body().string(), ChatResponse.class); api.success(chatResponse); } catch (Exception e) { api.failure(e); } } }); } ``` 5. 处理响应数据 在成功回调函数中,将响应正文转换为 ChatResponse 对象,并将其返回给回调方法,该对象包含了机器人对我们问题的回答信息。 ```java @Override public void onResponse(Call call, Response response) throws IOException { try { Gson gson = new Gson(); ChatResponse chatResponse = gson.fromJson(response.body().string(), ChatResponse.class); api.success(chatResponse); } catch (Exception e) { api.failure(e); } } ``` 6. 使用接口 将以上方法的代码写在一个独立的类中,调用该类的 sendRequest 方法即可。 ```java RestApi api = new RestApi() { @Override public void success(ChatResponse response) { // 处理响应数据 } @Override public void failure(Exception e) { // 处理请求失败错误信息 } }; TuringRobotApi.getInstance().sendRequest("你好", api); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正在修炼的IT大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值