通往成功之路Tech, Mason

itchat简单入门

2018-01-29  本文已影响82人  此十八

一、itchat介绍

itchat是一个开源的微信个人号接口,通过itchat可以实现微信(好友或微信群)的信息处理,包括文本、图片、小视频、地理位置消息、名片消息、语音消息、动画表情、普通链接、音乐链接、群消息、红包消息、系统消息等,可以对微信的消息进行获取和回复。

附:

Git地址:https://github.com/littlecodersh/ItChat

二、itchat使用

环境

itchat库的安装pip install itchat

检验是否安装成功python -c "import itchat",如果没有报错则说明安装成功

api

https://itchat.readthedocs.io/zh/latest/api/

三、实例

这里编辑器是使用的PyCharm,很好用的一款python编辑器。需要的可以去下载。

自动回复消息

下面代码是将微信消息在控制台输出

importitchat@itchat.msg_register(itchat.content.TEXT)defprint_content(msg):print(msg['Text'])itchat.auto_login()itchat.run()

保存文件为itchattest.py,执行该文件,会自动生成登录微信网页版的二维码,使用微信扫一扫该二维码登录即可。登录成功后,日志显示为:

Getting uuid of QR code.Downloading QR code.Please scan the QR code tologin.Please press confirm on your phone.Loading the contact,thismay take a littlewhile.TERM environment variablenotset.Login successfully as #此处是你登录的微信账号昵称#Startautoreplying.

用文件传输助手或其他微信账号给上一步登录的微信发消息,会看到消息内容被打印在控制台。

如果要实现简单的自动回复,只需要修改一下上述代码即可:

importitchat@itchat.msg_register(itchat.content.TEXT)deftext_reply(msg):returnmsg['Text']itchat.auto_login()itchat.run()

执行步骤同上,用其他微信给该微信发送消息,能看到自动回复内容与发送的消息内容一样

这里简单分析下代码:

@itchat.msg_register(itchat.content.TEXT)deftext_reply(msg):returnmsg['Text']

通过装饰器将text_reply注册为处理文本消息的函数

微信的信息类型除了itchat.content.TEXT外还有其他类型:

TEXT, MAP, CARD, NOTE, SHARING, PICTURE,

RECORDING, VOICE, ATTACHMENT, VIDEO, FRIENDS

itchat.auto_login()

登录微信网页版,会生成一个登录二维码,扫描登录即可

如果不想每次运行都登录,可以设置:

itchat.auto_login(hotReload=True)

可以在一段时间内不用再次扫描二维码登录

itchat.run()

处于持续运行状态

微信截图1

发送微信消息

下面是发送微信消息给文件传输助手:

importitchatitchat.auto_login(hotReload=True)itchat.send('test',toUserName='filehelper')

这里主要是使用itchat.send('test',toUserName='filehelper')给文件传输助手发送消息,这里要注意下使用中文‘文件传输助手’是接收不到发送的消息的。send方法的api见下面代码:

defsend(self, msg, toUserName=None, mediaId=None):''' wrapped function for all the sending functions

        for options

            - msg: message starts with different string indicates different type

                - list of type string: ['@fil@', '@img@', '@msg@', '@vid@']

                - they are for file, image, plain text, video

                - if none of them matches, it will be sent like plain text

            - toUserName: 'UserName' key of friend dict

            - mediaId: if set, uploading will not be repeated

        it is defined in components/messages.py

    '''raise NotImplementedError()

其中msg为要发送的消息内容,可以是中文

toUserName为要接收消息的好友的UserName

UserName的获取方法,可以通过:

importitchatitchat.auto_login(hotReload=True)friendslist = itchat.get_friends(update=True)[1:]printfriendslist

执行后返回一个dict,dict中包含每个好友的信息,信息内容包括:UserName,City,DisplayName,PYQuanPin,Province,KeyWord,RemarkName,HeadImgUrl等

下面是get_friends方法的具体解释:

defget_friends(self, update=False):''' fetch friends list

        for options

            - update: if not set, local value will be returned

        for results

            - a list of friends' info dicts will be returned

        it is defined in components/contact.py

    '''raiseNotImplementedError()

下载和发送微信附件

简单实现代码如下:

importitchatitchat.auto_login(hotReload=True)@itchat.msg_register(['Picture','Recording','Attachment','Video'])defdownload_files(msg):msg['Text'](msg['FileName'])    itchat.send('@%s@%s'%('img'ifmsg['Type'] =='Picture'else'fil', msg['FileName']), msg['FromUserName'])return'%s received'%msg['Type']itchat.run()

这里对关键行做下解释:

msg['Text'](msg['FileName'])

msg['Text']是一个文件下载函数

将FileName传入msg['Text']可以将文件下载下来

itchat.send('@%s@%s'%('img'ifmsg['Type'] =='Picture'else'fil', msg['FileName']), msg['FromUserName'])

itchat.send将下载的文件再发回给发送者

msg包含的内容,不理解的同学可以通过debug看到具体包含了哪些内容

作者:威武不能屈

链接:https://www.jianshu.com/p/e02e456a6d3a

來源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

上一篇下一篇

猜你喜欢

热点阅读