Python微信庫:itchat


在論壇上看到了用Python登錄微信並實現自動簽到,才了解到一個新的Python庫: itchat

庫文檔說明鏈接在這: itchat

我存個檔在我網站(主要是我打開很慢),以便以后閱讀。

0x01 Start

最簡單的回復

通過如下代碼,可以完成回復所有文本信息(包括群聊)。

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鍵下存放了用於下載消息內容的方法,傳入文件地址即可 @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']) # 在注冊時增加isGroupChat=True將判定為群聊回復 @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()

當然這里不需要深究為什么這些東西可以這么寫,我在這里放出了示例程序只是為了給你一個該sdk相關代碼大概樣子的概念。

有了大概的模式的了解之后我們就可以進入下一部分的介紹。

0x02 Login

在上一部分中你看到了基本的注冊與登陸,而顯然登陸使用的是itchat提供了auto_login方法,調用即可完成登錄。

一般而言,我們都會在完成消息的注冊后登陸。

當然這里需要特別強調的是三點,分別是短時間關閉重連、命令行二維碼與自定義登陸內容。 itchat提供了登陸狀態暫存,關閉程序后一定時間內不需要掃碼即可登錄。 為了方便在無圖形界面使用itchat,程序內置了命令行二維碼的顯示。 * 如果你需要就登錄狀態就一些修改(例如更改提示語、二維碼出現后郵件發送等)。

**0x01-1 短時間關閉程序后重連**

這樣即使程序關閉,一定時間內重新開啟也可以不用重新掃碼。

最簡單的用法就是給 auto_login 方法傳入值為真的 hotReload 。

該方法會生成一個靜態文件 itchat.pkl ,用於存儲登陸的狀態。

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()

通過設置statusStorageDir可以將靜態文件指定為其他的值。

這一內置選項其實就相當於使用了以下兩個函數的這一段程序:

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.')

其中load_login_status與dump_login_status分別對應讀取與導出設置。

通過設置傳入的fileDir的值可以設定導入導出的文件。

**0x01-2 命令行二維碼顯示**

通過以下命令可以在登陸的時候使用命令行顯示二維碼:

itchat.auto_login(enableCmdQR=True)

部分系統可能字幅寬度有出入,可以通過將enableCmdQR賦值為特定的倍數進行調整:

# 如部分的linux系統,塊字符的寬度為一個字符(正常應為兩字符),故賦值為2
itchat.auto_login(enableCmdQR=2)

默認控制台背景色為暗色(黑色),若背景色為淺色(白色),可以將enableCmdQR賦值為負值:

itchat.auto_login(enableCmdQR=-1)

**0x01-2 自定義登錄過程**

如果需要控制登錄的過程,可以閱讀下面的內容。

同時itchat也提供了登陸所需的每一步的方法,登陸的過程按順序為: 獲取二維碼uuid->獲取二維碼->判斷是否已經登陸成功->獲取初始化數據->更新微信相關信息(通訊錄、手機登陸狀態)->循環掃描新信息(開啟心跳)

獲取二維碼uuid

獲取生成二維碼所需的uuid,並返回。

  • 方法名稱: get_QRuuid
  • 所需值:無
  • 返回值:成功->uuid,失敗->None

獲取二維碼

根據uuid獲取二維碼並打開,返回是否成功。

  • 方法名稱: get_QR
  • 所需值:uuid
  • 返回值:成功->True,失敗->False

判斷是否已經登陸成功

判斷是否已經登陸成功,返回掃描的狀態碼。

  • 方法名稱: check_login
  • 所需值:uuid
  • 返回值:登陸成功->'200',已掃描二維碼->'201',二維碼失效->'408',未獲取到信息->'0'

獲取初始化數據

獲取微信用戶信息以及心跳所需要的數據。

  • 方法名稱: web_init
  • 所需值:無
  • 返回值:存儲登錄微信用戶信息的字典

獲取微信通訊錄

獲取微信的所有好友信息並更新。

  • 方法名稱: get_contract
  • 所需值:無
  • 返回值:存儲好友信息的列表

更新微信手機登陸狀態

在手機上顯示登錄狀態。

  • 方法名稱: show_mobile_login
  • 所需值:無
  • 返回值:無

循環掃描新信息(開啟心跳)

循環掃描是否有新的消息,開啟心跳包。

  • 方法名稱: start_receiving
  • 所需值:無
  • 返回值:無

EG:

一個登錄例子:

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將根據接收到的消息類型尋找對應的已經注冊的方法。

