How to send SMS (using Twilio channel) from Microsoft Bot Framework? - javascript

Currently my bot is on Facebook messenger, used by employees.
I'd like my bot to send one SMS to a person to welcome him / her to our team and with its credentials.
I know Microsoft Bot Framework integrates Twilio, so I integrated Twilio channel following this: https://learn.microsoft.com/en-us/bot-framework/channel-connect-twilio, so I have a phone, and everything is well configured because I can send manually SMS (from the Twilio's dashboard), it works.
Problem is that I don't know how to use it right now, in the bot.
const confirmPerson = (session, results) => {
try {
if (results.response && session.userData.required) {
// Here I want to send SMS
session.endDialog('SMS sent ! (TODO)');
} else {
session.endDialog('SMS cancelled !');
}
} catch (e) {
console.error(e);
session.endDialog('I had a problem while sending SMS :/');
}
};
How to achieve this ?
EDIT: Precision, the person welcoming employee is a coach, just sending SMS from bot with the credentials to use in the webapp the bot connects after first usage by the user welcomed

Twilio developer evangelist here.
You can do this in bot framework by sending an ad-hoc proactive message. It seems you'd need to create an address for the user that you want to send messages to though and I can't find in the documentation what an address should look like.
Since you're in a Node environment, you could use Twilio's API wrapper to this though. Just install twilio to your project with:
npm install twilio
Then gather your account credentials and use the module like so:
const Twilio = require('twilio');
const confirmPerson = (session, results) => {
try {
if (results.response && session.userData.required) {
const client = new Twilio('your_account_sid','your_auth_token');
client.messages.create({
to: session.userData.phoneNumber, // or whereever it's stored.
from: 'your_twilio_number',
body: 'Your body here'
}).then(function() {
session.endDialog('SMS sent ! (TODO)');
}).catch(function() {
session.endDialog('SMS could not be sent.');
})
} else {
session.endDialog('SMS cancelled !');
}
} catch (e) {
console.error(e);
session.endDialog('I had a problem while sending SMS :/');
}
};
Let me know how this goes.

Related

Gmail with Heroku to send mail

I want to add to my web app that after order I'm sending a mail.
I choose Nodemailer because it's the most famous npm to use.
I coded my request and in the local environment, it's working.
I uploaded the code to Heroku and I get an Error.
Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs
I checked people told me to disable the captcha wish I did here: UnlockCaptcha
And now I still get the same error, and I get a mail that google blocked the connection what can I do?
const nodemailer = require('nodemailer');
const { sendLog } = require('../middleware/sendLog');
const { coupons, actions } = require('../constant/actionCoupon');
var simple = function () {
var textMultiple = {
text1: 'text1',
text2: 'text2',
};
return textMultiple;
};
// send mail system for the (REQUEST ACCEPTED SYSTEM)
const sendMail = (mail, action) => {
let mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.MAIL,
pass: process.env.PASSWORD,
},
});
let mailDetails = {
from: process.env.MAIL,
to: mail,
subject: `Thank you for your purchase. with love FameGoal`,
text: "for any probleme please reply on this message",
};
mailTransporter.sendMail(mailDetails, function (err, data) {
if (err) {
console.log(err);
console.log(`error sent mail to ${mail}`, 'error');
} else {
console.log('succeed');
console.log(`succesfully sent mail to ${mail}`, 'info');
}
});
};
exports.sendMail = sendMail;
Using Gmail as an SMTP relay isn't the most ideal because Google servers may reject basic username/password authentication at times.
There are some workarounds. The most ideal is to use OAuth2 to send emails.
OAuth2
OAuth2 uses access tokens to perform authentication instead of a password.
I won't go over the steps to set up OAuth2 because it can take some time but if you're interested, this answer: https://stackoverflow.com/a/51933602/10237430 goes over all of the steps.
App passwords
If the Google account you're trying to send emails from has two step verification enabled, using a password to send emails will not work. You instead need to generate a app-specific password on Google's site and pass that in the password field.
More info on that here: https://support.google.com/accounts/answer/185833?hl=en
Enabling less secure apps
If you still want to use your current setup, you have to make sure you enable less secure apps on the Google account you're sending emails from. This will let you authenticate with Google using just an email and a password.
More info on that here: https://support.google.com/accounts/answer/6010255?hl=en
Basic password authentication will not work until you enable less secure apps.

