当前位置: 首页 > 后端技术 > Node.js

用Node+wechaty写一个爬虫脚本每天定时给女朋友发暖心微信消息

时间:2023-04-04 00:51:44 Node.js

使用Node+wechaty写一个爬虫脚本。每天定时给女朋友发暖心的微信吧之后偶然在评论区看到有读者问我们能不能用微信来实现。然后正好最近在做一个微信机器人小项目,就把这个定时任务放到微信上去做,说了就做,搞了一个下午终于搞定了。项目地址github:https://github.com/gengchen528/wechatBot使用库wechaty-微信操作node-schedule-定时任务superagent-抓取页面信息cheerio-抓取页面qrcode-terminal-终端显示二维码功能定时好友发送每日天气提醒、每日语句根据关键词自动加好友、自动拉群功能。继续展开……(有好的想法也可以提一下pr)每日语句的数据来源和上面大佬一样也是来自墨迹WeatherTimingtasknode-schedule的一个天气信息就是你。你可以安排每个月、每周、每天执行什么任务来达到效果。由于微信是定时发消息的,与邮件相比,微信无法将图片和文字放在同一个消息框里,所以在美观上可能不如邮件,但文字排版后还是可以的。由于时间仓促,文字比较少,以后会继续补充内容;代码说明目录结构config:存储公共变量和superagent的配置schedule:任务调度的配置superagent:获取每日语句和天气信息发送信息全部在这个文件里/***WechatBot*-https://github.com/gengchen528/wechatBot*/const{Wechaty,Friendship}=require('wechaty')constschedule=require('./schedule/index')constconfig=require('./config/index')constuntils=require('./untils/index')constsuperagent=require('./superagent/index')//二维码生成函数onScan(qrcode,status){require('qrcode-terminal').generate(qrcode)//在控制台显示二维码constqrcodeImageUrl=['https://api.qrserver.com/v1/create-qr-code/?data=',encodeURIComponent(qrcode),.join('')console.log(qrcodeImageUrl)}//登录异步函数onLogin(user){console.log(`贴心小助手${user}已登录`)//登录后创建定时任务schedule.setSchedule(config.SENDDATE,()=>{console.log('您的贴心小助手开始工作了!')main()})}//logoutfunctiononLogout(user){console.log(`${user}logout`)}//自动添加群组功能asyncfunctiononMessage(msg){constcontact=msg.from()//Messagesenderconstcontent=msg.text()//消息内容constroom=msg.room()//是否是群消息if(room){console.log(`群名:${room.topic()}发件人:${contact.name()}内容:${content}`)}else{console.log(`发件人:${contact.name()}消息内容:${content}`)}if(msg.self()){return}if(/微信天天说|天天说|微信机器人/.test(content)){letkeyRoom=awaitthis.Room.find({topic:/^微信天天说/i})if(keyRoom){try{awaitkeyRoom.add(contact)awaitkeyRoom.say('微信天天说:欢迎新朋友',contact)}catch(e){console.error(e)}}}}//自动添加朋友功能异步功能iononFriendShip(friendship){letlogMsgtry{logMsg='Addfriend'+friendship.contact().name()console.log(logMsg)switch(friendship.type()){/****1.新朋友请求**设置请求后,我们可以从`request.hello`获取验证消息,*并通过`request.accept()`接受此请求*/caseFriendship.Type.Receive:if(/微信dailysay|微信机器人|WeChat|dailytalk/i.test(friendship.hello())){logMsg='自动添加好友,因为验证信息中包含关键字'dailytalk''awaitfriendship.accept()}else{logMsg='失败验证'+friendship.hello()}break/****2.FriendShipConfirmed**/caseFriendship.Type.Confirm:logMsg='friendshipconfirmedwith'+friendship.contact().name()break}}catch(e){logMsg=e.message}console.log(logMsg)}//自动消息发送函数asyncfunctionmain(){letcontact=awaitbot.Contact.查找({名称:config.NICKNAME})||awaitbot.Contact.find({alias:config.NAME})//获取要发送的联系人letone=awaitsuperagent.getOne()//获取每日一句话letweather=awaitsuperagent.getWeather()//获取天气信息lettoday=awaituntils.formatDate(newDate())//获取今天的日期letmemorialDay=untils.getDay(config.MEMORIAL_DAY)//获取阵亡将士纪念日的天数letstr=today+'
'+'今天是我们在一起的第一天'+memorialDay+'day'+'

了解今天的天气

'+weather.weatherTips+'

