salix/back/methods/chat/send.js

67 lines
1.9 KiB
JavaScript
Raw Normal View History

const axios = require('axios');
2020-01-20 06:33:24 +00:00
module.exports = Self => {
Self.remoteMethodCtx('send', {
description: 'Send a RocketChat message',
accessType: 'WRITE',
accepts: [{
arg: 'to',
2021-03-15 11:26:11 +00:00
type: 'string',
2020-01-20 06:33:24 +00:00
required: true,
2020-01-23 12:31:07 +00:00
description: 'User (@) or channel (#) to send the message'
2020-01-20 06:33:24 +00:00
}, {
arg: 'message',
2021-03-15 11:26:11 +00:00
type: 'string',
2020-01-20 06:33:24 +00:00
required: true,
description: 'The message'
}],
returns: {
2021-03-15 11:26:11 +00:00
type: 'object',
2020-01-20 06:33:24 +00:00
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);
2020-01-20 06:33:24 +00:00
};
2020-01-23 12:31:07 +00:00
async function sendMessage(sender, channel, message) {
/* if (process.env.NODE_ENV !== 'production') {
2020-01-20 06:33:24 +00:00
return new Promise(resolve => {
2021-03-15 11:26:11 +00:00
return resolve({
body: JSON.stringify(
{statusCode: 200, message: 'Fake notification sent'}
)
});
2020-01-20 06:33:24 +00:00
});
}
*/
const login = await Self.getServiceAuth();
2020-01-20 06:33:24 +00:00
const avatar = `${login.host}/avatar/${sender.name}`;
2020-01-23 12:31:07 +00:00
const options = {
headers: {
'X-Auth-Token': login.auth.token,
'X-User-Id': login.auth.userId
},
2020-01-23 12:31:07 +00:00
};
return axios.post(`${login.api}/chat.postMessage`, {
'channel': channel,
'avatar': avatar,
'alias': sender.nickname,
'text': message
}, options);
2020-01-20 06:33:24 +00:00
}
};