A complete and graceful API for Wechat. 微信个人号接口、微信机器人及命令行微信,三十行即可自定义个人号机器人。
这样在itchat更新的时候就不需要手动删除pkl了,我也不用因为修改pkl的内容导致bug而被吐槽。
好像很久以前就有说需要增加二维码的回调,但以前都是建议不使用auto_login,自定义登录过程。 现在auto_login里面的功能多了之后,还是给加上qrCallback吧。 需要注意的是,如果使用了qrCallback,系统默认不会再存储二维码并显示,这些内容全都交给qrCallback。
可以通过如下程序测试:
import logging
import itchat
itchat.set_logging(loggingLevel=logging.DEBUG)
def qrCallback(uuid, status, qrcode):
if status == '0':
with open('qr.jpg', 'wb') as f:
f.write(qrcode)
itchat.utils.print_qr('qr.jpg')
print('** qr callback **')
print('%s: %s' % (uuid, status))
print('qr size: %s' % len(qrcode))
print('*****************')
itchat.auto_login(True, qrCallback=qrCallback)
itchat.run(debug=True)
qrCallback必须接受三个参数,uuid status qrcode。 uuid和qrcode分别对应qrcode的uuid以及二进制图片。 status有0, 200, 201, 400, 408(都是字符串形式),对应为:
这里给出一个使用这个功能通过网页显示二维码的示例:源码
好像也没什么好说的,之后如果发现一些奇怪的问题,记得这样调试:
itchat.run(debug=True)
本来由于对于webwxsync(itchat.get_msg()
)返回的用户信息全部默认为群聊,导致了该问题。
目前已经修复,使用如下代码测试,记得删一下itchat.pkl之后测试:
import logging, sys
import itchat
from itchat.content import *
itchat.set_logging(loggingLevel=logging.DEBUG)
itchat.auto_login(True)
@itchat.msg_register(FRIENDS)
def add_friend(msg):
itchat.add_friend(**msg['Text'])
@itchat.msg_register(TEXT)
def check_contact(msg):
print('** Contact check begin **')
for member in itchat.get_friends():
if '@@' in member['UserName']:
print('Fake member: %s' % member['NickName'])
for chatroom in itchat.get_chatrooms():
if '@@' not in chatroom['UserName']:
print('Fake chatroom: %s' % member['NickName'])
print('** Contact check finish **')
itchat.run()
为了方便之后的调试与交流,每个发送操作都会产生带参数的logging信息。
可以通过如下代码测试:
import itchat
from itchat.content import *
itchat.auto_login(True)
@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.run(debug=True)
这就是我手滑,原谅我,同样记得删除itchat.pkl之后测试。
为了方便之后对代码的修改和调整,与itchatmp的适配,实现一些一直累计的需求。
在1.2.0版本中作如下更改:
使用logging记录日志。
新增接口,设定日志输出位置(文件、控制台),类似这样操作:
itchat.set_logging(showOnCmd=True, loggingFile=None, loggingLevel=10)
使用能够记录更多信息的返回值,类似这样操作:
# r.json() -> {'BaseResponse': {'Ret': 0 }}
r = ReturnValue(r.json())
if r:
print('True')
else:
print('False')
print(r['BaseResponse'])
# {'Ret': 0}
增加新实例接口与退出接口
itchat.new_instance()
itchat.logout()
将本处于init.py中的方法也加入client
将client以初始化时加载形式组织
定义时方法仅作占位及注释作用
# core.py 即原client.py
from .messages import load_messages_components
class Core(object):
def __init__(self):
self.__load_components()
def load_components(self):
load_messages_components(self)
def produce_msg(self, msg):
''' place for docs
* will be initialized in messages
'''
raise NotImplementedError()
# messages.py
def load_components(core):
core.produce_msg = produce_msg
def produce_msg(self, msg):
pass