nodejs发送微信消息
时间: 2023-07-10 17:11:36 浏览: 63
可以使用第三方库wechaty来实现Node.js发送微信消息。具体步骤如下:
1. 安装wechaty库
使用npm安装wechaty库:
```
npm install wechaty
```
2. 注册微信机器人账号
使用微信账号登录[网页版微信](https://wx.qq.com/),并扫描二维码登录。
3. 编写代码
```javascript
const { Wechaty } = require('wechaty')
const bot = new Wechaty()
bot.on('scan', (qrcode, status) => {
console.log(`Scan QR Code to login: ${status}\nhttps://wechaty.js.org/qrcode/${encodeURIComponent(qrcode)}`)
})
bot.on('login', user => {
console.log(`Login user: ${user}`)
})
bot.on('message', async message => {
if (message.type() === bot.Message.Type.Text) {
console.log(`Received message: ${message}`)
// 发送微信消息
await message.say('Hello, I am a Wechaty bot!')
}
})
bot.start()
.then(() => console.log('Wechaty bot started.'))
.catch(e => console.error(e))
```
4. 运行代码
在终端中执行以下命令运行代码:
```
node index.js
```
5. 测试发送消息
使用其他微信账号向机器人账号发送文本消息,机器人账号会自动回复“Hello, I am a Wechaty bot!”。
注意:使用Wechaty发送微信消息需要先添加好友,否则发送消息会失败。