Why can't I log into the Discord.js client?

This code isn't working, it never logs Ready! to the console. It's also not logging out any errors, so I believe it may have logged in correctly but just isn't working. Does anyone have any pointers?
var Discord = require("discord.js");
var client = new Discord.Client();
client.login('myEmail', 'myPassword', output);
client.on('ready', () => {
console.log("Ready!");
});
function output(error, token) {
console.log("errorz!");
if (error) {
console.log("There was an error logging in: ${error}");
return;
} else {
console.log("`Logged in. Token: ${token}`");
}
}
Just to make sure I am doing this right, I have put this in a file called discord-fisher.js and I am running it using node discord-fisher.js from the terminal.
Per the documentation for Discord.js for Client#login:
.login( token )
Logs the client in, establishing a websocket connection to Discord.
So when you use login, you don't provide your email or password details, you provide your API token associated with your account.

How to implement push notification support in Cordova app using Quickblox?

Apologies for such a basic question, but I really can't find any information on the subject.
The Quickblox Javascript SDK has some classes related to push notifications, and I have enabled them using chat_history and the alerting tab in chat. However what I don't understand is how to receive these notifications on the front end UI?
I don't have any code to share as I don't know where to start!
Any help would be truly appreciated, thank you.
There are modules to work with pushes:
QB.messages.tokens
QB.messages.subscriptions
QB.messages.events
To subscribe for pushes you have to do 2 things:
Create a push token using QB.messages.tokens
Create a subscription using QB.messages.subscriptions
Additional info can be found in REST API page http://quickblox.com/developers/Messages#Typical_use_.D1.81ases
Also you have to upload APNS and Google API key to QuickBlox admin panel.
This all needs if you are going to build Cordova app for iOS/Android
You need encode the message.
You need to make sure your mobile app would know to understand the decoded message.
For example,
sending push notification to android qb_user_id: 20290
(and from me - my qb_user_id: 12121):
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function send_push() {
var params = {
notification_type: 'push',
push_type: 'gcm',
user: {ids: [20290]},
environment: "production",
message: b64EncodeUnicode('{"message":"HELLO WORLD","user_id":12121,"device_type":"WEB","message_qb_id":"563a55a44cedaa83885724cf","message_type":"Text","send_status":"BeingProcessed","send_time":1446663588607}')
};
QB.messages.events.create(params, function(err, response) {
if (err) {
console.log("QB.messages.events.create::error:" +err);
} else {
console.log("QB.messages.events.create::response:" + response);
}
});
}
In this example, the mobile app is looking for a message in this format:
{"message","user_id","device_type","message_qb_id","message_type","send_status","send_time"}

Failed sending mail with googleapis' service account and JWT auth in nodejs

