node使用wechaty制作微信机器人每天给老婆发送暖心
发布: 2019-03-08 20:57:09标签: nodeJs
在掘金上看到了一篇文章,一直想自己写一份。终于在工作之余,抽时间自己写了一份。这里只展示主要代码,详细代码请到github仓库
很惭愧!一天之后就放弃了,平均8个小时微信自动掉线(github有推荐收费pad版,暂时不尝试了)(/ω\)
代码 github地址
核心代码 【登录微信】
01const qrcodeTerminal = require('qrcode-terminal')02const { Wechaty, Contact, Message, log } = require('wechaty')03const startSchedule = require('./schedule') // 定时任务 可以理解为一个function0405const bot = new Wechaty()0607let schedule0809// 二维码登录10bot.on('scan', (qrcode, status) => {11 if (status === 0) {12 qrcodeTerminal.generate(qrcode, { small: true }) // show qrcode on console13 }14 const qrcodeImageUrl = [15 'https://api.qrserver.com/v1/create-qr-code/?data=',16 encodeURIComponent(qrcode)17 ].join('')18 console.log(qrcodeImageUrl)19})20// 登录21bot.on('login', user => {22 console.log(`${user} 登录成功`)23 main()24})25// 登出26bot.on('logout', user => {27 console.log(`${user} 退出登录`)28 process.exit()29 if (schedule) schedule.stop()30})313233// 接受到信息34bot.on('message', async msg => {35 if (msg.self()) return3637 await msg.say(msg.text() || '我现在只能识别文字')38})3940// 登录成功之后的事情41async function main() {42 const girl = await bot.Contact.find('对应微信名字')4344 if (girl) {45 // await girl.say('想说的话') // 通过这种办法,发送微信消息46 /**47 * 自定义开始聊天48 **/49 schedule = startSchedule(girl) 50 }51}5253bot54 .start()55 .then(() => console.log('微信机器人启动成功'))56 .catch(console.error)57
复制代码定时任务 【天气预报、每日一句】 (schedule.js)
01const axios = require('axios')02const moment = require('moment')03const HourSchedule = require('./utils/HourSchedule')04const one = require('./spider/one.js')05const weather = require('./spider/weather')060708// 定时发送天气预报09async function tellWwather(...peopleList) {10 const text = await weather()11 for (let i = 0; i < peopleList.length; i++) {12 const people = peopleList[i]13 if (people) {14 people.say(text)15 }16 }17}1819// 定时发送每日一句20async function sayOne(...peopleList) {21 const text = await one()22 for (let i = 0; i < peopleList.length; i++) {23 const people = peopleList[i]24 if (people) {25 people.say(text)26 }27 }28}2930// 开始定时任务31module.exports = (gile) => {32 // 此处省略,自定义处理33}34
复制代码信息网站
参考技术
碰到问题
- centos服务器部署失败
01# https://github.com/Chatie/wechaty/issues/1515021.yum install libXScrnSaver*032.yum install epel-release043.yum install libappindicator-gtk3
复制代码