在 Python语言中,有一个微信接口模块itchat,可以用来实现微信的一些功能,本主题专门使用itchat来实现一些应用:
- 掌握iChat的API结构;
- 应用iChat的API实现用户需求;
前提:安装iChat模块
> pip install itchat
安装过程截图:
Python3.6版本下,itchat模块安装过程
一、itchat的API结构
使用dir函数可以获取itchat中的API信息;
代码:
import itchat
print(dir(itchat))
上述代码在python交互编程模式下,与ipython中都可以使用。
获取的API信息如下(从ipython中拷贝的):
['Core', 'VERSION', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'add_friend', 'add_member_into_chatroom', 'auto_login', 'check_login', 'components', 'config', 'configured_reply', 'content', 'core', 'create_chatroom', 'delete_member_from_chatroom', 'dump_login_status', 'get_QR', 'get_QRuuid', 'get_chatrooms', 'get_contact', 'get_friends', 'get_head_img', 'get_mps', 'get_msg', 'instanceList', 'load_login_status', 'log', 'login', 'logout', 'msg_register', 'new_instance', 'originInstance', 'returnvalues', 'revoke', 'run', 'search_chatrooms', 'search_friends', 'search_mps', 'send', 'send_file', 'send_image', 'send_msg', 'send_raw_msg', 'send_video', 'set_alias', 'set_chatroom_name', 'set_logging', 'set_pinned', 'show_mobile_login', 'start_receiving', 'storage', 'update_chatroom', 'update_friend', 'upload_file', 'utils', 'web_init']
根据字面意思,大致也知道上述函数的作用,具体的使用可以使用help函数获取。代码如下:
help(itchat.login)
或者
help('itchat.login')
获取的帮助结果如下:
Help on method login in module itchat.components.login:
login(enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None) method of itchat.core.Core instance
帮助输出截图
二、itchat的使用
1. 登录/登出
(1)登录函数
def login(self, enableCmdQR=False, picDir=None, qrCallback=None, loginCallback =None, exitCallback=None):
log in like web wechat does
for log in
- a QR code will be downloaded and opened
- then scanning status is logged, it paused for you confirm
- finally it logged in and show your nickName
for options
- enableCmdQR: show qrcode in command line
- integers can be used to fit strange char length
- picDir: place for storing qrcode
- qrCallback: method that should accept uuid, status, qrcode
- loginCallback: callback after successfully logged in
- if not set, screen is cleared and qrcode is deleted
- exitCallback: callback after logged out
- it contains calling of logout
for usage
..code::python
import itchat
itchat.login()
it is defined in components/login.py
and of course every single move in login can be called outside
you may scan source code to see how
- and modified according to your own demand
使用代码
#coding=utf-8
import itchat
itchat.login()
login函数执行过程中会产生一个二维码图片,more存放在login运行的当前工作目录,并且使用工具打开。
login登录运行过程
在用户使用手机扫描登录前,login处于阻塞状态;等扫描登录完成,会提示登录成功。登录成功后的输出: