This article mainly introduces the Python library: Itchat of the usage of the detailed, now share to everyone, but also for everyone to make a reference. Come and see it together.
See a new Python library by signing in with Python and automating check-ins on the forum: itchat
Library Document Description link in this: itchat
I save a file on my website (mostly I open it very slowly) so that I can read it later.
0x01 Start
The simplest reply
You can reply to all text messages (including group chat) by following the code below.
Import itchatfrom itchat.content import text@itchat.msg_registerdef simple_reply (msg): if msg[' Type '] = = TEXT: return ' I Received:%s '% msg[' Content ']itchat.auto_login () Itchat.run ()
Configuration of common messages
Itchat supports all message types with group chat, the following example shows a simple configuration for these message types.
#coding =utf8import itchatfrom 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 ']) # The text key for the following four classes of messages holds the method for downloading the message content, and the incoming file address can be @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 ') # received friend Invitation auto Add Friend @itchat.msg_register (FRIENDS) def add_friend (msg): itchat.add_ Friend (**msg[' Text ') # This action will automatically input the new friend's message, do not need to reload the Address Book itchat.send_msg (' Nice to meet you! ', msg[' recommendinfo ' [' UserName '] # added isgroupchat=true will be determined as group chat reply @itchat.msg_register (TEXT, isgroupchat = True) def groupchat_reply (msg) when registering: if msg[' isAt ': itchat.send (U ' @%s\u2005i received:%s '% (msg[' actualnickname '], msg[' Content '), msg[' Fromusername ']) itchat.auto_login (True) Itchat.run ()
Of course there's no need to delve into why these things can be written, and I'm releasing the sample program here just to give you a concept of what the SDK code looks like.
With a general understanding of the pattern we can go into the next section of the introduction.
0x02 Login
In the previous section you saw the basic registration and landing, and apparently logged in using the Itchat provides the Auto_login method, the call can complete the login.
Generally speaking, we will log in after completing the registration of the message.
Of course, the special emphasis here is three points, respectively, the short time to close the re-connection, command line QR code and custom landing content. Itchat provides a temporary login status, close the program after a certain period of time do not need to scan code to log in. In order to facilitate the use of itchat in the non-graphical interface, the program has built-in command line QR code display. * If you need to sign in the status of some changes (such as changing the prompt, the QR code appears after the message sent, etc.).
**0x01-1 a short time to close the program and re-connect * *
This way, even if the program is turned off, it can be reopened within a certain time without having to re-scan the code.
The simplest use is to pass the Auto_login method to the Hotreload with the value true.
This method generates a static file itchat.pkl that stores the status of the login.
Import itchatfrom 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 ()
You can specify a static file as a different value by setting Statusstoragedir.
This built-in option is actually equivalent to this program that uses the following two functions:
Import itchatfrom itchat.content import textif 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. ')
where Load_login_status and dump_login_status respectively correspond to the read and export settings.
You can set the import and export file by setting the value of the incoming filedir.
**0x01-2 command line QR code display * *
You can use the following command to display the QR code on the command line when logging in:
Itchat.auto_login (Enablecmdqr=true)
Some systems may have framed widths, which can be adjusted by assigning ENABLECMDQR to a specific multiplier:
# as part of the Linux system, the block character width is one character (normal should be two characters), so the assignment is 2itchat.auto_login (enablecmdqr=2)
The default console background color is dark (black), and if the background color is light (white), the ENABLECMDQR can be assigned a negative value:
Itchat.auto_login (Enablecmdqr=-1)
**0x01-2 Customizing the logon process * *
If you need to control the logon process, you can read the following.
At the same time, Itchat also provides a way to log in every step of the process, the procedure in order for: Get the QR code uuid-> get the QR code----to determine whether the successful login to obtain the initial data--Update related information (communication record, mobile phone landing status) Cycle through new information (Turn on Heartbeat)
Get the two-dimensional code UUID
Gets the UUID required to generate the QR code and returns it.
Method Name: Get_qruuid
Required Value: None
Return value: Success->uuid, Failure->none
Get two-dimensional code
Gets the QR code according to the UUID and opens, returns whether the success.
Method Name: GET_QR
Desired value: UUID
Return value: Success->true, Failure->false
Determine if the login has been successful
To determine if the login was successful, return the scanned status code.
Method Name: Check_login
Desired value: UUID
Return Value: Login success, ' 200 ', scanned QR code--' 201 ', QR code failure---' 408 ', not obtained information, ' 0 '
Get Initialization data
Gets the user information and the data needed for the heartbeat.
Method Name: Web_init
Required Value: None
return value: A dictionary that stores logon user information
Get Contacts
Get all of your friend information and update it.
Method Name: Get_contract
Required Value: None
Return value: Stores a list of friend information
Update Mobile Login Status
Displays the login status on the phone.
Method Name: Show_mobile_login
Required Value: None
return value: None
Cycle through new information (Turn on Heartbeat)
Cycle through the scan for new messages to open the heartbeat pack.
Method Name: start_receiving
Required Value: None
return value: None
EG:
A login example:
Import Itchat, Time, Sysdef output_info (msg): Print (' [info]%s '% msg) def OPEN_QR (): For get_count in range: OUTP Ut_info (' Getting uuid ') uuid = Itchat.get_qruuid () while UUID is None:uuid = Itchat.get_qruuid (); time.sleep (1) O Utput_info (' Getting QR Code ') if ITCHAT.GET_QR (UUID): Break elif get_count >= 9:output_info (' Failed to get QR Code, restart the program ') Sys.exit () output_info (' Please scan the QR code ') Return Uuiduuid = OPEN_QR () Waitforconfirm = Falsewhile 1:status = itchat.check_login (uuid) if status = = ' $ ': break elif status = = ' 201 ': If Waitforconfirm:output_info (' Please press confirm ') Waitforconfirm = True elif Status = = ' 408 ': output_in Fo (' Reloading QR Code ') uuid = OPEN_QR () waitforconfirm = Falseuserinfo = 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_registeRdef simple_reply (msg): If msg[' Type '] = = ' Text ': Return ' I Received:%s '% msg[' Content ']itchat.run ()
0x03 Register
Registering Message methods
Itchat will look for the corresponding registered method based on the type of message received.
If a message type does not have a corresponding registration method, the message will be discarded.
In the process of operation can also be dynamically registered methods, the registration method and the result is unchanged.
Registered
You can register a message method in two ways
Import itchatfrom itchat.content import *# with no parameter registration, all message types will call the method (including the group message) @itchat. Msg_registerdef simple_reply (msg): if msg[' type ' = = ' text ': return ' I Received:%s '% msg[' Text ']# with parameter registration, the class message type will call the method @itchat.msg_register ([Text, MAP, CARD, NOTE, sharing]) def text_reply (msg): itchat.send ('%s:%s '% (msg[' Type '), msg[' text '), msg[' Fromusername '])
Message type
The msg that is passed to the registration method contains all the contents of the returned dictionary.
This API adds text, Type (that is, parameter) key values for easy operation.
The itchat.content contains all the message type parameters, as shown in the following table:
For example, you need to store the attachments sent to you:
@itchat. Msg_register (ATTACHMENT) def download_files (msg): msg[' Text '] (msg[' FileName ')
It is worth noting that the group message added three key values: isAt: Determine if @ actualnickname: actual Nickname * Content: Actual content
This procedure can be used to test:
Import itchatfrom 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 ()
Priority of registering messages
Priority is: The post-registration message is preceded by the registration message, with the parameter message preceded by no parameter message.
Take the following two programs as an example:
Import itchatfrom itchat.content import *itchat.auto_login () @itchat. Msg_register (TEXT) def text_reply (msg): Return ' This was the old register ' @itchat. Msg_register (TEXT) def text_reply (msg): return ' This is a new one ' Itchat.run ( )
This is a new one when the text is sent in private chat.
Import itchatfrom itchat.content import *itchat.auto_login () @itchat. Msg_registerdef 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 will be said to me only when you send text in private chat, and the rest will revert to I received a ....
Dynamic registration Messages
Dynamic registration can choose to put Itchat.run () into another thread or use the Configured_reply () method to process messages.
The two methods are:
# use another thread, but be careful not to let the program run terminate import Threadthread.start_new_thread (Itchat.run, ()) # using the Configured_reply method while 1: Itchat.configured_reply () # Some other functions time.sleep (1)
Here is an example of a dynamic registration:
#coding =utf8import threadimport itchatfrom itchat.content Import *replytogroupchat = Truefunctionstatus = Falsedef Change_function (): if Replytogroupchat! = Functionstatus: if replytogroupchat: @itchat. Msg_register ( Text, isgroupchat = True) def group_text_reply (msg): if u ' off ' in msg[' text ']: replytogroupchat = False return u ' closed ' elif u ' open ' in msg[' Text ': return u ' is already running ' return u ' input ' close ' or ' turn on ' test function ' else: @ Itchat.msg_register (TEXT, isgroupchat = True) def group_text_reply (msg): if u ' open ' in msg[' TEXT ']: Replytogroupchat = True return u ' re-opened successfully ' functionstatus = Replytogroupchatthread.start_new_thread ( Itchat.run, ()) while 1: change_function () time.sleep (. 1)
0x04 Reply
Reply
Itchat provides five ways to reply, and it is recommended to use the Send method directly.
Send method
Method:
Send (msg= ' Text Message ', Tousername=none)
Required values:
1.MSG: Message Content
2. ' @fil @ file Address ' will be recognized as a transfer file, ' @img @ image address ' will be recognized as a transfer image, ' @vid @ Video address ' will be recognized as a small video
3.toUserName: Send Object, if left blank will be sent to yourself
Return value: Send Success->true, failed->false
#coding =utf8import Itchatitchat.auto_login () itchat.send (' Hello world! ') # Make sure that the program directory exists: Gz.gif and Xlsx.xlsxitchat.send (' @img @%s '% ' gz.gif ') itchat.send (' @fil @%s '% ' xlsx.xlsx ') itchat.send (' @ vid@%s '% ' demo.mp4 ')
Send_msg method
Method:
Send_msg (msg= ' Text Message ', Tousername=none)
Required values:
MSG: Message Content
Tousername: Send Object, if left blank will be sent to yourself
Return value: Send Success->true, failed->false
Examples of programs:
Import Itchatitchat.auto_login () itchat.send_msg (' Hello World ')
Send_file method
Method:
Send_file (Filedir, Tousername=none)
Required values:
Filedir: File path (a reminder without this file will be printed when the file does not exist)
Tousername: Send Object, if left blank will be sent to yourself
Return value: Send Success->true, failed->false
#coding =utf8import Itchatitchat.auto_login () #请确保该程序目录下存在: Xlsx.xlsxitchat.send_file (' xlsx.xlsx ')
Send_img method
Method:
Send_img (Filedir, Tousername=none)
Required values:
Filedir: File path (a reminder without this file will be printed when the file does not exist)
Tousername: Send Object, if left blank will be sent to yourself
Return value: Send Success->true, failed->false
#coding =utf8import Itchatitchat.auto_login () # Make sure that the program directory exists: gz.gifitchat.send_img (' gz.gif ')
Send_video method
Method:
Send_video (Filedir, Tousername=none)
Required values:
Filedir: File path (a reminder without this file will be printed when the file does not exist)
Tousername: Send Object, if left blank will be sent to yourself
Return value: Send Success->true, failed->false
Need to ensure that the sent video is a real mp4 file
#coding =utf8import Itchatitchat.auto_login () #请确保该程序目录下存在: Demo.mp4itchat.send_file (' Demo.mp4 ')
0x05 Memmber Stuff
In the process of using the individual, there are three main types of accounts to be obtained, namely: Friends public number * Group Chat
Itchat provides a holistic approach and search method for all three types of accounts.
Group chat is a way to get a list of users and create group chat, add, and delete users.
Here we divide these three kinds to describe how to use each.
Friends
A friend gets a get_friends and will return to the full list of friends. Each of the Friends for a dictionary list of the first item for my account information * Incoming Update key is true will be able to update the friend list and return
Friends Search method is search_friends, there are four ways to search: 1. Get only your own user Information 2. Get user information for a specific UserName 3. Gets the comment, number, and nickname of any one of the user 4 that is equal to the name key value. Get comments, numbers, and nicknames equal to the corresponding key value of the user
Three or four of them can be used together, here is the sample program:
# Get your own user information, return your own property dictionary itchat.search_friends () # Get user information for a specific userName itchat.search_friends (username= ' @abcdefg1234567 ') # Get any user itchat.search_friends (name= ' littlecodersh ') equal to the name key value to get the user itchat.search_friends corresponding to the respective key value (Wechataccount = ' Littlecodersh ') # Three or four functions can be used together with itchat.search_friends (name= ' Littlecoder robot ', wechataccount= ' Littlecodersh ')
Public number
The public number is get_mps and will be returned to the full list of public numbers. where each public number is a dictionary the incoming update key is true to update the public number list and return
The public number search method is Search_mps, there are two methods of search: 1. Get the public number 2 for a specific UserName. Get the public number with a specific character in the name
If both items are specific, only the public number of the specific UserName will be returned, as shown in the sample program:
# Get the public number for a specific userName, the return value is a dictionary itchat.search_mps (username= ' @abcdefg1234567 ') # Gets the public number with a specific character in the name, The return value is a dictionary of the list itcaht.search_mps (name= ' Littlecoder ') # The following method is equivalent to a specific usernameitchat.search_mps (username= ' @ abcdefg1234567 ', name= ' Littlecoder ')
Group Chat
Group chat is get_chatrooms and will return to the full group chat list. Each group chat for a dictionary the incoming update key to True will be able to update the group chat list and return
Group Chat Search method is search_chatrooms, there are two ways to search: 1. Get group chat 2 for a specific username. Get group chat with a specific character in the name
If both items are specific, only group chat will be returned for a specific username, the following is an example program:
# Get group chat for a specific userName, return a dictionary itchat.search_chatrooms (username= ' @abcdefg1234567 ') # get a group chat with a specific character in the name The return value is a dictionary of the list itcaht.search_chatrooms (name= ' Littlecoder ') # The following method is equivalent to a specific usernameitchat.search_chatrooms (username= ' @ abcdefg1234567 ', name= ' Littlecoder ')
The group chat user list is obtained by Update_chatroom. Group chat does not get a list of users for group chat in first time, so you need to call this command to get a member of group chat This method needs to pass in the username of group chat to return a list of users for a particular group chat
Memberlist = Itchat.update_chatroom (' @abcdefg1234567 ')
The ways to create group chat, add, and delete group chat users are as follows: As a result of a group chat before the program to detect whether a friend, currently these three methods are strictly limited the use of frequency delete group chat requires this account as a group administrator, otherwise it will fail
Memberlist = Itchat.get_friends () [1:]# Create group chat, topic key value for group chat name chatroomusername = Itchat.create_chatroom (memberlist, ' test Chatroom ') # Delete user itchat.delete_member_from_chatroom in group chat (Chatroomusername, memberlist[0]) # Add users to group chat itchat.add_ Member_into_chatroom (Chatroomusername, memberlist[0])
0x06 Qaq
Q: Why do I still have no way to display the QR code on the command line after I set the ENABLECMDQR of Itchat.auto_login () to true?
A: This is because the optional package pillow is not installed and can be installed using the command on the right: Pip Install Pillow
0x07 Eg
def signin (): # Find the public number, sign in 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) # If execution succeeds writing to the Peugeot file exit () if __name__ = = ' __main__ ': # If it is not logged in, the loop is logged while the not Itchat.load_login_status (): sendMail () itchat.auto_login (hotreload=true) itchat.dump_login_status () signin () # sign in Time.sleep (3600) signin () # Sign In