Python “图灵机器人”对话交互

1、创建图灵机器人账户

注册图灵机器人账号并创建一个机器人服务:

http://www.tuling123.com/

2、添加微信授权公众号,微信扫描生成的二维码:

3、微信关注图灵机器人公众号; 根据提供的API接入的apikey,就可以通过Python来关联微信与图灵机器人, 进行人机交互了;

4、完成下面程序,并执行再扫码登录微信,此时你的微信就可以自动回复所有消息;

demo1:图灵机器人,自动回复所有微信好友和群消息

注:wxpy一个根据网页版微信的接口封装的库,如果没有库,可直接pip安装

# 实例1:微信回复所有好友包括群消息
#注册图灵机器人,然后微信关注公众号,授权,然后运行这个代码会自动回复微信信息;
from wxpy import *
#扫码登陆
bot = Bot()
# 初始化图灵机器人
tuling = Tuling(api_key='你申请的key')
# 自动回复所有文字消息
@bot.register(msg_types=TEXT)
def auto_reply_all(msg):
    tuling.do_reply(msg)
# 开始运行
bot.join()

demo2:查找好友列表,回复指定好友消息

# 实例2:微信回复指定好友信息
#注册图灵机器人,然后微信关注公众号,授权,然后运行这个代码会自动回复微信信息;
from wxpy import *
#扫码登陆
bot = Bot()
# 初始化图灵机器人
tuling = Tuling(api_key='你申请的key')
# 获取好友
dear = bot.friends().search('石头')[0]#模糊查询石头好友

# 使用图灵机器人自动与指定好友聊天
@bot.register(dear)
def reply_my_friend(msg):
    print(msg)
    tuling.do_reply(msg)

embed()
# 开始运行
bot.join():

 demo3:控制台与图灵机器人直接对话

了解图灵机器人的API接口,注意这里是免费注册后测试用的,api官网没直接提供,如果是花钱注册的商用的,则系统会提供API,这里仅供参考

 注意:请求数据和响应数据分别要编码和解码

#! /usr/bin/python3.4
#实例3:图灵机器人直接交互(控制台输入)
# _*_ encode:utf-8_*_

import json
from urllib.request import urlopen,Request
from urllib.error import URLError
from urllib.parse import urlencode

class TuringChatMode(object):
    #初始化API请求地址
    def __init__(self):
        # API接口地址
        self.turing_url = 'http://www.tuling123.com/openapi/api?'

     #定义人机交互方法
    def botInteraction (self,text):
      
        url_data = dict(
            key = '你的key',
            info = text,
            userid = 'zyg',
        )
      
        self.request = Request(self.turing_url + urlencode(url_data))#设置并实例化Request

        try:
            w_data = urlopen(self.request)#发送请求
        except URLError:
            raise Exception("No internet connection available to transfer txt data")
            #断言了请求URL异常
        except:
            raise KeyError("Server wouldn't respond (invalid key or quota has been maxed out)")
            # 其他情况断言提示服务相应次数已经达到上限

        response_text = w_data.read().decode('utf-8')
        #print(response_text)

        json_result = json.loads(response_text)#将json格式进行解析

        return json_result['text']

if __name__ == '__main__':
    
    turing = TuringChatMode()
    while True:
        msg = input("
我要说话:")
        if msg == 'quit':
            exit("您已经退出了对话!")         # 设定输入quit,退出聊天。
        else:
            botMsg = turing.botInteraction(msg)
            print("图灵BOT回复我:",botMsg)

demo4:可以根据tkinter进行GUI布局,结合上面demo3实现聊天界面数据交互,此处略;

原文地址:https://www.cnblogs.com/ygzhaof/p/9712948.html