制作一个聊天机器人

使用腾讯的人机闲聊API接口完成:

from hashlib import md5
from time import time
from random import sample
import string
from os import system,name
from urllib.parse import quote
from requests import post
 
def curlmd5(src):
    m = md5(src.encode('UTF-8'))
    return m.hexdigest().upper()
 
def get_params(plus_item):
    global params
    t = time()
    time_stamp = str(int(t))
    nonce_str = ''.join(sample(string.ascii_letters + string.digits, 10))
    app_id='2163266485'
    app_key='a0LYjIDhQYcRhSY6'
    params = {
     'app_id' : app_id,
              'question' : plus_item,
              'time_stamp' : time_stamp,
              'nonce_str' : nonce_str,
              'session' : '10000'
             }
    sign_before = ''
    for key in sorted(params):
        sign_before += '{}={}&'.format(key,quote(params[key], safe=''))
    sign_before += 'app_key={}'.format(app_key)
    sign = curlmd5(sign_before)
    params['sign'] = sign
    return params
 
def get_content(plus_item):
    global payload,r
    url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat"
    plus_item = plus_item.encode('utf-8')
    payload = get_params(plus_item)
    r = post(url,data=payload)
    content = r.json()
    if content['ret'] == 0:
        return '输出 >>> ' + str(content["data"]["answer"])
    else:
        return '错误 >>> ' + str(content['msg'])

if __name__ == '__main__' and name == 'nt':
    system('chcp 65001 >nul & color 0A & title 聊天')
    while 1:
        print(get_content(input('输入 >>> ')))
else:
    print('请使用Windows系统运行此程序!')

参考:《Python3 调用腾讯AI开放平台之智能闲聊与情感分析》

你可能感兴趣的:(python)