上一篇Python遇见微信,我们使用WechatPCAPI获取微信好友信息和查看退出消息。在本文中,我们将使用WechatPCAPI来实现微信自动回复的功能。实现自动回复功能,我们需要用到图灵机器人,网址为:http://www.turingapi.com,我们在浏览器中输入以上网址打开,然后点击注册/登录按钮,如如下图:打开之后,如下图:我们再点击立即注册,跳转到注册页面,如下图:我们先填写需要的信息,然后点击注册按钮填完之后。注册成功后,我们会跳转到机器人管理页面。如下图:我们点击CreateRobot按钮,跳转到如下页面:我们填写好相应的信息后,点击Create按钮,然后跳转到机器人设置页面,如下图:我们需要记录密钥。有了apikey,我们就可以实现自动回复功能了。实现代码如下:importtime,logging,random,requestsfromqueueimportQueuefromWechatPCAPIimportWechatPCAPIlogging.basicConfig(level=logging.INFO)queue_recved_event=Queue()defon_message(msg):queue_recved_event.put(msg)#机器人返回消息defreply_msg(receive_msg):apikey='ownapikey'apiurl='http://www.tuling123.com/openapi/api?key=%s&info=%s'%(apikey,receive_msg)result=requests.get(apiurl)result.encoding='utf-8'data=result.json()returndata['text']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()if'msg::single'inmsg.get('type'):data=msg.get('data')ifdata.get('is_recv',False):msgfrominfo=data.get('msgfrominfo')如果msgfrominfo不是None:wx_id=msgfrominfo.get('wx_id')如果wx_id!='weixin':receive_msg=str(data.get('msgcontent'))reply=reply_msg(receive_msg)wx_inst.send_text(to_user=wx_id,msg=reply)看执行效果:完整代码在下面公众号后台回复200523得到
