Sinch API JS, instant messaging. User creation is disabled for this application - sinch

I'm trying to create user for start instant messaging
$('button#register').on('click', function(event){
event.preventDefault();
$('button#register').attr('disabled', true);
clearError();
var signUpObj = {};
signUpObj.username = $('input#username').val();
signUpObj.password = $('input#password').val();
sinchClient.newUser(signUpObj, function(ticket) {
sinchClient.start(ticket, function() {
global_username = signUpObj.username;
localStorage[sessionName] = JSON.stringify(sinchClient.getSession());
}).fail(handleError);
}).fail(handleError);
})
But I'm receiving error message
errorCode: 40303
message: User creation is disabled for this application
So, what I should done?

In the dashboard of you app (sinch.com/dashboard), enable js auth

Related

Sending message from Cognito triggers

I want to restrict user sign-ins from Cognito hosted UI. I can see there are triggers in which we can attach lambda, but whenever I change event object inside of lambda, instead of getting my custom message User exceeded limits, I get unrecognizable lambda output error.
Can anyone help me in this or is there any other way to achieve this functionality?
Now,I'm getting this
with this code :
exports.handler = (event, context, callback) => {
if (true) {
var error = new Error("Cannot signin because your signin count is 5");
// Return error to Amazon Cognito
callback(error, event);
}
// Return to Amazon Cognito
callback(null, event);
};
But,I don't want prefix PreAuthentication failed with error,I just want to display my message.
Any help is appreciated.
Currently, there is no way to stop Cognito from adding the prefix because the form is a hosted web UI.
If this is a hard requirement, the workaround is to create your own login form and use the aws-cognito-sdk
Once you make the call to cognitoUser.authenticateUser in the code below the Pre authentication trigger will fire the Lambda function and you will need to handle the error and parse it to remove the unwanted prefix.
Hope this Helps
aws Examples: Using the JavaScript SDK
var authenticationData = {
Username : 'username',
Password : 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n',
ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'username',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer*/
var idToken = result.idToken.jwtToken;
},
//Your message from the Lambda will return here, you will need to parse the err to remove the unwanted prefix*
onFailure: function(err) {
alert(err);
},
});

How capture audio message receive or image receive in BotKit Facebook

I have been using Botkit Facebook Messenger and I can receive text messages from Facebook perfectly, however I can not capture audio messages, images or attachments.
Has anyone been able to capture these types of messages?
var Botkit = require('botkit');
var controller = Botkit.facebookbot({
access_token: process.env.access_token,
verify_token: process.env.verify_token,
})
var bot = controller.spawn({
});
// if you are already using Express, you can use your own server instance...
// see "Use BotKit with an Express web server"
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
// this is triggered when a user clicks the send-to-messenger plugin
controller.on('facebook_optin', function(bot, message) {
bot.reply(message, 'Welcome to my app!');
});
// user said hello
controller.hears(['hello'], 'message_received', function(bot, message) {
bot.reply(message, 'Hey there.');
});
controller.hears(['cookies'], 'message_received', function(bot, message) {
bot.startConversation(message, function(err, convo) {
convo.say('Did someone say cookies!?!!');
convo.ask('What is your favorite type of cookie?', function(response, convo) {
convo.say('Golly, I love ' + response.text + ' too!!!');
convo.next();
});
});
});
there is an example for stickers, images, and audio replies in the facebook starter project: https://github.com/howdyai/botkit-starter-facebook/blob/master/skills/sample_events.js
If you have trouble using them, feel free to create an issues on the github!

MS BotBuilder : How can the bot receive parameters and initiate conversation at webchat start

