聊天机器人

将以下代码保存到eim_monitor.py文件里(在Adapter 插件目录中)

# 将聊天服务从图灵机器人切换到腾讯闲聊
import requests
import json
import time
import random
import string 
import hashlib
import urllib

def monitor(msg, logger):
    '''
    handle the message from the eim client(eg: scratch)
    '''
    appId = "2155753409"
    apiKey = "MyLQpyMr7K6S3kNI"
    apiUrl = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat"
    content = {
        '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(content):
        # 键值拼接过程value部分需要URL编码,URL编码算法用大写字母,例如%E8。quote默认大写。
        sign_before += '{}={}&'.format(key, urllib.parse.quote(content[key], safe=''))
        # 将应用密钥以app_key为键名,拼接到字符串sign_before末尾
    sign_before += 'app_key={}'.format(apiKey)

    # 对字符串sign_before进行MD5运算,得到接口请求签名
    sign = hashlib.md5(sign_before.encode('UTF-8')).hexdigest().upper()
    content['sign'] = sign
    stime=time.time()
    r = requests.post(apiUrl, data=content).json()
    qtime=time.time()
    dt=qtime-stime
    print(dt)
    return r['data']['answer']

之后可以在Scratch中使用它:

聊天机器人源码