微信个人号变为聊天机器人

实验环境

Python 3.5.2
微信的API包itchat

pip install itchat --upgrade

判断itchat 是否安装成功

python -c "import itchat"  

如果没有报错信息说明 已经将实验环境安装完成
让我们来实现一个聊天机器人吧

前期准备

申请一个免费的 Tuling Key
http://tuling123.com/help/h_cent_webapi.jhtml
如下图申请了一个APIkey

代码实现

#coding=utf8
import requests
import itchat

KEY = '****************************'

def get_response(msg):
    # 构造了要发送给服务器的数据
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        # 字典的get方法在字典没有'text'值的时候会返回None而不会抛出异常
        return r.get('text')
    # 为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常
    # 如果服务器没能正常交互(返回非json或无法连接),那么就会进入下面的return
    except:
        # 将会返回一个None
        return

@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复
    defaultReply = 'I received: ' + msg['Text']
    # 如果图灵Key出现问题,那么reply将会是None
    reply = get_response(msg['Text'])
    # a or b的意思是,如果a有内容,那么返回a,否则返回b
    # 有内容一般就是指非空或者非None,你可以用`if a: print('True')`来测试
    return reply or defaultReply

# 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动
itchat.auto_login(hotReload=True)
itchat.run()

实验结果

找个朋友给你发微信吧。