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') // 定时任务 可以理解为一个function
04
05const bot = new Wechaty()
06
07let schedule
08
09// 二维码登录
10bot.on('scan', (qrcode, status) => {
11 if (status === 0) {
12 qrcodeTerminal.generate(qrcode, { small: true }) // show qrcode on console
13 }
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})
31
32
33// 接受到信息
34bot.on('message', async msg => {
35 if (msg.self()) return
36
37 await msg.say(msg.text() || '我现在只能识别文字')
38})
39
40// 登录成功之后的事情
41async function main() {
42 const girl = await bot.Contact.find('对应微信名字')
43
44 if (girl) {
45 // await girl.say('想说的话') // 通过这种办法,发送微信消息
46 /**
47 * 自定义开始聊天
48 **/
49 schedule = startSchedule(girl)
50 }
51}
52
53bot
54 .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')
06
07
08// 定时发送天气预报
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}
18
19// 定时发送每日一句
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}
29
30// 开始定时任务
31module.exports = (gile) => {
32 // 此处省略,自定义处理
33}
34
复制代码

信息网站

参考技术

  • wechaty
    一个微信开发的库,收发信息,添加好友等等。
  • 入门DEMO
    github上wechaty入门代码,里边有多个等级
  • cheerio
    像jquery一样解析html的库

碰到问题

  • centos服务器部署失败
01# https://github.com/Chatie/wechaty/issues/1515
021.yum install libXScrnSaver*
032.yum install epel-release
043.yum install libappindicator-gtk3
复制代码