salix/back/methods/chat/send.js

70 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) {
await sendMessage(sender, to, message);
return true;
}
return false;
2020-01-20 06:33:24 +00:00
};
2020-01-23 12:31:07 +00:00
async function sendMessage(sender, channel, message) {
2022-02-23 11:07:05 +00:00
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({
2022-02-23 11:07:05 +00:00
statusCode: 200,
message: 'Fake notification sent'
2021-03-15 11:26:11 +00:00
});
2020-01-20 06:33:24 +00:00
});
}
2022-02-23 11:07:05 +00:00
const login = await Self.getServiceAuth();
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
}
};