安裝:python
pip install -U wxpy -i "https://pypi.doubanio.com/simple/"
代碼:json
# coding:utf-8 from wxpy import * # 實例化,並登陸微信 bot = Bot(cache_path=True) # 查找到要使用機器人來聊天的好友 #my_friend = bot.friends().search('xxx')[0] my_friend = ensure_one(bot.search(u'xxx')) # 調用圖靈機器人API #api_key能夠網上找,也能夠到官網註冊http://www.tuling123.com/ tuling = Tuling(api_key='759e94b5631f4cc39d9de36b1a3e0811') # 4a0488cdce684468b95591a641f0971d # 使用圖靈機器人自動與指定好友聊天 @bot.register(my_friend) def reply_my_friend(msg): tuling.do_reply(msg) embed() bot.logout
itchat版本代碼:api
import requests import itchat #像圖靈機器人官網註冊申請http://www.tuling123.com/ KEY = '2c242b43e94a4e0ca984629828d4e164' def get_response(msg): # 構造了要發送給服務器的數據 # 使用圖靈機器人提供的接口 apiUrl = 'http://www.tuling123.com/openapi/api' #一個發動的api的數據 data = { 'key' : KEY, 'info' : msg, 'userid' : 'wechat-robot', } try: #使用post方法去請求 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()
參考:服務器