一、開始之前必須安裝itchat庫
pip install itchat
(使用pip必須在電腦的環(huán)境變量中添加Python的路徑)
或 conda install request
二、開始編程前,我們需要在圖靈機器人官網(wǎng)注冊自己的圖靈機器人,來實現(xiàn)我們程序的智能聊天功能
1、圖靈機器人官網(wǎng)(http://www.turingapi.com/)
2、注冊登錄后點擊創(chuàng)建機器人
3、創(chuàng)建成功后,可以獲得機器人提供的API接口(apikey)
三、代碼實現(xiàn)
import itchat import requests #上傳獲得消息內(nèi)容到圖靈機器人 def getMessage(msg): apiURL='http://www.tuling123.com/openapi/api' data={'key':'你的apikey', 'info':msg, 'userID':'你的userID(可以隨便寫)' } r=requests.post(apiURL, data=data).json() print('答:'+r.get('text')) return r.get('text') #監(jiān)聽個人微信聊天 @itchat.msg_register(itchat.content.TEXT) def return_message(msg): try: print('問:'+msg['Text']) except Exception as e: print(e) return getMessage(msg['Text']) ''' #監(jiān)聽微信群聊天 @itchat.msg_register([itchat.content.TEXT],isGroupChat=True) def return_message(msg): print('問:'+msg['Text']) return getMessage(msg['Text']) ''' if __name__=='__main__': itchat.auto_login(hotReload=True) itchat.run()