recime-bot-runtime
Version:
This runtime is intended to run inside a micro-service container with platform specific integration and module interpreter.
132 lines (131 loc) • 5.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var request = require("request");
var wechat_1 = require("../wechat");
var WeChat = /** @class */ (function () {
function WeChat(bot) {
this.bot = bot;
}
WeChat.prototype.send = function (message, filter) {
var _this = this;
var wechat = new wechat_1.WeChat(this.bot);
return wechat.accessToken().then(function (token) {
switch (message.type) {
case 'text': {
var payload = {
msgtype: message.type,
text: {
content: message.content
},
touser: filter
};
return _this.sendRequest(token, payload);
}
case 'audio':
case 'image':
case 'video': {
message.type = message.type === "audio" ? "voice" : message.type;
var media = function () {
if (message.media_id) {
return Promise.resolve({
media_id: message.media_id
});
}
return wechat.uploadMedia(message.url, message.type).then(function (data) {
if (data.media_id) {
return {
media_id: data.media_id
};
}
});
};
return media().then(function (file) {
var payload = {
msgtype: message.type,
touser: filter.length === 1 ? filter[0] : filter
};
payload[message.type] = file;
console.log(message.type, ' ', payload);
return _this.sendRequest(token, payload);
});
}
case 'news': {
return _this.uploadNews(token, (message.news.articles || []).map(function (article, idx) {
return {
title: article.title,
content_source_url: article.url,
thumb_media_id: article.thumb_media_id,
content: article.content,
digest: article.description,
show_cover_pic: idx === 0 ? 1 : 0
};
})).then(function (news) {
var payload = {
msgtype: 'mpnews',
mpnews: {
media_id: news.media_id
},
touser: filter.length === 1 ? filter[0] : filter
};
console.log('payload:', payload);
return _this.sendRequest(token, payload);
});
}
}
});
};
WeChat.prototype.uploadNews = function (token, articles) {
return new Promise(function (resolve, reject) {
request({
json: true,
method: "POST",
url: "https://api.weixin.qq.com/cgi-bin/material/add_news",
qs: {
access_token: token
},
body: {
articles: articles
}
}, function (err, response, body) {
if (err) {
console.error(err);
return reject(err);
}
if (body.errcode) {
return reject({
code: body.errcode,
message: body.errmsg
});
}
resolve(body);
});
});
};
WeChat.prototype.sendRequest = function (token, payload) {
return new Promise(function (resolve, reject) {
request({
json: true,
method: "POST",
url: "https://api.weixin.qq.com/cgi-bin/message/mass/" + (Array.isArray(payload.touser) ? 'send' : 'preview'),
qs: {
access_token: token
},
body: payload
}, function (err, response, body) {
if (err) {
console.error(err);
return reject(err);
}
if (body.errcode !== 0) {
return reject({
code: body.errcode,
message: body.errmsg
});
}
resolve(body);
});
});
};
return WeChat;
}());
exports.WeChat = WeChat;