編程語言:Python2.7,基於圖靈APIhtml
首先在圖靈機器人官網(http://www.tuling123.com) 註冊帳號,建立機器人,使用圖靈的API接口,實現智能聊天等功能豐富的機器人,圖靈免費帳號每日調用接口數5000次。編程
安裝itchat庫:
pip install itchat
json
下面是Python實現代碼:api
# -*- 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微信