wechatBot微信每日说,每日自动发送微信消息给你心爱的人项目介绍灵感来源在掘金看到了一篇《用Node + EJS写一个爬虫脚本每天定时女朋友发一封暖心邮件》后,在评论区偶然看到一位读者说可不可以用微信实现一下。然后最近刚好在做微信机器人的小项目,那就把这个定时任务放到微信上去做吧,说干就干,撸了一下午终于撸出来了。项目地址github:https://github.com/gengchen528/wechatBot使用库wechaty - 微信操作node-schedule - 定时任务superagent - 爬取页面信息cheerio - 抓取页面qrcode-terminal - 终端显示二维码功能定时给朋友发送每日天气提醒以及每日一句根据关键词自动加好友和自动拉群功能后续继续扩展吧…(你有好的想法也可以提pr)数据来源每日一句和上面的大佬一样也是来自one天气信息来自墨迹天气定时任务node-schedule非你莫属了,可以定时每个月、每个礼拜、每天具体什么时候执行什么任务实现效果由于是微信定时发送消息,较邮件来说,微信无法把图片和文字放在同一消息框中,所以美观度来说可能没有邮件好,不过文字进行排版后还是可以的,由于时间仓促,所以文字比较少,后续会继续增加内容;代码说明目录结构config: 存放公共变量和superagent的配置schedule: 任务调度的配置superagent: 获取每日一句和天气信息untils: 抽取的共用方法核心代码index.js关于微信的登录,定时任务的创建,发送信息的获取都在这个文件里/** * WechatBot * - https://github.com/gengchen528/wechatBot /const {Wechaty,Friendship} = require(‘wechaty’)const schedule = require(’./schedule/index’)const config = require(’./config/index’)const untils = require(’./untils/index’)const superagent = require(’./superagent/index’)// 二维码生成function onScan (qrcode, status) { require(‘qrcode-terminal’).generate(qrcode) // 在console端显示二维码 const qrcodeImageUrl = [ ‘https://api.qrserver.com/v1/create-qr-code/?data=’, encodeURIComponent(qrcode), ].join(’’) console.log(qrcodeImageUrl)}// 登录async function onLogin (user) { console.log(贴心小助理${user}登录了) // 登陆后创建定时任务 schedule.setSchedule(config.SENDDATE,()=>{ console.log(‘你的贴心小助理开始工作啦!’) main() })}//登出function onLogout(user) { console.log(${user} 登出)}// 自动加群功能async function onMessage (msg) { const contact = msg.from() // 发消息人 const content = msg.text() //消息内容 const room = msg.room() //是否是群消息 if(room){ console.log(群名: ${room.topic()} 发消息人: ${contact.name()} 内容: ${content}) }else { console.log(发消息人: ${contact.name()} 消息内容: ${content}) } if (msg.self()) { return } if(/微信每日说|每日说|微信机器人/.test(content)){ let keyRoom = await this.Room.find({topic: /^微信每日说/i}) if(keyRoom){ try{ await keyRoom.add(contact) await keyRoom.say(‘微信每日说:欢迎新朋友 ‘, contact) }catch (e) { console.error(e) } } }}// 自动加好友功能async function onFriendShip(friendship) { let logMsg try { logMsg = ‘添加好友’ + friendship.contact().name() console.log(logMsg) switch (friendship.type()) { /* * * 1. New Friend Request * * when request is set, we can get verify message from request.hello, * and accept this request by request.accept() / case Friendship.Type.Receive: if (/微信每日说|微信机器人|微信|每日说/i.test(friendship.hello())) { logMsg = ‘自动添加好友,因为验证信息中带关键字‘每日说’’ await friendship.accept() } else { logMsg = ‘没有通过验证 ’ + friendship.hello() } break /* * * 2. Friend Ship Confirmed * / case Friendship.Type.Confirm: logMsg = ‘friend ship confirmed with ’ + friendship.contact().name() break } } catch (e) { logMsg = e.message } console.log(logMsg)}// 自动发消息功能async function main() { let contact = await bot.Contact.find({name:config.NICKNAME}) || await bot.Contact.find({alias:config.NAME}) // 获取你要发送的联系人 let one = await superagent.getOne() //获取每日一句 let weather = await superagent.getWeather() //获取天气信息 let today = await untils.formatDate(new Date())//获取今天的日期 let memorialDay = untils.getDay(config.MEMORIAL_DAY)//获取纪念日天数 let str = today + ‘<br>’ + ‘今天是我们在一起的第’ + memorialDay + ‘天’ + ‘<br><br>今日天气早知道<br><br>’ + weather.weatherTips +’<br><br>’ +weather.todayWeather+ ‘每日一句:<br><br>’+one+’<br><br>’+’——来自最爱你的我’ await contact.say(str)//发送消息}const bot = new Wechaty()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.jsconst superagent = require(’../config/superagent’)const config = require(’../config/index’)const cheerio = require(‘cheerio’)async function getOne() { // 获取每日一句 let res = await superagent.req(config.ONE,‘GET’) let $ = cheerio.load(res.text) let todayOneList = $(’#carousel-one .carousel-inner .item’) let todayOne = $(todayOneList[0]).find(’.fp-one-cita’).text().replace(/(^\s)|(\s*$)/g, “”) return todayOne;}async function getWeather() { //获取墨迹天气 let url = config.MOJI_HOST+config.CITY+’/’+config.LOCATION let res = await superagent.req(url,‘GET’) let $ = cheerio.load(res.text) let weatherTips = $(’.wea_tips em’).text() const today = $(’.forecast .days’).first().find(’li’); let 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, “”), Wind:$(today[3]).find(’em’).text().replace(/(^\s*)|(\s*$)/g, “”), WindLevel:$(today[3]).find(‘b’).text().replace(/(^\s*)|(\s*$)/g, “”), PollutionLevel:$(today[4]).find(‘strong’).text().replace(/(^\s*)|(\s*$)/g, “”) } let obj = { weatherTips:weatherTips, todayWeather:todayInfo.Day + ‘:’ + todayInfo.WeatherText + ‘<br>’ + ‘温度:’ + todayInfo.Temp + ‘<br>’ + todayInfo.Wind + todayInfo.WindLevel + ‘<br>’ + ‘空气:’ + todayInfo.PollutionLevel + ‘<br>’ } return obj}module.exports ={ getOne,getWeather}项目运行由于需要安装chromium, 所以要先配置一下镜像,注意由于wechaty的限制,最好使用node10以上版本npmnpm config set registry https://registry.npm.taobao.orgnpm config set disturl https://npm.taobao.org/distnpm config set puppeteer_download_host https://npm.taobao.org/mirrorsyarnyarn config set registry https://registry.npm.taobao.orgyarn config set disturl https://npm.taobao.org/distyarn config set puppeteer_download_host https://npm.taobao.org/mirrors然后进行项目安装git clone git@github.com:gengchen528/wechatBot.gitcd wechatBotnpm install 或 cnpm install参数配置wechatBot/config/index.js// 配置文件// 配置文件module.exports ={ ONE:‘http://wufazhuce.com/',//ONE的web版网站 MOJI_HOST:‘https://tianqi.moji.com/weather/china/', //中国墨迹天气url CITY:‘shanghai’,//收信者所在城市 LOCATION:‘pudong-new-district’,//收信者所在区 MEMORIAL_DAY:‘2015/04/18’, //你和收信者的纪念日 NAME:‘Leo_chen’,//微信备注姓名 NICKNAME:‘Leo_chen’, //微信昵称 SENDDATE:‘30 * * * * *’,//定时发送时间,规则见 /schedule/index.js}开始运行npm run start然后掏出你的手机,最好使用小号,扫描控制台的二维码即可待解决问题由于微信登录和邮件登录不同,所以无法使用进程守护工具,目前没有测试是否能够长时间登录因为node的原因,如果发生错误,可能会导致任务无法进行,需要手动重启并登录最好能够使用小号登录,如果是常用微信登录,在电脑客户端登陆后可能会wechaty挤掉墨迹天气页面在获取的时候可能会存在延时,有时可能获取不到后续功能为了防止占用你的微信号,你和你的爱人添加我的微信后。你发送指定内容,我将会每天帮你发送消息还有在思考中…(你有好的想法也可以提出来)最后因为给这个微信加了自动加好友和拉群功能,所以有兴趣的小伙伴可以加我的微信进行测试,记得在加好友的时候带上暗号:微信每日说,然后发送微信每日说我会把你拉到群中(由于wechaty网页接口变更,目前自动拉群功能,免费版已经不能使用,只可以自动加好友,不过我会手动拉你进群 ????)赶快亲自试一试吧,相信你会挖掘出更多好玩的功能github:https://github.com/gengchen528/wechatBot
...