I'm using the direct-line method to communicate with this bot :
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID || config.appId,
appPassword: process.env.MICROSOFT_APP_PASSWORD || config.appPassword
});
// Initialize bot
var bot = universalBot(connector);
var server = restify.createServer();
server.listen(process.env.port || port, function () {
console.log('%s listening to %s', server.name, server.url);
});
var botListener = connector.listen();
server.post('/api/messages', (req, resp) => {
token = req.query.token;
console.log(token); //prints the token to the terminal
botListener(req, resp);
});
var msg = new builder.Message()
.text(notification);
//.address(address)
bot.send(msg, function (err) {
// Return success/failure
res.status(err ? 500 : 200);
res.end();
});
In order to pro-actively send the message i still need the address of the user and conversation id.
Is there a way to obtain these information at the time this initialisation on the browser ;
var bot = {
id: params['botid'] || 'botid',
name: params['botname'] || 'botname',
screen: params['screen'] || null
};
BotChat.App({
directLine: {
//secret: params['s'],
token: params['t'],
//domain: params['domain'],
//webSocket: params['webSocket']
},
user: user, //Need to access this user object at server on the webchat start
bot: bot
}, document.getElementById("BotChatGoesHere"));
Or any other way where the bot can start the conversation when the user loads the html in the browser.
UPDATE : The conversationUpdate dialog serves for triggering and initiating a dialog, but how can I access the parameter (token) and user object sent along, inside conversationUpdate dialog?
Thanks
If I understand you correctly, you want your bot to prompt the user with something like Hi, what can I help you with today? the minute the webchat loads, right? I haven't tried the direct line, always used the provided iframe, and here's what I do in my bot to send the welcome message:
bot.on('conversationUpdate', (message) => {
(message.membersAdded || [])
.filter((identity) => identity.id == message.address.bot.id)
.forEach((identity) => {
const reply = new builder.Message()
.address(message.address)
.text("Hi, How can I help you today?");
bot.send(reply);
});
});
I believe what you are looking for is the backchannel. With this, you can send values to your bot. the backchannel documentation is at the bottom of the readme on that repo.

Service worker causing CORS issues on Firefox

I'm using service worker for push notifications, following this article. Everything is working with Chrome but with Firefox (v.44.0.2) I have a weird issue.
On successful login to my app, I register the service worker which does nothing but waiting for push events; I see that is correctly registered (from some logging and from about:serviceworkers). Now, if I refresh the page (CTRL+R) all my POST have CORS issues (missing Access-Control-Allow-Origin header) due to this service worker and the user is redirected to login page; from here on all POSTs do not work for the same reason.
Conversely, if I login, unregister the service worker and then refresh, there are no problems at all. Any idea of what's going on? Again my service worker just handles push events, no caching no other processing done and it perfectly works on Chrome.
Here's my service worker code ( SOME_API_URL points to a real API which is not needed for testing purpose cause the issue happens after the service worker registers, no push events needed)
self.addEventListener('push', function(event) {
// Since there is no payload data with the first version
// of push messages, we'll grab some data from
// an API and use it to populate a notification
event.waitUntil(
fetch(SOME_API_URL).then(function(response) {
if (response.status !== 200) {
// Either show a message to the user explaining the error
// or enter a generic message and handle the
// onnotificationclick event to direct the user to a web page
console.log('Looks like there was a problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification.title;
var message = data.notification.message;
var icon = data.notification.icon;
var notificationTag = data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
}).catch(function(err) {
console.error('Unable to retrieve data', err);
var title = 'An error occurred';
var message = 'We were unable to get the information for this push message';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
tag: notificationTag
});
})
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow('/');
}
})
);
});
Firefox 44 has bug 1243453, which causes the Origin header of cross-origin requests to get dropped if the service worker doesn't listen for fetch events.
The bug has been fixed in Firefox 45, which will be released the week of March 8, 2016 (next week, as of the time of this writing). In the meantime, and for users who don't immediately upgrade to the latest Firefox release, you can work around the problem by adding this code to the service worker:
addEventListener('fetch', function(evt) {
evt.respondWith(fetch(evt.request));
});

onIncomingMessage on Sinch-rtc never gets called on receiving Sinch IM message

I am using NodeJS and Sinch-RTC (for IM feature) and I am unable to receive IM messages on my server - Meaning my onIncomingMessage is never called even though a message is sent to my username via phone. I am using the following code on my server.
var SinchClient = require('sinch-rtc');
var sinchClient = new SinchClient({
applicationKey: 'MY-APP-KEY',
capabilities: {messaging: true, calling: true},
supportActiveConnection: true,
});
var messageClient = sinchClient.getMessageClient();
sinchClient.start({username: 'MY_USERNAME', password: 'MY_PASSWORD'}).then(function() {
console.log('Success!');
global_username = username;
}).fail(handleFail)
var handleFail = function() {console.log("Message Sending failed");};
var eventListener = {
onIncomingMessage: function(message) {
console.log( message.textBody);
}
}
messageClient.addEventListener(eventListener);
When I run this program as "node sinchReceive.js" I am unable to receive any sinch message sent to MY_USERNAME. However, I can send a message to a different username and that doesn't have any problem. Please tell me what could be wrong or if I am missing something. Thanks.

Resources