how to send formatted messages to rocketchat from hubot? - rocket.chat

I would like to prepare formatted messages to rocketchat from hubot but I can't find any reference for that.
That's my main reference:
http://theprogrammingbutler.com/blog/archives/2011/10/28/hubot-scripts-explained/
I have tried this:
msg.http(url)
.headers("PRIVATE-TOKEN": api_key, Accept: 'application/json')
.get() (err, response, body) ->
try
json = JSON.parse(body)
for issue in json
msg.send "#{issue.title}"
catch error
msg.send "Sistema not found."
console.log(error)
But I would like some more rich and elaborated.
Any sugestion ??
Thanks.

The hubot adapter for Rocket.Chat has a method called customMessage. You can include attachments like you would with slack to achieve rich messages.
To use customMessage use something like this:
robot.adapter.customMessage({
channel: room,
attachments: [
{
title: "New Event",
title_link: "http://example.com/event",
text: "<img src=\"http://example.com/picture\" width=\"20\" /> Event 1234: <br /> urgent event"
}
]
});

I had a similar need. What worked for me was using the image_url field, documented in the realtime API documentation:
module.exports = function(robot) {
robot.respond(/image/i, function(res) {
resposta = robot.adapter.customMessage({
channel: room,
attachments: [
{
title: "Image",
title_link: "http://www.example.com",
image_url: "http://www.example.com/image.png",
text: "This image"
}
]
});
});
};

Related

How to replay conversation through nodeJs using messagebird WhatsApp Business API?

How to test?
get started from this url: https://developers.messagebird.com/docs/whatsapp/getting-started/
var messagebird = require('messagebird')();
my code
messagebird.conversations.reply(data.id, {
'type': 'image',
'content': {
'image': {
'url': 'https://api.faridblaster.my/test',
'caption': 'Bocaahhh3332'
}
}
}, function (err, response) {
if (err) {
return console.log(err);
}
});
the result show me
Expected Output should be
status: 'delivered',
Thanks in advance!
Based on the provided examples, this is the expected status right after you are sending the message.
If you'd like to monitor the status changes for the message, you will have to register a webhook for the message.updated events and you'll get your updates in the reportURL (details here)

Send mail using Mailchimp's API

I created a mail campaign(chose "automated" and "API")
When I try to send a test mail
post: https://us20.api.mailchimp.com/3.0/campaigns/{my_campaign_id}/actions/test
I get a 400, "Cannot send this campaign because it is currently sending" error.
And in the dashboard I can see the status of the campaign is "Sending".
The edit mode of the campaign there is only an option to pause the campaign.
Here is the code(using Node.js) used to send the mail
const request = require('superagent');
request.post(`https://us20.api.mailchimp.com/3.0/campaigns/${CAMPAIGN_ID}/actions/test`)
.set('Content-Type', 'application/json;charset=utf-8')
.set('Authorization', 'Basic ' + new Buffer('any:' + MAILCHIMP_API_KEY).toString('base64'))
.send({
test_emails: [ 'my_mail#gmail.com' ],
send_type: 'html',
})
.end((error, response) => {
if (error) {
res.send({ error });
} else {
res.send({ data: response });
}
});
Could you guys point out how to fix the "sending" error.
Thanks.
According to the MailChimp automation documents you should first pauze the campaign before you can edit it's properties.
I guess you have to wait untill the campaign is done sending before you can send a testmail on it: https://mailchimp.com/help/troubleshooting-automations/.

Mandrill with parse server not working on heroku migration