如果一個消息類型沒有對應的注冊方法,該消息將會被舍棄。

在運行過程當中也可以動態注冊方法,注冊方式與結果不變。

注冊

你可以通過兩種方式注冊消息方法

import itchat
from itchat.content import * # 不帶參數注冊,所有消息類型都將調用該方法(包括群消息) @itchat.msg_register def simple_reply(msg): if msg['Type'] == 'Text': return 'I received: %s' % msg['Text'] # 帶參數注冊,該類消息類型將調用該方法 @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply(msg): itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])

消息類型

向注冊方法傳入的msg包含微信返回的字典的所有內容。

本api增加Text、Type(也就是參數)鍵值,方便操作。

itchat.content中包含所有的消息類型參數,內容如下表所示:

比如你需要存儲發送給你的附件:

@itchat.msg_register(ATTACHMENT)
def download_files(msg): msg['Text'](msg['FileName'])

值得注意的是,群消息增加了三個鍵值: isAt: 判斷是否@本號 ActualNickName: 實際NickName * Content: 實際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()

注冊消息的優先級

優先級分別為:后注冊消息先於先注冊消息,帶參數消息先於不帶參數消息。

以下面的兩個程序為例:

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()

在私聊發送文本時將會回復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()

僅在私聊發送文本時將會回復You said to me one to one,其余情況將會回復I received a ...。

動態注冊消息

動態注冊時可以選擇將 itchat.run() 放入另一線程或使用 configured_reply() 方法處理消息。

兩種方法分別是:

# 使用另一線程,但注意不要讓程序運行終止
import thread thread.start_new_thread(itchat.run, ()) # 使用configured_reply方法 while 1: itchat.configured_reply() # some other functions time.sleep(1)

以下給出一個動態注冊的例子:

#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'關閉' in msg['Text']: replyToGroupChat = False return u'已關閉' elif u'開啟' in msg['Text']: return u'已經在運行' return u'輸入"關閉"或者"開啟"測試功能' 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

回復

itchat提供五種回復方法,建議直接使用send方法。

send方法

  • 方法:

    send(msg='Text Message', toUserName=None)

  • 所需值:

    1.msg:消息內容
     2.'@fil@文件地址'將會被識別為傳送文件,'@img@圖片地址'將會被識別為傳送圖片,'@vid@視頻地址'將會被識別為小視頻 3.toUserName:發送對象,如果留空將會發送給自己
  • 返回值:發送成功->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:消息內容
     toUserName:發送對象,如果留空將會發送給自己
  • 返回值:發送成功->True, 失敗->False

  • 程序示例:

    import itchat

    itchat.auto_login()

    itchat.send_msg('Hello world')

send_file方法

  • 方法:

    send_file(fileDir, toUserName=None)

  • 所需值:

    fileDir:文件路徑(不存在該文件時將打印無此文件的提醒)
     toUserName:發送對象,如果留空將會發送給自己
  • 返回值:發送成功->True, 失敗->False

    #coding=utf8

    import itchat

    itchat.auto_login()

    #請確保該程序目錄下存在:xlsx.xlsx

    itchat.send_file('xlsx.xlsx')

send_img方法

  • 方法:

    send_img(fileDir, toUserName=None)

  • 所需值:

    fileDir:文件路徑(不存在該文件時將打印無此文件的提醒)
     toUserName:發送對象,如果留空將會發送給自己
  • 返回值:發送成功->True, 失敗->False

#coding=utf8
import itchat itchat.auto_login() # 請確保該程序目錄下存在:gz.gif itchat.send_img('gz.gif')

send_video方法

  • 方法:

    send_video(fileDir, toUserName=None)

  • 所需值:

    fileDir:文件路徑(不存在該文件時將打印無此文件的提醒)
     toUserName:發送對象,如果留空將會發送給自己
  • 返回值:發送成功->True, 失敗->False

    需要保證發送的視頻為一個實質的mp4文件

    #coding=utf8

    import itchat

    itchat.auto_login()

    #請確保該程序目錄下存在:demo.mp4

    itchat.send_file('demo.mp4')

0x05 Memmber stuff

在使用個人微信的過程當中主要有三種賬號需要獲取,分別為: 好友 公眾號 * 群聊

itchat為這三種賬號都提供了整體獲取方法與搜索方法。

而群聊多出獲取用戶列表方法以及創建群聊、增加、刪除用戶的方法。