'+weather.todayWeather+'今日一句话:

'+one+'

'+'-----来自最爱你的我'awaitcontact.say(str)//发送消息}constbot=newWechaty()bot.on('scan',onScan)bot.on('login',onLogin)bot.on('logout',onLogout)bot.on('message',onMessage)bot.on('friendship',onFriendShip)bot.start().then(()=>console.log('开始登录微信')).catch(e=>console.error(e))superagent/index.jsconstsuperagent=require('../config/superagent')constconfig=require('../config/index')constcheerio=require('cheerio')asyncfunctiongetOne(){//获取每日一句话letres=awaitsuperagent.req(config.ONE,'GET')let$=cheerio.load(res.text)让todayOneList=$('#carousel-one.carousel-inner.item')让todayOne=$(todayOneList[0]).find('.fp-one-cita').text().replace(/(^\s*)|(\s*$)/g,"")returntodayOne;}asyncfunctiongetWeather(){//获取墨迹天气leturl=config.MOJI_HOST+config.CITY+'/'+config.位置letres=awaitsuperagent.req(url,'GET')let$=cheerio.load(res.text)letweatherTips=$('.wea_tipsem').text()consttoday=$('.forecast.days').first().find('li');让todayInfo={Day:$(today[0]).text().replace(/(^\s*)|(\s*$)/g,""),WeatherText:$(today[1]).text().replace(/(^\s*)|(\s*$)/g,""),Temp:$(today[2]).text().replace(/(^\s*)|(\s*$)/g,""),风:$(今天[3]).find('em').text().replace(/(^\s*)|(\s*$)/g,""),WindLevel:$(today[3]).find('b').text().replace(/(^\s*)|(\s*$)/g,""),污染等级:$(today[4]).find('strong').text().replace(/(^\s*)|(\s*$)/g,"")}letobj={weatherTips:weatherTips,todayWeather:todayInfo.Day+':'+todayInfo.WeatherText+'
'+'Temperature:'+todayInfo.Temp+'
'+todayInfo.Wind+todayInfo.WindLevel+'
'+'Air:'+todayInfo.PollutionLevel+'
'}returnobj}module.exports={getOne,getWeather}由于项目需要安装chromium,所以需要先配置镜像。注意,由于wechaty的限制,最好使用node10以上npmnpmconfigsetregistryhttps://registry.npm.taobao.orgnpmconfigsetdisturlhttps://npm.taobao.org/distnpmconfigsetpuppeteer_download_hosthttps://npm.taobao.org/mirrorsyarnyarn配置设置注册表https://registry.npm.taobao.orgyarn配置设置disturlhttps://npm.taobao.org/distyarn配置设置puppeteer_download_hosthttps://npm.taobao。org/mirrors然后进行项目安装gitclonegit@github.com:gengchen528/wechatBot.gitcdwechatBotnpminstallorcnpminstall参数配置wechatBot/config/index.js//配置文件//配置Filemodule.exports={ONE:'http://wufazhuce.com/',//ONE网页版网站MOJI_HOST:'https://tianqi.moji.com/weather/china/',//中文墨迹天气urlCITY:'shanghai',//收件人城市LOCATION:'pudong-new-district',//收件人所在地区MEMORIAL_DAY:'2015/04/18',//你和收件人的纪念日NAME:'Leo_chen',//WeChatnotenameNICKNAME:'Leo_chen',//微信昵称SENDDATE:'30*****',//预定发送时间,规则见/schedule/index.js}开始运行npmrunstart然后取出你的手机,最好用小号,扫描控制台二维码即可解决由于微信登录不同于邮箱登录,进程守护工具不能使用。目前暂时没有测试看是否可以长时间登录,因为node出现错误可能会导致任务无法执行。最好用小号登录,如果是普通的微信登录,在电脑客户端登录后,wechaty可能会把天气页面挤出墨迹。有时可能会有延迟,有时您可能无法获得后续功能。为了防止你的微信被占用,你和你的爱人加我微信,你们发指定内容。我每天都会给你发消息,我还在想。……(大家也可以提出自己的好点子)最后,因为这个微信增加了自动加好友和拉群的功能,有兴趣的朋友可以加我微信测试一下,加好友的时候记得带上。密码:WechatDaily说了,加好友发送入群后,会自动发送群二维码;注意,加好友的时候,请填写微信每日验证中说可以自动加好友赶紧自己试试吧,相信你会挖掘出更多好玩的功能github:https://github.com/gengchen528/微信机器人