65 lines
1.8 KiB
JavaScript
65 lines
1.8 KiB
JavaScript
const axios = require('axios');
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('send', {
|
|
description: 'Send a RocketChat message',
|
|
accessType: 'WRITE',
|
|
accepts: [{
|
|
arg: 'to',
|
|
type: 'string',
|
|
required: true,
|
|
description: 'User (@) or channel (#) to send the message'
|
|
}, {
|
|
arg: 'message',
|
|
type: 'string',
|
|
required: true,
|
|
description: 'The message'
|
|
}],
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/send`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.send = async(ctx, to, message) => {
|
|
const models = Self.app.models;
|
|
const accessToken = ctx.req.accessToken;
|
|
const sender = await models.Account.findById(accessToken.userId);
|
|
const recipient = to.replace('@', '');
|
|
|
|
if (sender.name != recipient)
|
|
return sendMessage(sender, to, message);
|
|
};
|
|
|
|
async function sendMessage(sender, channel, message) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
return new Promise(resolve => {
|
|
return resolve({
|
|
statusCode: 200,
|
|
message: 'Fake notification sent'
|
|
});
|
|
});
|
|
}
|
|
|
|
const login = await Self.getServiceAuth();
|
|
const avatar = `${login.host}/avatar/${sender.name}`;
|
|
|
|
const options = {
|
|
headers: {
|
|
'X-Auth-Token': login.auth.token,
|
|
'X-User-Id': login.auth.userId
|
|
},
|
|
};
|
|
|
|
return axios.post(`${login.api}/chat.postMessage`, {
|
|
'channel': channel,
|
|
'avatar': avatar,
|
|
'alias': sender.nickname,
|
|
'text': message
|
|
}, options);
|
|
}
|
|
};
|