I have migrate app from parse.com to heroku with mLab and everything works fine except cloud code.
I am using Mandrill for sending email from parse cloud code which is not working with heroku
Here is what I have done so far:
Installed mandrill ~0.1.0 into parse-server-example and push the code to heroku app
Put the cloud code into '/cloud/main.js'
Called the function from iOS app which respond error as:
[Error]: Invalid function. (Code: 141, Version: 1.13.0).
Here is my code script:
Parse.Cloud.define("sendMail", function(request, response) {
var Mandrill = require('mandrill');
Mandrill.initialize('xxxxxx-xxxxx');
Mandrill.sendEmail({
message: {
text: "ffff",
subject: "hello",
from_email: "xxxxx#gmail.com",
from_name: "pqr",
to: [
{
email: "xxxxxxxxxx#gmail.com",
name: "trump"
}
]
},
async: true
},{
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
});
But after calling 'sendMail' function I am getting this error:
[Error]: Invalid function. (Code: 141, Version: 1.13.0).
================================== MailGun ==========================
Parse.Cloud.define('hello', function(req, res) {
var api_key = 'key-xxxxxxxxxxxxxx';
var domain = 'smtp.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'xxxxxxxald#gmail.com',
to: 'xxxxx8#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
//res.success(req.params.name);
});
I had a similar problem with sendgrid, but I finally find a way around the problem.
I think this steps may help you,
Miss some brackets or some code separator? ( try rewritting the entire code in the main.js )
The app is actually running? ( when you type "heroku open" in the terminal you get the default message? ) - if not check step 1.
If the previous are not working, rollback to a safe build and Add the add-ons in the heroku dashboard instead of installing them yourself, then download the git and do any changes to git and then push.
Below I have pasted from cloud code main.js code that is working using Mandrill on heroku parse application to send password recovery e-mail.
in cloud code main.js:
var mandrill_key = process.env.MANDRILL_KEY;
var Mandrill = require('mandrill-api/mandrill');
var mandrill_client = new Mandrill.Mandrill(mandrill_key);
{
success: function(gameScore) {
//alert('New object created with objectId: ' + gameScore.id);
mandrill_client.messages.send(
{
message: {
html: "<p>Hello " + firstUser.get('fullname') + ",</p><p>We received your request to reset your password.</p><p>Your user name is <strong>" + firstUser.get('username') + "</strong>. Please click here to create a new password. This link will expire in one hour after this mail was sent</p><p>If you need additional help, just let us know.</p><p>SampleCompany Support<br>customerservice#example.com</p><p>Copyright Sample Company, Inc. 2014-2017</p>",
subject: "Sample Company Name account recovery",
from_email: "customerservice#example.com",
from_name: "Sample Company Name",
to: [
{
email: firstUser.get('email'),
name: firstUser.get('fullname')
}
]
},
async: true
},
//Success
function(httpResponse) {
console.log(httpResponse);
//alert("Email sent!");
},
//Failure
function(httpResponse) {
console.error(httpResponse);
//alert("Uh oh, something went wrong");
});
},
error: function(gameScore, error) {
console.error(error.message);
//alert('Failed to create new object, with error code: ' + error.message);
},
useMasterKey: true
})

slack api rtm direct message

I'm using a node package: slack-client to interact with the api at slack. Now with or without using slack-client how do I send a direct message from my bot to a user I want to specify? Here's what have so far with a plain socket connection:
var WebSocket = require('ws')
,ws2 = new WebSocket(myURL); //from rtm start
ws2.on('open', function() {
ws2.send({
"id": 333,
"type": "message",
"channel": "#user1", //User I want to send to
"text": "HEY!!!!"
});
});
ws2.on('message', function(message) {
console.log('received: %s', message);
});
I was hoping that message would go directly to me from the bot but nothing. I get a reply of type hello though? The send details above I got on another post about this but it doesn't work for me. The message Id was one I created.
Ok so when calling the rtm.start via the web api, you would get a list of DM's that would be open for various users otherwise you can easily just open an im with im.open. I'm using the node package slack-client as mentioned in my question so you can do this:
//name of user your bot wants to send a msg to.
var userTest = slack.getUserByName('user1');
slack.openDM(userTest.id, function(res)
{
TestMsg(res.channel.id, 'some other msg');//test function I'm using
});
Next is the TestMsg function:
function TestMsg(userChannelId, msg)
{
request.post({url: 'https://slack.com/api/chat.postMessage',
form: { token: "xxxx-yourbot-token",channel: userChannelId,text: msg ,username: "yourBotNamehere", as_user: false}
}, function(error, response, body){
console.log(response.body);
});
}
I couldn't get it to work yet using the websockets send method but I suppose the api of postMessage will do for now as you can post richly formatted messages with postMessage. Hope this helps someone

How can I read a local file in Cloud Code as a string?

I'm using Parse Cloud Code.
My system has a welcome message. I use MailGun to send it.
The problem I have is that the message now is an HTML file, so I would like to let the HTML file in my server, read it using Cloud Code and pass that info to MailGun.
Can I read a local text file using Cloud Code and have it in my program as a string?
Should I save that file in my public folder or in the same folder than my cloudcode program?
I'm not confident with MailGun, but I believe it should work like MailChimp or Mandrill. If so, you should be able to store on MailGun your whole HTML template and just have some template_vars to complete.
This is a sample code of our own way to send mail with HTML thanks to the Mandrill system
Parse.Cloud.define("sendMailTemplate", function(request, response) {
var emails = request.params.emails;
var template_name = request.params.template_name;
var template_merge_content = request.params.template_merge_content;
var subject = request.params.subject;
var Mandrill = require('cloud/mandrillTemplateSend.js');
if (subject === undefined) {
subject = 'Mail sent by Mandrill';
body = subject;
}
Parse.Config.get().then(function(config) {
Mandrill.initialize(config.get('Mandrill_key'));
}).then(function() {
_.each(emails, function(email) {
Mandrill.sendTemplate({
template_name: template_name,
template_content: [{
name: template_merge_content.username,
content: ''
}],
message: {
text: '',
subject: subject,
from_email: 'contact#yourdomain.com',
to: [{
email: email,
name: template_merge_content.username
}],
merge_vars: [{
rcpt: email,
vars: template_merge_content
}],
},
async: false
});
});
}).then(function() {
response.success('Success');
}, function(error) {
response.error(error);
});
});
This object template_merge_content is quiet important. It's an object where is saved all the dynamic vars which are send to complete your HTML mail.
According to http://blog.mailgun.com/transactional-html-email-templates/ it seems you have same kind of method to send your mail.
So final advice would be to NOT store your HTML template within any Parse's class, or to save it within https://parse.com/docs/js/api/symbols/Parse.Config.html

Resources