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) { await sendMessage(sender, to, message); return true; } return false; }; 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); } };