为了迎接即将到来的春节, 我研究了下微信机器人相关
1.wechaty
JS操作个人微信的一个库
github:https://github.com/Chatie/wechaty

2.环境配置
由于这个库用到了puppeteer, 所以需要下载chromium, 国内有点麻烦, 所以官方给了解决方法
https://github.com/Chatie/wechaty-puppet-puppeteer#note-for-developers-in-china
npm
user
npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist
npm config set puppeteer_download_host https://npm.taobao.org/mirrors
then you can check your $HOME/.npmrc
yarn
user
yarn config set registry https://registry.npm.taobao.org
yarn config set disturl https://npm.taobao.org/dist
yarn config set puppeteer_download_host https://npm.taobao.org/mirrors
3.安装
$ npm init
$ npm install wechaty --save
4.群发程序
const {
Contact,
log,
Wechaty
} = require('wechaty')
const contactArr = require('./contactArr').contactArr // 自己定义的, 指定群发对象的数组
// 定义
const bot = new Wechaty({
name: 'zzes-wechat-bot'
})
// 注册事件
bot
.on('login', onLogin) // 登录回调
.on('logout', onLogout) // 登出回调
.on('scan', onScan) // 扫描二维码回调
.on('error', onError) // 错误回调
.on('message', onMessage) // 接收信息回调
// 启动
bot
.start()
.catch(async e => {
console.error('bot start fail: ', e)
await bot.stop()
process.exit(-1)
})
// 事件定义
// 扫码
function onScan (qrcode, status) {
require('qrcode-terminal').generate(qrcode, { small: true }) // show qrcode on console
const qrcodeImageUrl = [
'https://api.qrserver.com/v1/create-qr-code/?data=',
encodeURIComponent(qrcode),
].join('')
console.log(qrcodeImageUrl)
}
// 登录
function onLogin (user) {
console.log(`${user.name()} login`)
bot.say('Wechaty login').catch(console.error)
main() // 群发
}
function onLogout (user) {
console.log(`${user.name()} logouted`)
}
function onError (e) {
console.error('bot error:', e)
}
// 接收信息
async function onMessage (msg) {
console.log(msg.toString())
}
/**
* 群发函数
*/
async function main() {
// 此处注意, 由于网页版获取完整的好友列表需要一定时间, 需要加一点延时, 再获取
setTimeout(function(){
contactArr.forEach(async (v) => {
const contact = await bot.Contact.find({alias: v}) // 通过配置的备注寻找好友
await contact.say(`${v}, 怎么样, 加入治电, 投入学习吧!`) // 带备注发消息
})
},6000);
}
可维护的群发列表 contactArr.js
const contactArr = [
'张三', '李四'
]
exports.contactArr = contactArr
5.参考资料
- wechaty文档: https://chatie.io/wechaty/
网友评论