Python implements WeChat interface - itchat module
Install
sudo pip install itchat
Log in
itchat.auto_login()
This method will use WeChat to scan the QR code to log in, but this method of logging in is indeed a short-term login, and will not retain the login status, that is, you still need to scan the QR code next time you log in. If you addhotReload==True
, Then the login state will be retained, and at least the QR code will not be scanned again during the subsequent login processes. This parameter generates a static fileitchat.pkl
to store the login state.
A specific method called after logging out and logging in
The method of grayscale function is mainly used here. The method after login needs to be assigned to
loginCallback
the method after exit, which needs to be assigned inexitCallback
. IfloginCallback
the value is not set, the QR code image will be automatically deleted and the command line display will be cleared.
import itchat, time
def lc():
print("Finash Login!")
def ec():
print("exit")
itchat.auto_login(loginCallback=lc, exitCallback=ec)
time.sleep()
itchat.logout() #强制退出登录
Reply message
send
send(msg="Text Message", toUserName=None)
parameter:
msg
: text message content
@fil@path_to_file
: Send File
@img@path_to_img
: send pictures
@vid@path_to_video
: send video
toUserName
: The object to send to, if left blank, it will be sent to itself.return value
True
orFalse
example code
# coding-utf-8
import itchat
itchat.auto_login()
itchat.send("Hello World!")
ithcat.send("@fil@%s" % '/tmp/test.text')
ithcat.send("@img@%s" % '/tmp/test.png')
ithcat.send("@vid@%s" % '/tmp/test.mkv')
send_msg
send_msg(msg='Text Message', toUserName=None)
, among themmsg
is the text to be sent,toUserName
is the sending object, if left blank, it will be sent to itself, the return value isTrue
orFalse
example code
import itchat
itchat.auto_login()
itchat.send_msg("hello world.")
send_file
send_file(fileDir, toUserName=None)
fileDir
is the file path, when the file does not exist, a reminder that there is no such file will be printed, and the return value isTrue
orFalse
example code
mport itchat
itchat.auto_login()
itchat.send_file("/tmp/test.txt")
send_image
send_image(fileDir, toUserName=None)
Parameters same as aboveexample code
import itchat
itchat.auto_login()
itchat.send_img("/tmp/test.txt")
send_video
send_video(fileDir, toUserName=None)
Parameters same as aboveexample code
import itchat
itchat.auto_login()
itchat.send_video("/tmp/test.txt")
register message method
itchat
The corresponding registered method will be found according to the received message type. If a message type does not have a corresponding registered method, the message will be discarded. The method can also be dynamically registered during the running process, and the registration method and result remain unchanged.
Registration method
Without specific object registration, it will be registered as a reply method for ordinary messages.
import itchat
from itchat.content import *
@itchat.msg_register(TEXT) #这里的TEXT表示如果有人发送文本消息,那么就会调用下面的方法
def simple_reply(msg):
#这个是向发送者发送消息
itchat.send_msg('已经收到了文本消息,消息内容为%s'%msg['Text'],toUserName=msg['FromUserName'])
return "T reveived: %s" % msg["Text"] #返回的给对方的消息,msg["Text"]表示消息的内容
Register with object parameters, the corresponding message object will call this method, which
isFriendChat
means between friends,isGroupChat
means group chat,isMapChat
means public account
import itchat
from itchat.content import *
@itchat.msg_register(TEXT, isFriendChat=True, isGroupChat=True,isMpChat=True)
def text_reply(msg):
msg.user.send("%s : %s" % (mst.type, msg.text))
The message type passed in to the registration method
msg
contains all the contents of the dictionary returned by WeChat.itchat
AddingText
,Type
(that is, parameters) key values, is convenient for operation.
itcaht.content
Contains all message type parameters, as shown in the following table
parameter | lType | Text key value |
---|---|---|
TEXT | text | Text content (text message) |
MAP | map | Location text (location sharing) |
CARD | business card | Recommender Dictionary (Recommender's business card) |
SHARING | share | Share name (shared music or article, etc.) |
PICTURE download method | image/expression | |
RECORDING | voice | Download method |
ATTACHMENT | Appendix | Download method |
VIDEO | small video | Download method |
FRIENDS | friend invitation | Parameters required to add friends |
SYSTEM | system information | List of users who updated the content or UserName of the group chat |
NOTE | notify | Notification text (message retracted, etc.) |
Download and send attachments
itchat
The attachment download method is stored inmsg
theText
key of . The sent filename (the default filename given by the image), is stored inmsg
theFileName
key of . The download method, accepts an available positional parameter (including the filename), and responds with the file storage. Note: The downloaded file is stored in the specified file, and the path andFileName
connection can be directly connected, such asmsg["Text"]('/tmp/weichat'+msg['FileName'])
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
#msg.download(msg['FileName']) #这个同样是下载文件的方式
msg['Text'](msg['FileName']) #下载文件
#将下载的文件发送给发送者
itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' else 'fil', msg["FileName"]), msg["FromUserName"])
group message
Three key values have been added, as follows:
isAt
Judge whether @ this number
ActualNickName
: actualNickName
(nickname)
Content
: actualContent
test program
import itcaht
from itchat.content import TEXT
@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
if(msg.isAt): #判断是否有人@自己
#如果有人@自己,就发一个消息告诉对方我已经收到了信息
itchat.send_msg("我已经收到了来自{0}的消息,实际内容为{1}".format(msg['ActualNickName'],msg['Text']),toUserName=msg['FromUserName'])
itchat.auto_login()
itchat.run()
Priority of registration messages
In general, messages of the same type registered later will overwrite previously registered messages. For details, see the documentation https://itchat.readthedocs.io/zh/latest/
Message content
Note: All message content can be accessed using key-value pairs, such as
msg["FromUserName]
viewing the sender, anditchat.search_friends(userName=msg['FromUserName'])['NickName']
viewing the sender's nickname
general news
General messages follow the following:
{
"FromUserName": "",
"ToUserName": "",
"Content": "",
"StatusNotifyUserName": "",
"ImgWidth": 0,
"PlayLength": 0,
"RecommendInfo": {},
"StatusNotifyCode": 0,
"NewMsgId": "",
"Status": 0,
"VoiceLength": 0,
"ForwardFlag": 0,
"AppMsgType": 0,
"Ticket": "",
"AppInfo": {},
"Url": "",
"ImgStatus": 0,
"MsgType": 0,
"ImgHeight": 0,
"MediaId": "",
"MsgId": "",
"FileName": "",
"HasProductId": 0,
"FileSize": "",
"CreateTime": 0,
"SubMsgType": 0
}
initialization message
MsgType: 51
FromUserName: 自己ID
ToUserName: 自己ID
StatusNotifyUserName: 最近联系的联系人ID
Content:
<msg>
<op id='4'>
<username>
# 最近联系的联系人
filehelper,xxx@chatroom,wxid_xxx,xxx,...
</username>
<unreadchatlist>
<chat>
<username>
# 朋友圈
MomentsUnreadMsgStatus
</username>
<lastreadtime>
1454502365
</lastreadtime>
</chat>
</unreadchatlist>
<unreadfunctionlist>
# 未读的功能账号消息,群发助手,漂流瓶等
</unreadfunctionlist>
</op>
</msg>
text message
MsgType: 1
FromUserName: 发送方ID
ToUserName: 接收方ID
Content: 消息内容
picture message
itchat
AddedText
key, the key value is the method to download the image.
MsgType: 3
FromUserName: 发送方ID
ToUserName: 接收方ID
MsgId: 用于获取图片,用于表示每一条消息
Content:
<msg>
<img length="6503" hdlength="0" />
<commenturl></commenturl>
</msg>
Extension: If you want to get
Content
the specific content in the text, you can use regular expressions to match it
video message
*
itchat
Added aText
key, the key value is the method to download the video.*
MsgType: 62
FromUserName: 发送方ID
ToUserName: 接收方ID
MsgId: 用于获取小视频
Content:
<msg>
<img length="6503" hdlength="0" />
<commenturl></commenturl>
</msg>
geolocation message
itchat
AddedText
key, the key value is the textual form of the location.
MsgType: 1
FromUserName: 发送方ID
ToUserName: 接收方ID
Content: http://weixin.qq.com/cgi-bin/redirectforward?args=xxx
OriContent:<?xml version="1.0"?>
<msg>
<location x="34.195278" y="117.177803" scale="16" label="江苏省徐州市铜山区新区海河路" maptype="0" poiname="江苏师范大学大学生公寓园区" />
</msg>
business card message
itchat
AddedText
key, the key valueadd_friend
is the property required by the call.
MsgType: 42
FromUserName: 发送方ID
ToUserName: 接收方ID
Content:
<?xml version="1.0"?>
<msg bigheadimgurl="" smallheadimgurl="" username="" nickname="" shortpy="" alias="" imagestatus="3" scene="17" province="" city="" sign="" sex="1" certflag="0" certinfo="" brandIconUrl="" brandHomeUrl="" brandSubscriptConfigUrl="" brandFlags="0" regionCode="" />
RecommendInfo:
{
"UserName": "xxx", # ID,这里的是昵称
"Province": "xxx",
"City": "xxx",
"Scene": 17,
"QQNum": 0,
"Content": "",
"Alias": "xxx", # 微信号
"OpCode": 0,
"Signature": "",
"Ticket": "",
"Sex": 0, # 1:男, 2:女
"NickName": "xxx", # 昵称
"AttrStatus": 4293221,
"VerifyFlag": 0
}
The following is the test code for adding friends
@itchat.msg_register(itchat.content.CARD,isFriendChat=True)
def simply(msg):
print msg['Text']
print msg['Content']
itchat.add_friend(userName=msg['Text']['UserName']) #添加推荐的好友
print msg['RecommendInfo']
print msg['RecommendInfo']['UserName']
Voice messages
*
itchat
Added aText
key, the key value is the method to download the voice file,MP3
the format of the downloaded file is
MsgType: 34
FromUserName: 发送方ID
ToUserName: 接收方ID
MsgId: 用于获取语音
Content:
<msg>
<voicemsg endflag="1" cancelflag="0" forwardflag="0" voiceformat="4" voicelength="1580" length="2026" bufid="216825389722501519" clientmsgid="49efec63a9774a65a932a4e5fcd4e923filehelper174_1454602489" fromusername="" />
</msg>
Download method:
msg['Text'](msg['FileName'])
animated emoji
itchat
Added aText
key, the key value is the method to download the emoticon of this picture. Note: I personally tested that the emoticons provided by some WeChat stores could not be downloaded successfully. The emoticons hereemoji
belong toTEXT
categories, so if they are registered asPICTURE
message types, they cannot be monitored.
MsgType: 47
FromUserName: 发送方ID
ToUserName: 接收方ID
Content:
<msg>
<emoji fromusername = "" tousername = "" type="2" idbuffer="media:0_0" md5="e68363487d8f0519c4e1047de403b2e7" len = "86235" productid="com.tencent.xin.emoticon.bilibili" androidmd5="e68363487d8f0519c4e1047de403b2e7" androidlen="86235" s60v3md5 = "e68363487d8f0519c4e1047de403b2e7" s60v3len="86235" s60v5md5 = "e68363487d8f0519c4e1047de403b2e7" s60v5len="86235" cdnurl = "http://emoji.qpic.cn/wx_emoji/eFygWtxcoMF8M0oCCsksMA0gplXAFQNpiaqsmOicbXl1OC4Tyx18SGsQ/" designerid = "" thumburl = "http://mmbiz.qpic.cn/mmemoticon/dx4Y70y9XctRJf6tKsy7FwWosxd4DAtItSfhKS0Czr56A70p8U5O8g/0" encrypturl = "http://emoji.qpic.cn/wx_emoji/UyYVK8GMlq5VnJ56a4GkKHAiaC266Y0me0KtW6JN2FAZcXiaFKccRevA/" aeskey= "a911cc2ec96ddb781b5ca85d24143642" ></emoji>
<gameext type="0" content="0" ></gameext>
</msg>
Common link or app to share message
Mainly for sharing articles, etc.
MsgType: 49
AppMsgType: 5
FromUserName: 发送方ID
ToUserName: 接收方ID
Url: 链接地址
FileName: 链接标题
Content:
<msg>
<appmsg appid="" sdkver="0">
<title></title>
<des></des>
<type>5</type>
<content></content>
<url></url>
<thumburl></thumburl>
...
</appmsg>
<appinfo>
<version></version>
<appname></appname>
</appinfo>
</msg>
music link message
Mainly for music
MsgType: 49
AppMsgType: 3
FromUserName: 发送方ID
ToUserName: 接收方ID
Url: 链接地址
FileName: 音乐名
AppInfo: # 分享链接的应用
{
Type: 0,
AppID: wx485a97c844086dc9
}
Content:
<msg>
<appmsg appid="wx485a97c844086dc9" sdkver="0">
<title></title>
<des></des>
<action></action>
<type>3</type>
<showtype>0</showtype>
<mediatagname></mediatagname>
<messageext></messageext>
<messageaction></messageaction>
<content></content>
<contentattr>0</contentattr>
<url></url>
<lowurl></lowurl>
<dataurl>
http://ws.stream.qqmusic.qq.com/C100003i9hMt1bgui0.m4a?vkey=6867EF99F3684&guid=ffffffffc104ea2964a111cf3ff3edaf&fromtag=46
</dataurl>
<lowdataurl>
http://ws.stream.qqmusic.qq.com/C100003i9hMt1bgui0.m4a?vkey=6867EF99F3684&guid=ffffffffc104ea2964a111cf3ff3edaf&fromtag=46
</lowdataurl>
<appattach>
<totallen>0</totallen>
<attachid></attachid>
<emoticonmd5></emoticonmd5>
<fileext></fileext>
</appattach>
<extinfo></extinfo>
<sourceusername></sourceusername>
<sourcedisplayname></sourcedisplayname>
<commenturl></commenturl>
<thumburl>
http://imgcache.qq.com/music/photo/album/63/180_albumpic_143163_0.jpg
</thumburl>
<md5></md5>
</appmsg>
<fromusername></fromusername>
<scene>0</scene>
<appinfo>
<version>29</version>
<appname>摇一摇搜歌</appname>
</appinfo>
<commenturl></commenturl>
</msg>
group message
itchat
Added three key-values related to group chat:
isAt
: Determine whether @ this number
ActualNickName
: actualNickName
Content
: actualContent
MsgType: 1
FromUserName: @@xxx
ToUserName: @xxx
Content:
@xxx:<br/>xxx
Red envelope news
MsgType: 49
AppMsgType: 2001
FromUserName: 发送方ID
ToUserName: 接收方ID
Content: 未知
system information
MsgType: 10000
FromUserName: 发送方ID
ToUserName: 自己ID
Content:
"你已添加了 xxx ,现在可以开始聊天了。"
"如果陌生人主动添加你为朋友,请谨慎核实对方身份。"
"收到红包,请在手机上查看"
Account type
tchat
The overall acquisition method and search method are provided for all three accounts.
friend
get_friends
itchat.get_friends()
Return to full friend list
Each friend is a dictionary, the first item of which is my account information;
incoming
update=True
, will update the friends list and return,get_friends(update=True)
search_friends
itchat.get_friends() Friends search, there are the following four ways
Get only your own user information
# 获取自己的用户信息,返回自己的属性字典
itchat.search_friends()
Get specific
UserName
user information
# 获取特定UserName的用户信息
itchat.search_friends(userName='@abcdefg1234567')
## 获取发送信息的好友的详细信息
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def reply(msg):
print msg['FromUserName']
print itchat.search_friends(userName=msg['FromUserName']) #详细信息
print itchat.search_friends(userName=msg['FromUserName'])['NickName'] #获取昵称
Get users whose remarks, WeChat IDs, and nicknames are equal to
name
the key value. (It can be used with the next configuration.)For example, there is a person with a note in my WeChat
autolife
, I can use this method to search for detailed information
# 获取任何一项等于name键值的用户
itchat.search_friends(name='autolife')
Get users whose remarks, WeChat IDs, and nicknames are equal to the corresponding key values. (Can be used with the previous configuration.)
# 获取分别对应相应键值的用户
itchat.search_friends(wechatAccount='littlecodersh')
# 三、四项功能可以一同使用
itchat.search_friends(name='LittleCoder机器人', wechatAccount='littlecodersh')
update_friend
Mainly used for friend update
Specific User: Enter the user
UserName
, return the latest information for the specified user.User list: a list of incoming
UserName
components, return a list of users' latest information
memberList = itchat.update_friend('@abcdefg1234567')
No public
get_mps
will return a complete list of job numbers
Each official account is a dictionary,
Passing
update=True
in will update the list of official accounts and return.
search_mps
Get a specific
UserName
official account
# 获取特定UserName的公众号,返回值为一个字典
itchat.search_mps(userName='@abcdefg1234567')
Get the official account with specific characters in the name.
# 获取名字中含有特定字符的公众号,返回值为一个字典的列表
itchat.search_mps(name='LittleCoder')
When both are warriors, only a specific
UserName
public account will be returned.
group chat
get_chatrooms
: Returns the full list of group chats.
search_chatrooms
: Group chat search.
update_chatroom
: Get the list of group chat users or update the group chat.
The group chat will not get the user list of the group chat in the first acquisition, so you need to call this command to get the group chat members.
For incoming group chats
UserName
, returns details for a specific group chat.Pass
UserName
in a list of components, and return a list of the latest information for the specified user.
memberList = itchat.update_chatroom('@@abcdefg1234567', detailedMember=True)
Create group chat, add/delete group chat users:
Due to the previous program of detecting whether to be blocked by friends through group chat, the frequency of use of these three methods is currently strictly limited.
Deleting a group chat requires the account to be an administrator, otherwise it will be invalid.
Adding users to group chats has direct joining and sending invitations, through
useInvitation
settings.Group chats with more than 40 people cannot use the direct join method.
memberList = itchat.get_frients()[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], useInvitation=False)
Method summary
itchat.add_friend
itchat.new_instance
itchat.add_member_into_chatroom
itchat.originInstance
itchat.auto_login
itchat.returnvalues
itchat.check_login
itchat.run
itchat.components
itchat.search_chatrooms
itchat.config
itchat.search_friends
itchat.configured_reply
itchat.search_mps
itchat.content
itchat.send
itchat.core
itchat.send_file
itchat.Core
itchat.send_image
itchat.create_chatroom
itchat.send_msg
itchat.delete_member_from_chatroom
itchat.send_raw_msg
itchat.dump_login_status
itchat.send_video
itchat.get_chatrooms
itchat.set_alias
itchat.get_contact
itchat.set_chatroom_name
itchat.get_friends
itchat.set_logging
itchat.get_head_img
itchat.set_pinned
itchat.get_mps
itchat.show_mobile_login
itchat.get_msg
itchat.start_receiving
itchat.get_QR
itchat.storage
itchat.get_QRuuid
itchat.update_chatroom
itchat.instanceList
itchat.update_friend
itchat.load_login_status
itchat.upload_file
itchat.log
itchat.utils
itchat.login
itchat.VERSION
itchat.logout
itchat.web_init
itchat.msg_register