這里我們分這三種分別介紹如何使用。

好友

好友的獲取方法為 get_friends ,將會返回完整的好友列表。 其中每個好友為一個字典 列表的第一項為本人的賬號信息 * 傳入update鍵為True將可以更新好友列表並返回

好友的搜索方法為 search_friends ,有四種搜索方式: 1. 僅獲取自己的用戶信息 2. 獲取特定UserName 的用戶信息 3. 獲取備注、微信號、昵稱中的任何一項等於 name 鍵值的用戶 4. 獲取備注、微信號、昵稱分別等於相應鍵值的用戶

其中三、四項可以一同使用,下面是示例程序:

# 獲取自己的用戶信息,返回自己的屬性字典
itchat.search_friends() # 獲取特定UserName的用戶信息 itchat.search_friends(userName='@abcdefg1234567') # 獲取任何一項等於name鍵值的用戶 itchat.search_friends(name='littlecodersh') # 獲取分別對應相應鍵值的用戶 itchat.search_friends(wechatAccount='littlecodersh') # 三、四項功能可以一同使用 itchat.search_friends(name='LittleCoder機器人', wechatAccount='littlecodersh')

公眾號

公眾號的獲取方法為 get_mps ,將會返回完整的公眾號列表。 其中每個公眾號為一個字典 傳入update鍵為True將可以更新公眾號列表並返回

公眾號的搜索方法為 search_mps ,有兩種搜索方法: 1. 獲取特定 UserName 的公眾號 2. 獲取名字中含有特定字符的公眾號

如果兩項都做了特定,將會僅返回特定 UserName 的公眾號,下面是示例程序:

# 獲取特定UserName的公眾號,返回值為一個字典
itchat.search_mps(userName='@abcdefg1234567') # 獲取名字中含有特定字符的公眾號,返回值為一個字典的列表 itcaht.search_mps(name='LittleCoder') # 以下方法相當於僅特定了UserName itchat.search_mps(userName='@abcdefg1234567', name='LittleCoder')

群聊

群聊的獲取方法為 get_chatrooms ,將會返回完整的群聊列表。 其中每個群聊為一個字典 傳入update鍵為True將可以更新群聊列表並返回

群聊的搜索方法為 search_chatrooms ,有兩種搜索方法: 1. 獲取特定UserName的群聊 2. 獲取名字中含有特定字符的群聊

如果兩項都做了特定,將會僅返回特定UserName的群聊,下面是示例程序:

# 獲取特定UserName的群聊,返回值為一個字典
itchat.search_chatrooms(userName='@abcdefg1234567') # 獲取名字中含有特定字符的群聊,返回值為一個字典的列表 itcaht.search_chatrooms(name='LittleCoder') # 以下方法相當於僅特定了UserName itchat.search_chatrooms(userName='@abcdefg1234567', name='LittleCoder')

群聊用戶列表的獲取方法為 update_chatroom 。 群聊在首次獲取中不會獲取群聊的用戶列表,所以需要調用該命令才能獲取群聊的成員 該方法需要傳入群聊的UserName,返回特定群聊的用戶列表

memberList = itchat.update_chatroom('@abcdefg1234567')

創建群聊、增加、刪除群聊用戶的方法如下所示: 由於之前通過群聊檢測是否被好友拉黑的程序,目前這三個方法都被嚴格限制了使用頻率 刪除群聊需要本賬號為群管理員,否則會失敗

memberList = itchat.get_friends()[1:]
# 創建群聊,topic鍵值為群聊名
chatroomUserName = itchat.create_chatroom(memberList, 'test chatroom')
# 刪除群聊內的用戶 itchat.delete_member_from_chatroom(chatroomUserName, memberList[0]) # 增加用戶進入群聊 itchat.add_member_into_chatroom(chatroomUserName, memberList[0])

0x06 QAQ

Q: 為什么我在設定了itchat.auto_login()的enableCmdQR為True后還是沒有辦法在命令行顯示二維碼?

A: 這是由於沒有安裝可選的包 pillow ,可以使用右邊的命令安裝: pip install pillow

0x07 Eg

def signin(): # 查找公眾號,進行簽到 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) # 如果執行成功寫入標致文件 exit() if __name__ == '__main__': # 如果不是在登陸狀態,就循環登陸 while not itchat.load_login_status(): sendMail() itchat.auto_login(hotReload=True) itchat.dump_login_status() signin() # 簽到 time.sleep(3600) signin() # 簽到

Thank you for read

End!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM