,由于微信禁止网页版登录,所以itchat库实现的功能已经不能用了。Python现在还能操作微信吗?答案是肯定的。目前有一个可以操作微信的项目WechatPCAPI。简单的说就是直接操作PC版的微信客户端。当然,它也有一定的缺点:PC版的微信客户端和Python都需要使用指定的版本。本文中,我们使用的Python版本为3.7.6,微信客户端版本为2.6.8.52,WechatPCAPI的GitHub地址为:https://github.com/Mocha-L/WechatPCAPI。获取好友列表WechatPCAPI提供方法get_friends(),返回信息包括:好友、群组、公众号列表信息。信息主要包括:微信号、昵称、自己设置的备注。我们利用获得的昵称做一个简单的词云展示。代码实现如下:logging.basicConfig(level=logging.INFO)defon_message(message):passdefget_friends():#初始化微信实例wx_inst=WechatPCAPI(on_message=on_message,log=logging)#启动微信wx_inst.start_wechat(block=True)#等待登录成功。这时候需要手动扫码登录微信wx_inst.get_myself():time.sleep(5)print('登录成功')nicknames=[]#排除词remove=['still','won't','some','so','surely','up','something','why','really','so','but','how','still','when','one','what','myself','everything','like','same','no','not','a','this','for']对于键,wx_inst.get_friends().items()中的值:如果在['fmessage','floatbottle','filehelper']或'chatroom'中键:继续nicknames.append(value['wx_nickname'])words=[]fortextinnicknames:ifnottext:continuefortinjieba.cut(text):iftinremove:continuewords.append(t)globalword_cloud#用逗号分隔单词word_cloud=','.join(words)defnk_cloud():#打开词云背景图cloud_mask=np.array(Image.open('bg.png'))#定义词云一一些属性wc=WordCloud(#背景图片分割颜色为白色background_color='white',#背景图片mask=cloud_mask,#显示最大字数max_words=300,#显示中文font_path='./fonts/simkai.ttf',#最大尺寸max_font_size=70)globalword_cloud#词云函数x=wc.generate(word_cloud)#生成词云图像image=x.to_image()#显示词云图像image.show()#保存词云图片厕所。to_file('nk.png')看效果:消息防撤回当我们用微信和朋友聊天的时候,对方有时候会撤回消息。一般情况下,我们并不知道好友撤回的消息是什么。通过WechatPCAPI可以实现消息的防召回功能。我们知道,通常撤回消息就是上一步点击撤回操作发送的内容。当然也可以在前两三步撤回消息。这里我们只撤回上一步。基本思路是:我们将上一步发送的消息撤回并保存,当对方点击撤回操作时,我们将上一步的消息再次返回给自己。我们看一下实现代码:logging.basicConfig(level=logging.INFO)queue_recved_event=Queue()defon_message(msg):queue_recved_event.put(msg)deflogin():pre_msg=''#初始化微信实例wx_inst=WechatPCAPI(on_message=on_message,log=logging)#启动微信wx_inst.start_wechat(block=True)#等待登录成功。这时候需要手动扫码登录微信wx_inst.get_myself():time.sleep(5)print('登录成功')whileTrue:msg=queue_recved_event.get()data=msg.get('data')sendinfo=data.get('sendinfo')data_type=str(data.get('data_type'))msg??content=str(data.get('msgcontent'))is_recv=data.get('is_recv')print(msg)如果data_type=='1'和'revokemsg'不在msgcontent中:pre_msg=msgcontent如果sendinfo不是None并且'revokemsg'在msgcontent中:user=str(sendinfo.get('wx_id_search'))recall='撤回消息:'+pre_msgwx_inst.send_text(to_user=user,msg=recall)查看运行效果:源码和微信安装包可在公众号Python小二后台回复200506获取
