itchat是一個開源的微信個人號接口,可以使用該庫進行微信網(wǎng)頁版中的所有操作,比如:所有好友、添加好友、拉好友群聊、微信機器人等等。詳細用戶請看文檔介紹,在這里。
本文主要使用該庫完成一個能夠處理微信消息的的圖靈機器人,包括好友聊天、群聊天。
1、itchat庫的安裝
pip install itchat
安裝完成后運行以下代碼,會出現(xiàn)出現(xiàn)一張二維碼,掃碼登陸之后將會登陸微信網(wǎng)頁。
2、登陸
import itchat# 登陸itchat.auto_login() # 可設(shè)置hotReload = True# 運行并保持在線狀態(tài)itchat.run()
此外,itchat 也提供短時間內(nèi)斷線重連的功能,只需要添加hotReload = True參數(shù),下次登陸時不需要通過掃描二維碼,只需要在手機端確認登陸即可。
3、消息的發(fā)送
itchat 庫可以發(fā)送 文本、圖片、視頻、附件等內(nèi)容,如向微信文件傳輸助手發(fā)送消息,可這樣:
itchat.send('Hello', toUserName='filehelper')toUserName 為要向發(fā)送消息的人的微信號,可以在微信手機端點擊查詢,也可以使用itchat庫中的search_friends函數(shù)來進行查找,返回其微信號,詳細用法,自行查找官方文檔。
4、消息的接收
###################### 完整代碼############################### 加載庫from itchat.content import *import requestsimport jsonimport itchatitchat.auto_login(hotReload = True)# 調(diào)用圖靈機器人的api,采用爬蟲的原理,根據(jù)聊天消息返回回復(fù)內(nèi)容def tuling(info): appkey = "e5ccc9c7c8834ec3b08940e290ff1559" url = "http://www.tuling123.com/openapi/api?key=%s&info=%s"%(appkey,info) req = requests.get(url) content = req.text data = json.loads(content) answer = data['text'] return answer# 對于群聊信息,定義獲取想要針對某個群進行機器人回復(fù)的群ID函數(shù)def group_id(name): df = itchat.search_chatrooms(name=name) return df[0]['UserName']# 注冊文本消息,綁定到text_reply處理函數(shù)# text_reply msg_files可以處理好友之間的聊天回復(fù)@itchat.msg_register([TEXT,MAP,CARD,NOTE,SHARING])def text_reply(msg): itchat.send('%s' % tuling(msg['Text']),msg['FromUserName'])@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])def download_files(msg): msg['Text'](msg['FileName']) return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])# 現(xiàn)在微信加了好多群,并不想對所有的群都進行設(shè)置微信機器人,只針對想要設(shè)置的群進行微信機器人,可進行如下設(shè)置@itchat.msg_register(TEXT, isGroupChat=True)def group_text_reply(msg): # 當然如果只想針對@你的人才回復(fù),可以設(shè)置if msg['isAt']: item = group_id(u'想要設(shè)置的群的名稱') # 根據(jù)自己的需求設(shè)置 if msg['ToUserName'] == item: itchat.send(u'%s' % tuling(msg['Text']), item)itchat.run()
新聞熱點
疑難解答