I'm trying to send an email using a service account and JWT authentication and keep getting and error with a very unhelpful message: { code: 500, message: null }
This code snippet is from the following StackOverflow link: Failed sending mail through google api in nodejs
It seems like the solution there was to change the key in the parameters to resource instead of message but it's not working for me. This is strange because in the JS example in the docs (https://developers.google.com/gmail/api/v1/reference/users/messages/send) it claims the key is still message
I'm authenticating with
var jwtClient = new google.auth.JWT(config.SERVICE_EMAIL, config.SERVICE_KEY_PATH, null, config.ALLOWED_SCOPES);
then sending an email with
jwtClient.authorize(function(err, res) {
if (err) return console.log('err', err);
var email_lines = [];
email_lines.push("From: \"Some Name Here\" <rootyadaim#gmail.com>");
email_lines.push("To: hanochg#gmail.com");
email_lines.push('Content-type: text/html;charset=iso-8859-1');
email_lines.push('MIME-Version: 1.0');
email_lines.push("Subject: New future subject here");
email_lines.push("");
email_lines.push("And the body text goes here");
email_lines.push("<b>And the bold text goes here</b>");
var email = email_lines.join("\r\n").trim();
var base64EncodedEmailSafe = new Buffer(email).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
var params = {
auth: jwtClient,
userId: "myaddress#gmail.com",
resource: {
raw: base64EncodedEmailSafe
}
};
gmail.users.messages.send(params, function(err, res) {
if (err) console.log('error sending mail', err);
else console.log('great success', res);
});
}
The comments in the library seem to say that resource is the correct property as well (https://github.com/google/google-api-nodejs-client/blob/master/apis/gmail/v1.js)
What am I missing?
According to #ryanseys on github
You cannot authorize Gmail API requests with JWT, you must use OAuth 2.0 because it needs to be auth'd to a specific user. Or else you'd be able to do some really shady things like send messages impersonating someone else. The Google APIs Explorer is authenticated with OAuth 2.0 that's why it works. See https://developers.google.com/gmail/api/auth/about-auth for more information.
As you can see in Failed sending mail through google api in nodejs, auth: OAuth2Client, they are using the OAuth2 client to authenticate. There is currently no way for you to send messages using the GMail API without authenticating as a specific GMail user. Service accounts do not have access to GMail the same way that regular users do.
Hopefully this helps someone else out there trying to use a service account to send mail!

I am trying to send a email in meteor with process.env and smtp gmail

I am using the following to send emails which works on localhost but not my server.
// server
Meteor.startup(function () {
process.env.MAIL_URL="smtp://uername%40gmail.com:password#smtp.gmail.com:465/";
});
I get the follow error in my logs(it seems like google is blocking it for some reason, is there a way to stop that?
[162.243.52.235] 534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 l10sm1017845qae.41 - gsmtp
at SMTPClient._actionAUTHComplete (/opt/meteor/app/programs/server/npm/email/main/node_modules/simplesmtp/lib/client.js:826:23)
at SMTPClient._onData (/opt/meteor/app/programs/server/npm/email/main/node_modules/simplesmtp/lib/client.js:329:29)
at CleartextStream.EventEmitter.emit (events.js:95:17)
at CleartextStream.<anonymous> (_stream_readable.js:746:14)
at CleartextStream.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at _stream_readable.js:401:7
at process._tickCallback (node.js:415:13)
This is the event that I think sends initiates the email sending. I know that meteor is now setup to use mailgun, is there a way to modify this to just use mailgun instead of meteor without process.env?
Template.forgotPassword.events({
'submit #forgotPasswordForm': function(e, t) {
e.preventDefault();
var forgotPasswordForm = $(e.currentTarget),
email = trimInput(forgotPasswordForm.find('#forgotPasswordEmail').val().toLowerCase());
if (isNotEmpty(email) && isEmail(email)) {
Accounts.forgotPassword({email: email}, function(err) {
if (err) {
if (err.message === 'User not found [403]') {
Session.set('alert', 'This email does not exist.');
} else {
Session.set('alert', 'We\'re sorry but something went wrong.');
}
} else {
Session.set('alert', 'Email Sent. Please check your mailbox to reset your password.');
}
});
}
return false;
},
'click #returnToSignIn': function(e, t) {
Session.set('showForgotPassword', null);
return false;
},
});
Packages already installed
You need to URL encode your username and password else Meteor confuses the two '#' signs with each other.
You could do this in your JS console (with encodeURIComponent(username)) and usually end up with something like
user%40gmail.com:password#smtp.gmail.com:465
You could use Mailgun in the same way, or Mandrill, or any other smtp provider. It's just the username format causing the issues.
I encountered a similar problem. The method send email work locally but not on the hosting modulus. For my part this was due to a blocking google security (access to my gmail account from Seattle while I live in France has probably seemed fishy to google). I went through several pages to authorize less strict connections to my gmail account.
On this page I saw the blockage. So I allowed the less secure applications and allowed access to my account.
If it helps someone ..
Just use the email package with
meteor add email
Then sending email will work. Mine works with port 587 in my config.
Meteor.startup(function () {
process.env.MAIL_URL = 'smtp://user%40gmail.com:password#smtp.gmail.com:587';
});

Categories

Resources