什么是聊天机器人

好吧其实没什么好解释的,就是能够一天二十四小时陪伴你到老的机器人,具有一定的学习能力,越来越像人,让你在没人陪的时候也能有人聊聊天解解闷

由于我还不太熟悉花里胡哨的机器学习,虽然对这方面有着很大的兴趣,但是奈何需要一定的门槛,不过没关系,我们可以先做一个调包侠

这篇教程,让我们一起用python来实现三款免费而且好用的机器人

从最简单的青云客开始吧

青云客

首先呢,青云客可谓是相当的简单了,也不需要注册,不需要登录,直接上代码吧

url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s'%(urllib.parse.quote('你好呀'))
html = requests.get(url)
print(html.json()['content'])

唯一需要注意的一点是,中文在url里,必须得转码,避免报错的可能,使用urllib

微软小冰

微软小冰是领先的跨平台人工智能机器人。微软小冰注重人工智能在拟合人类情商维度的发展,强调人工智能情商,而非任务完成在人机交互中的基础价值。

首先需要先领养小冰,通过微博关注小冰,然后给她发个消息

领养完成之后,按F12打开调试窗口,通过chat/里的Cookie,找到SUB值,注意不要手动退出,手动退出会刷新SUB的

之后,随便再发一条消息,找到new.json数据包,找到uid和source

最后构造参数

def xiaobing():
    uid = '你的uid'
    source = '你的source'
    SUB = '你的SUB'
    url_send = 'https://api.weibo.com/webim/2/direct_messages/new.json'
    data = {
        'text': 你要说的话,
        'uid': uid,
        'source': source
    }
    headers = {
        'cookie': 'SUB='+SUB,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
        'Referer': 'https://api.weibo.com/chat/'
    }
    response = requests.post(url_send, data=data, headers=headers).json()
    sendMsg = response['text']
    time.sleep(1)
    while True:
        url_get = 'https://api.weibo.com/webim/2/direct_messages/conversation.json?uid={}&source={}'.format(uid, source)
        response = requests.get(url=url_get,headers=headers).json()
        getMsg = response['direct_messages'][0]['text']
        if sendMsg == getMsg:
            time.sleep(1)
            else:
                return getMsg

也是调包侠的日常,没啥难度

腾讯闲聊

这个也和小冰类似

先创建应用

拿到ID和KEY

欧克,准备工作完成,上代码

def tencent(msg):
    APPID = '123'
    APPKEY = '123'
    url = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat'
    params = {
        'app_id': APPID,
        'time_stamp': str(int(time.time())),
        'nonce_str': ''.join(random.choice(string.ascii_letters + string.digits) for x in range(16)),
        'session': '10000'.encode('utf-8'),
        'question': msg.encode('utf-8')
    }
    sign_before = ''
    for key in sorted(params):
        # 键值拼接过程value部分需要URL编码,URL编码算法用大写字母,例如%E8。quote默认大写。
        sign_before += '{}={}&'.format(key, urllib.parse.quote(params[key], safe=''))
        # 将应用密钥以app_key为键名,拼接到字符串sign_before末尾
    sign_before += 'app_key={}'.format(APPKEY)

    # 对字符串sign_before进行MD5运算,得到接口请求签名
    sign = hashlib.md5(sign_before.encode('UTF-8')).hexdigest().upper()
    params['sign'] = sign
    # print(params)
    html = requests.post(url, data=params).json()
    return html['data']['answer']
msg= '我好看吗'
print("原话>>", msg)
res = tencent(msg)
print("腾讯>>", res)