编程语言:Python2.7,基于图灵API

首先在图灵机器人官网(http://www.tuling123.com) 注册账号,创建机器人,使用图灵的API接口,实现智能聊天等功能丰富的机器人,图灵免费账号每日调用接口数5000次。

安装itchat库:
pip install itchat

下面是Python实现代码

# -*- coding: UTF-8 -*-
# wx.py
 
import requests
import itchat #这是一个用于微信回复的库
import time
import random
 
KEY = '032b4700760cede07d872eed8ea562a5' #填写你的图灵key
 
# 向api发送请求
def get_response(msg):
  print("IN :" + msg)#显示机器人收到的消息
  apiUrl = 'http://www.tuling123.com/openapi/api'
  data = {
    'key'  : KEY,
    'info'  : msg,
    'userid' : 'pth-robot',
  }
  try:
    r = requests.post(apiUrl, data=data).json()
    return r.get('text')
  except:
    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'])
  #下面显示出机器人发出的消息
  print("OUT:" + reply)
  #为防止微信检测封号,此处仿真人随机延迟2-5秒回复
  time.sleep(random.randint(2,5))
  # a or b的意思是,如果a有内容,那么返回a,否则返回b
  return reply or defaultReply
 
# 为了方便在命令行中扫码,不再使用热启动
itchat.auto_login(enableCmdQR=True)
itchat.run()

如果想让这个机器人一直运行,在服务器上配置好相应的Python环境即可,不过需要注意的是,手机端的微信也需要保持开启,不然手机端退出后服务器端也会同步退出的。

参考资料:
http://www.jianshu.com/p/72e1b6196014
http://www.cnblogs.com/luowangbao/p/6358748.html