目标是开发一个简易机器人,能接收消息并作出回复。
企业信息页面链接地址:https://work.weixin.qq.com/wework_admin/frame#profile
配置消息服务器配置
获取 agentId 和 Secret 信息
创建 .env 配置文件配置企业微信机器人应用的配置信息
corpId=
corpSecret=
agentId=
配置应用消息:https://developer.work.weixin.qq.com/document/path/90236
请求方式 | POST(HTTPS) |
请求地址 | https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN |
机器人应用支持推送文本、图片、视频、文件、图文等类型。
配置 POST 请求参数
config.js 配置
const request = require('request')
const { config } = require('dotenv')
config()
const corpId = process.env.corpId
const corpSecret = process.env.corpSecret
const agentId = parseInt(process.env.agentId)
const toUser = '@all'
const tokenUrl = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${corpSecret}`
const sendMsgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
function getToken(success, error) {
request(tokenUrl, function(error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
console.log(json)
success(json.access_token)
} else {
error('Token in error.')
}
})
}
function sendMessage(token, content) {
const requestData = {
touser: toUser,
msgtype: "text",
agentid: agentId,
safe: 0,
text: {
content: content
}
}
request({
url: `${sendMsgUrl}${token}`,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: requestData
}, function(error, response, body) {
console.log(body)
if (!error && response.statusCode == 200) {}
});
}
function sendText(content) {
getToken((token) => {
sendMessage(token, content)
}, (error) => {
console.log(error)
})
}
module.exports = {
sendText,
}
npm 下载 node-schedule 定时任务模块
npm install node-schedule
配置定时发送任务
const alarmWechat = require('./config.js')
const schedule = require('node-schedule')
const scheduleTask = ()=> {
schedule.scheduleJob('30 * * * * *',() =>{
console.log('scheduleCronstyle:' + new Date());
alarmWechat.sendText('testmessage')
});
}
scheduleTask();
下载安装 axios 库
npm install axios
创建 .env 环境变量配置文件
HOOKURL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=【密钥】
具体实现
const axios = require("axios")
const { config } = require("dotenv")
config()
let data = {
msgtype: "text",
text: {
content: "helloworld"
}
}
axios.post(hookurl, data, {
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})