Python微信庫:itchat的用法詳解
在論壇上看到了用Python登錄微信并實(shí)現(xiàn)自動簽到,才了解到一個(gè)新的Python庫: itchat
庫文檔說明鏈接在這: itchat
我存?zhèn)€檔在我網(wǎng)站(主要是我打開很慢),以便以后閱讀。
0x01 Start
最簡單的回復(fù)
通過如下代碼,可以完成回復(fù)所有文本信息(包括群聊)。
import itchat from itchat.content import TEXT @itchat.msg_register def simple_reply(msg): if msg['Type'] == TEXT: return 'I received: %s' % msg['Content'] itchat.auto_login() itchat.run()
常用消息的配置
itchat支持所有的消息類型與群聊,下面的示例中演示了對于這些消息類型簡單的配置。
#coding=utf8 import itchat from itchat.content import * @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply(msg): itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName']) # 以下四類的消息的Text鍵下存放了用于下載消息內(nèi)容的方法,傳入文件地址即可 @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']) # 收到好友邀請自動添加好友 @itchat.msg_register(FRIENDS) def add_friend(msg): itchat.add_friend(**msg['Text']) # 該操作會自動將新好友的消息錄入,不需要重載通訊錄 itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName']) # 在注冊時(shí)增加isGroupChat=True將判定為群聊回復(fù) @itchat.msg_register(TEXT, isGroupChat = True) def groupchat_reply(msg): if msg['isAt']: itchat.send(u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName']) itchat.auto_login(True) itchat.run()
當(dāng)然這里不需要深究為什么這些東西可以這么寫,我在這里放出了示例程序只是為了給你一個(gè)該sdk相關(guān)代碼大概樣子的概念。
有了大概的模式的了解之后我們就可以進(jìn)入下一部分的介紹。
0x02 Login
在上一部分中你看到了基本的注冊與登陸,而顯然登陸使用的是itchat提供了auto_login方法,調(diào)用即可完成登錄。
一般而言,我們都會在完成消息的注冊后登陸。
當(dāng)然這里需要特別強(qiáng)調(diào)的是三點(diǎn),分別是短時(shí)間關(guān)閉重連、命令行二維碼與自定義登陸內(nèi)容。 itchat提供了登陸狀態(tài)暫存,關(guān)閉程序后一定時(shí)間內(nèi)不需要掃碼即可登錄。 為了方便在無圖形界面使用itchat,程序內(nèi)置了命令行二維碼的顯示。 * 如果你需要就登錄狀態(tài)就一些修改(例如更改提示語、二維碼出現(xiàn)后郵件發(fā)送等)。
**0x01-1 短時(shí)間關(guān)閉程序后重連**
這樣即使程序關(guān)閉,一定時(shí)間內(nèi)重新開啟也可以不用重新掃碼。
最簡單的用法就是給 auto_login 方法傳入值為真的 hotReload 。
該方法會生成一個(gè)靜態(tài)文件 itchat.pkl ,用于存儲登陸的狀態(tài)。
import itchat from itchat.content import TEXT @itchat.msg_register(TEXT) def simple_reply(msg): print(msg['Text']) itchat.auto_login(hotReload=True) itchat.run() itchat.dump_login_status()
通過設(shè)置statusStorageDir可以將靜態(tài)文件指定為其他的值。
這一內(nèi)置選項(xiàng)其實(shí)就相當(dāng)于使用了以下兩個(gè)函數(shù)的這一段程序:
import itchat from itchat.content import TEXT if itchat.load_login_status(): @itchat.msg_register(TEXT) def simple_reply(msg): print(msg['Text']) itchat.run() itchat.dump_login_status() else: itchat.auto_login() itchat.dump_login_status() print('Config stored, so exit.')
其中l(wèi)oad_login_status與dump_login_status分別對應(yīng)讀取與導(dǎo)出設(shè)置。
通過設(shè)置傳入的fileDir的值可以設(shè)定導(dǎo)入導(dǎo)出的文件。
**0x01-2 命令行二維碼顯示**
通過以下命令可以在登陸的時(shí)候使用命令行顯示二維碼:
itchat.auto_login(enableCmdQR=True)
部分系統(tǒng)可能字幅寬度有出入,可以通過將enableCmdQR賦值為特定的倍數(shù)進(jìn)行調(diào)整:
# 如部分的linux系統(tǒng),塊字符的寬度為一個(gè)字符(正常應(yīng)為兩字符),故賦值為2 itchat.auto_login(enableCmdQR=2)
默認(rèn)控制臺背景色為暗色(黑色),若背景色為淺色(白色),可以將enableCmdQR賦值為負(fù)值:
itchat.auto_login(enableCmdQR=-1)
**0x01-2 自定義登錄過程**
如果需要控制登錄的過程,可以閱讀下面的內(nèi)容。
同時(shí)itchat也提供了登陸所需的每一步的方法,登陸的過程按順序?yàn)椋?獲取二維碼uuid->獲取二維碼->判斷是否已經(jīng)登陸成功->獲取初始化數(shù)據(jù)->更新微信相關(guān)信息(通訊錄、手機(jī)登陸狀態(tài))->循環(huán)掃描新信息(開啟心跳)
獲取二維碼uuid
獲取生成二維碼所需的uuid,并返回。
方法名稱: get_QRuuid
所需值:無
返回值:成功->uuid,失敗->None
獲取二維碼
根據(jù)uuid獲取二維碼并打開,返回是否成功。
方法名稱: get_QR
所需值:uuid
返回值:成功->True,失敗->False
判斷是否已經(jīng)登陸成功
判斷是否已經(jīng)登陸成功,返回掃描的狀態(tài)碼。
方法名稱: check_login
所需值:uuid
返回值:登陸成功->'200',已掃描二維碼->'201',二維碼失效->'408',未獲取到信息->'0'
獲取初始化數(shù)據(jù)
獲取微信用戶信息以及心跳所需要的數(shù)據(jù)。
方法名稱: web_init
所需值:無
返回值:存儲登錄微信用戶信息的字典
獲取微信通訊錄
獲取微信的所有好友信息并更新。
方法名稱: get_contract
所需值:無
返回值:存儲好友信息的列表
更新微信手機(jī)登陸狀態(tài)
在手機(jī)上顯示登錄狀態(tài)。
方法名稱: show_mobile_login
所需值:無
返回值:無
循環(huán)掃描新信息(開啟心跳)
循環(huán)掃描是否有新的消息,開啟心跳包。
方法名稱: start_receiving
所需值:無
返回值:無
EG:
一個(gè)登錄例子:
import itchat, time, sys def output_info(msg): print('[INFO] %s' % msg) def open_QR(): for get_count in range(10): output_info('Getting uuid') uuid = itchat.get_QRuuid() while uuid is None: uuid = itchat.get_QRuuid();time.sleep(1) output_info('Getting QR Code') if itchat.get_QR(uuid): break elif get_count >= 9: output_info('Failed to get QR Code, please restart the program') sys.exit() output_info('Please scan the QR Code') return uuid uuid = open_QR() waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: output_info('Please press confirm') waitForConfirm = True elif status == '408': output_info('Reloading QR Code') uuid = open_QR() waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_contract() output_info('Login successfully as %s'%userInfo['NickName']) itchat.start_receiving() # Start auto-replying @itchat.msg_register def simple_reply(msg): if msg['Type'] == 'Text': return 'I received: %s' % msg['Content'] itchat.run()
0x03 Register
注冊消息方法
itchat將根據(jù)接收到的消息類型尋找對應(yīng)的已經(jīng)注冊的方法。
如果一個(gè)消息類型沒有對應(yīng)的注冊方法,該消息將會被舍棄。
在運(yùn)行過程當(dāng)中也可以動態(tài)注冊方法,注冊方式與結(jié)果不變。
注冊
你可以通過兩種方式注冊消息方法
import itchat from itchat.content import * # 不帶參數(shù)注冊,所有消息類型都將調(diào)用該方法(包括群消息) @itchat.msg_register def simple_reply(msg): if msg['Type'] == 'Text': return 'I received: %s' % msg['Text'] # 帶參數(shù)注冊,該類消息類型將調(diào)用該方法 @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply(msg): itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])
消息類型
向注冊方法傳入的msg包含微信返回的字典的所有內(nèi)容。
本api增加Text、Type(也就是參數(shù))鍵值,方便操作。
itchat.content中包含所有的消息類型參數(shù),內(nèi)容如下表所示:
比如你需要存儲發(fā)送給你的附件:
@itchat.msg_register(ATTACHMENT) def download_files(msg): msg['Text'](msg['FileName'])
值得注意的是,群消息增加了三個(gè)鍵值: isAt: 判斷是否@本號 ActualNickName: 實(shí)際NickName * Content: 實(shí)際Content
可以通過本程序測試:
import itchat from itchat.content import TEXT @itchat.msg_register(TEXT, isGroupChat = True) def text_reply(msg): print(msg['isAt']) print(msg['ActualNickName']) print(msg['Content']) itchat.auto_login() itchat.run()
注冊消息的優(yōu)先級
優(yōu)先級分別為:后注冊消息先于先注冊消息,帶參數(shù)消息先于不帶參數(shù)消息。
以下面的兩個(gè)程序?yàn)槔?/p>
import itchat from itchat.content import * itchat.auto_login() @itchat.msg_register(TEXT) def text_reply(msg): return 'This is the old register' @itchat.msg_register(TEXT) def text_reply(msg): return 'This is a new one' itchat.run()
在私聊發(fā)送文本時(shí)將會回復(fù)This is a new one。
import itchat from itchat.content import * itchat.auto_login() @itchat.msg_register def general_reply(msg): return 'I received a %s' % msg['Type'] @itchat.msg_register(TEXT) def text_reply(msg): return 'You said to me one to one: %s' % msg['Text'] itchat.run()
僅在私聊發(fā)送文本時(shí)將會回復(fù)You said to me one to one,其余情況將會回復(fù)I received a ...。
動態(tài)注冊消息
動態(tài)注冊時(shí)可以選擇將 itchat.run() 放入另一線程或使用 configured_reply() 方法處理消息。
兩種方法分別是:
# 使用另一線程,但注意不要讓程序運(yùn)行終止 import thread thread.start_new_thread(itchat.run, ()) # 使用configured_reply方法 while 1: itchat.configured_reply() # some other functions time.sleep(1)
以下給出一個(gè)動態(tài)注冊的例子:
#coding=utf8 import thread import itchat from itchat.content import * replyToGroupChat = True functionStatus = False def change_function(): if replyToGroupChat != functionStatus: if replyToGroupChat: @itchat.msg_register(TEXT, isGroupChat = True) def group_text_reply(msg): if u'關(guān)閉' in msg['Text']: replyToGroupChat = False return u'已關(guān)閉' elif u'開啟' in msg['Text']: return u'已經(jīng)在運(yùn)行' return u'輸入"關(guān)閉"或者"開啟"測試功能' else: @itchat.msg_register(TEXT, isGroupChat = True) def group_text_reply(msg): if u'開啟' in msg['Text']: replyToGroupChat = True return u'重新開啟成功' functionStatus = replyToGroupChat thread.start_new_thread(itchat.run, ()) while 1: change_function() time.sleep(.1)
0x04 Reply
回復(fù)
itchat提供五種回復(fù)方法,建議直接使用send方法。
send方法
方法:
send(msg='Text Message', toUserName=None)
所需值:
1.msg:消息內(nèi)容
2.'@fil@文件地址'將會被識別為傳送文件,'@img@圖片地址'將會被識別為傳送圖片,'@vid@視頻地址'將會被識別為小視頻
3.toUserName:發(fā)送對象,如果留空將會發(fā)送給自己
返回值:發(fā)送成功->True, 失敗->False
#coding=utf8 import itchat itchat.auto_login() itchat.send('Hello world!') # 請確保該程序目錄下存在:gz.gif以及xlsx.xlsx itchat.send('@img@%s' % 'gz.gif') itchat.send('@fil@%s' % 'xlsx.xlsx') itchat.send('@vid@%s' % 'demo.mp4')
send_msg方法
方法:
send_msg(msg='Text Message', toUserName=None)
所需值:
msg:消息內(nèi)容
toUserName:發(fā)送對象,如果留空將會發(fā)送給自己
返回值:發(fā)送成功->True, 失敗->False
程序示例:
import itchat itchat.auto_login() itchat.send_msg('Hello world')
send_file方法
方法:
send_file(fileDir, toUserName=None)
所需值:
fileDir:文件路徑(不存在該文件時(shí)將打印無此文件的提醒)
toUserName:發(fā)送對象,如果留空將會發(fā)送給自己
返回值:發(fā)送成功->True, 失敗->False
#coding=utf8 import itchat itchat.auto_login() #請確保該程序目錄下存在:xlsx.xlsx itchat.send_file('xlsx.xlsx')
send_img方法
方法:
send_img(fileDir, toUserName=None)
所需值:
fileDir:文件路徑(不存在該文件時(shí)將打印無此文件的提醒)
toUserName:發(fā)送對象,如果留空將會發(fā)送給自己
返回值:發(fā)送成功->True, 失敗->False
#coding=utf8 import itchat itchat.auto_login() # 請確保該程序目錄下存在:gz.gif itchat.send_img('gz.gif')
send_video方法
方法:
send_video(fileDir, toUserName=None)
所需值:
fileDir:文件路徑(不存在該文件時(shí)將打印無此文件的提醒)
toUserName:發(fā)送對象,如果留空將會發(fā)送給自己
返回值:發(fā)送成功->True, 失敗->False
需要保證發(fā)送的視頻為一個(gè)實(shí)質(zhì)的mp4文件
#coding=utf8 import itchat itchat.auto_login() #請確保該程序目錄下存在:demo.mp4 itchat.send_file('demo.mp4')
0x05 Memmber stuff
在使用個(gè)人微信的過程當(dāng)中主要有三種賬號需要獲取,分別為: 好友 公眾號 * 群聊
itchat為這三種賬號都提供了整體獲取方法與搜索方法。
而群聊多出獲取用戶列表方法以及創(chuàng)建群聊、增加、刪除用戶的方法。
這里我們分這三種分別介紹如何使用。
好友
好友的獲取方法為 get_friends ,將會返回完整的好友列表。 其中每個(gè)好友為一個(gè)字典 列表的第一項(xiàng)為本人的賬號信息 * 傳入update鍵為True將可以更新好友列表并返回
好友的搜索方法為 search_friends ,有四種搜索方式: 1. 僅獲取自己的用戶信息 2. 獲取特定 UserName 的用戶信息 3. 獲取備注、微信號、昵稱中的任何一項(xiàng)等于 name 鍵值的用戶 4. 獲取備注、微信號、昵稱分別等于相應(yīng)鍵值的用戶
其中三、四項(xiàng)可以一同使用,下面是示例程序:
# 獲取自己的用戶信息,返回自己的屬性字典 itchat.search_friends() # 獲取特定UserName的用戶信息 itchat.search_friends(userName='@abcdefg1234567') # 獲取任何一項(xiàng)等于name鍵值的用戶 itchat.search_friends(name='littlecodersh') # 獲取分別對應(yīng)相應(yīng)鍵值的用戶 itchat.search_friends(wechatAccount='littlecodersh') # 三、四項(xiàng)功能可以一同使用 itchat.search_friends(name='LittleCoder機(jī)器人', wechatAccount='littlecodersh')
公眾號
公眾號的獲取方法為 get_mps ,將會返回完整的公眾號列表。 其中每個(gè)公眾號為一個(gè)字典 傳入update鍵為True將可以更新公眾號列表并返回
公眾號的搜索方法為 search_mps ,有兩種搜索方法: 1. 獲取特定 UserName 的公眾號 2. 獲取名字中含有特定字符的公眾號
如果兩項(xiàng)都做了特定,將會僅返回特定 UserName 的公眾號,下面是示例程序:
# 獲取特定UserName的公眾號,返回值為一個(gè)字典 itchat.search_mps(userName='@abcdefg1234567') # 獲取名字中含有特定字符的公眾號,返回值為一個(gè)字典的列表 itcaht.search_mps(name='LittleCoder') # 以下方法相當(dāng)于僅特定了UserName itchat.search_mps(userName='@abcdefg1234567', name='LittleCoder')
群聊
群聊的獲取方法為 get_chatrooms ,將會返回完整的群聊列表。 其中每個(gè)群聊為一個(gè)字典 傳入update鍵為True將可以更新群聊列表并返回
群聊的搜索方法為 search_chatrooms ,有兩種搜索方法: 1. 獲取特定UserName的群聊 2. 獲取名字中含有特定字符的群聊
如果兩項(xiàng)都做了特定,將會僅返回特定UserName的群聊,下面是示例程序:
# 獲取特定UserName的群聊,返回值為一個(gè)字典 itchat.search_chatrooms(userName='@abcdefg1234567') # 獲取名字中含有特定字符的群聊,返回值為一個(gè)字典的列表 itcaht.search_chatrooms(name='LittleCoder') # 以下方法相當(dāng)于僅特定了UserName itchat.search_chatrooms(userName='@abcdefg1234567', name='LittleCoder')
群聊用戶列表的獲取方法為 update_chatroom 。 群聊在首次獲取中不會獲取群聊的用戶列表,所以需要調(diào)用該命令才能獲取群聊的成員 該方法需要傳入群聊的UserName,返回特定群聊的用戶列表
memberList = itchat.update_chatroom('@abcdefg1234567')
創(chuàng)建群聊、增加、刪除群聊用戶的方法如下所示: 由于之前通過群聊檢測是否被好友拉黑的程序,目前這三個(gè)方法都被嚴(yán)格限制了使用頻率 刪除群聊需要本賬號為群管理員,否則會失敗
memberList = itchat.get_friends()[1:] # 創(chuàng)建群聊,topic鍵值為群聊名 chatroomUserName = itchat.create_chatroom(memberList, 'test chatroom') # 刪除群聊內(nèi)的用戶 itchat.delete_member_from_chatroom(chatroomUserName, memberList[0]) # 增加用戶進(jìn)入群聊 itchat.add_member_into_chatroom(chatroomUserName, memberList[0])
0x06 QAQ
Q: 為什么我在設(shè)定了itchat.auto_login()的enableCmdQR為True后還是沒有辦法在命令行顯示二維碼?
A: 這是由于沒有安裝可選的包 pillow ,可以使用右邊的命令安裝: pip install pillow
0x07 Eg
def signin(): # 查找公眾號,進(jìn)行簽到 user = itchat.search_mps(name='Nulll.me') UserName = user[0]['UserName'] itchat.send(msg=u'3', toUserName=UserName) itchat.dump_login_status() pickleDumps('flag', localDay) # 如果執(zhí)行成功寫入標(biāo)致文件 exit() if __name__ == '__main__': # 如果不是在登陸狀態(tài),就循環(huán)登陸 while not itchat.load_login_status(): sendMail() itchat.auto_login(hotReload=True) itchat.dump_login_status() signin() # 簽到 time.sleep(3600) signin() # 簽到
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python分析微信好友性別比例和省份城市分布比例的方法示例【基于itchat模塊】
- Python使用itchat模塊實(shí)現(xiàn)簡單的微信控制電腦功能示例
- python基于itchat模塊實(shí)現(xiàn)微信防撤回
- python基于itchat實(shí)現(xiàn)微信群消息同步機(jī)器人
- python實(shí)現(xiàn)微信接口(itchat)詳細(xì)介紹
- python3操作微信itchat實(shí)現(xiàn)發(fā)送圖片
- 利用python微信庫itchat實(shí)現(xiàn)微信自動回復(fù)功能
- python使用itchat庫實(shí)現(xiàn)微信機(jī)器人(好友聊天、群聊天)
- python itchat實(shí)現(xiàn)微信自動回復(fù)的示例代碼
- python-itchat 獲取微信群用戶信息的實(shí)例
- python itchat實(shí)現(xiàn)微信好友頭像拼接圖的示例代碼
- Python實(shí)現(xiàn)清理微信僵尸粉功能示例【基于itchat模塊】
相關(guān)文章
詳解OpenCV中直方圖,掩膜和直方圖均衡化的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了OpenCV中直方圖、掩膜、直方圖均衡化詳細(xì)介紹及代碼的實(shí)現(xiàn),文中的示例代碼講解詳細(xì),需要的可以參考一下2022-11-11Python+OpenCV實(shí)現(xiàn)圖像基本操作的示例詳解
這篇文章主要為大家詳細(xì)介紹了Python通過OpenCV實(shí)現(xiàn)圖像的一些基本處理操作的方法,文中的示例代碼簡潔易懂,具有一定的參考價(jià)值,感興趣的可以學(xué)習(xí)一下2023-04-04python list是否包含另一個(gè)list所有元素的實(shí)例
今天小編就為大家分享一篇python list是否包含另一個(gè)list所有元素的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05python字符串str和字節(jié)數(shù)組相互轉(zhuǎn)化方法
下面小編就為大家?guī)硪黄猵ython字符串str和字節(jié)數(shù)組相互轉(zhuǎn)化方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03python數(shù)據(jù)結(jié)構(gòu)之鏈表的實(shí)例講解
下面小編就為大家?guī)硪黄猵ython數(shù)據(jù)結(jié)構(gòu)之鏈表的實(shí)例講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07