Microsoft Bot displays unnecessary duplicated messages in WebChat? - node.js

When a user visits my chat for the first time they are greeted with welcome message and immediately asked to provide their first name. As soon as the user inputs their first name the welcome message is and text prompt for their first name is displayed once again. Only after they input their first name for the second time, the bot moves on to the next question about their last name.
Additionally when user finally enters their first and last name in first chat and they come back again to the same chat, welcome message & first name prompt is displayed, only when user provides some input bot sends welcome back message.
This is minimal code required to reproduce this problem.
let restify = require('restify');
let builder = require('botbuilder');
// Setup Restify Server
let server = restify.createServer();
let connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
server.post('/api/messages', connector.listen());
let bot = new builder.UniversalBot(connector);
// Define default Dialog
bot.dialog('/', [
function (session) {
if (!session.userData.firstName) {
// firstName used as a flag to assess whether the user is coming back
// or new user - we can use it because the very first dialog is asking them
// for their first name.
session.send("Welcome!");
} else {
session.send("Welcome back %s!", session.userData.firstName);
}
session.beginDialog('mainConversationFlow');
}
])
bot.dialog('mainConversationFlow', [
function(session, args, next) {
if (!session.userData.firstName)
session.beginDialog('getFirstName');
else
next();
},
function(session, args, next) {
if(!session.userData.lastName)
session.beginDialog('getLastName');
else
next();
},
function(session, args, next) {
session.endConversation('The End');
}
])
bot.dialog('getFirstName', [
function(session, args) {
let msg = "What's your first name?";
builder.Prompts.text(session, msg);
},
function(session, results) {
session.userData.firstName = results.response.trim();
session.endDialog();
}
])
bot.dialog('getLastName', [
function(session, args) {
let msg = builder.Message.composePrompt(session,
["Hi %s, what's your last name?"], session.userData.firstName);
builder.Prompts.text(session, msg);
},
function(session, results) {
session.userData.lastName = results.response.trim();
session.endDialog();
}
])
bot.on('conversationUpdate', function (message) {
if (message.membersAdded) {
message.membersAdded.forEach(function (identity) {
if (identity.id === message.address.bot.id) {
bot.beginDialog(message.address, '/');
}
});
}
})
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
})
User on the first run of the app should be shown welcome message and asked for their first name. As soon as they input their first name, the bot should move right away to the next question about their last name and after the user answers that bot should end conversation.
When user entered their first & last names and they come back, the bot should only display welcome back message and end conversation.
This is snippet of my client code using BotFramework-WebChat:
let directLineSecret = 'mysecret';
let directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';
BotChat.App({
directLine: {secret: directLineSecret},
user: { id: localStorage.getItem('email')},
bot: { id: 'testbot' },
resize: 'detect'
}, this.botChatContainer.nativeElement);
let directLineClient = rp(directLineSpecUrl)
.then(function(spec) {
return new Swagger({
spec: JSON.parse(spec.trim()),
usePromise: true
});
})
.then(function(client) {
return rp({
url: 'https://directline.botframework.com/v3/directline/tokens/generate',
method: 'POST',
headers: {
'Authorization': 'Bearer ' + directLineSecret
},
json: true
}).then(function(response) {
let token = response.token;
client.clientAuthorizations.add('AuthorizationBotConnector', new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + token, 'header'));
return client;
});
})
.catch(function(err) {
console.error('Error initializing DirectLine client', err);
throw err;
});
These screenshots were taken in dev.botframework.com test window. However the same behaviour applies in my web app which uses WebChat.
Can you please help me to solve this issue?
Update
Logs:
2018-01-13 19:29:46.876 INFO - Container logs 2018-01-13T19:29:45.006255595Z
UserConversation message: , user: undefined 2018-01-13T19:29:45.006543896Z {"typ
e":"conversationUpdate","timestamp":"2018-01-13T19:29:44.4543348Z","membersAdded
":[{"id":"mybot#j4OUxKYkEpQ","name":"MyBot"}],"text":"","attachments":[],"entiti
es":[],"address":{"id":"C27bFaQ1Ohr","channelId":"webchat","user":{"id":"8f8399d
115774c86b83634bf7086f354"},"conversation":{"id":"8f8399d115774c86b83634bf7086f3
54"},"bot":{"id":"mybot#j4OUxKYkEpQ","name":"MyBot"},"serviceUrl":"https://webch
at.botframework.com/"},"source":"webchat","agent":"botbuilder","user":{"id":"8f8
399d115774c86b83634bf7086f354"}}
2018-01-13T19:29:45.006562196Z ----------------------------
2018-01-13T19:29:45.937402126Z Incoming message:
2018-01-13T19:29:45.937559026Z ----------------------------
2018-01-13T19:29:46.291227879Z Outgoing message: Welcome!
2018-01-13T19:29:46.291465679Z {"type":"message","agent":"botbuilder","source":"
webchat","address":{"id":"C27bFaQ1Ohr","channelId":"webchat","user":{"id":"8f839
9d115774c86b83634bf7086f354"},"conversation":{"id":"8f8399d115774c86b83634bf7086
f354"},"bot":{"id":"mybot#j4OUxKYkEpQ","name":"MyBot"},"serviceUrl":"https://web
chat.botframework.com/"},"text":"Welcome!"}
2018-01-13T19:29:46.291479179Z ----------------------------
2018-01-13T19:29:46.291708779Z Outgoing message:
What's your first name? 2018-01-13T19:29:46.291740980Z {"text":"What's your
first name?","inputHint":"expectingInput","type":"message","address":{"id":"C27b
FaQ1Ohr","channelId":"webchat","user":{"id":"8f8399d115774c86b83634bf7086f354"},
"conversation":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OU
xKYkEpQ","name":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"}}
2018-01-13T19:29:46.291759880Z ----------------------------
2018-01-13 19:29:56.876 INFO - Container logs 2018-01-13T19:29:53.471348251Z
UserConversation message: , user: undefined 2018-01-13T19:29:53.471657052Z {"typ
e":"conversationUpdate","timestamp":"2018-01-13T19:29:53.3233269Z","membersAdded
":[{"id":"AvfenKwcS1o","name":"You"}],"text":"","attachments":[],"entities":[],"
address":{"id":"DbpPwxf2m7T","channelId":"webchat","user":{"id":"8f8399d115774c8
6b83634bf7086f354"},"conversation":{"id":"8f8399d115774c86b83634bf7086f354"},"bo
t":{"id":"mybot#j4OUxKYkEpQ","name":"MyBot"},"serviceUrl":"https://webchat.botfr
amework.com/"},"source":"webchat","agent":"botbuilder","user":{"id":"8f8399d1157
74c86b83634bf7086f354"}}
2018-01-13T19:29:53.471672552Z ----------------------------
2018-01-13T19:29:53.515781796Z UserConversation
message: John, user: You 2018-01-13T19:29:53.515792596Z {"type":"message","times
tamp":"2018-01-13T19:29:53.1827153Z","textFormat":"plain","text":"John","entitie
s":[{"type":"ClientCapabilities","requiresBotState":true,"supportsTts":true,"sup
portsListening":true}],"textLocale":"en","sourceEvent":{"clientActivityId":"1515
871784086.6213104132628995.0"},"attachments":[],"address":{"id":"8f8399d115774c8
6b83634bf7086f354|0000002","channelId":"webchat","user":{"id":"AvfenKwcS1o","nam
e":"You"},"conversation":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"
mybot#j4OUxKYkEpQ","name":"MyBot"},"serviceUrl":"https://webchat.botframework.co
m/"},"source":"webchat","agent":"botbuilder","user":{"id":"AvfenKwcS1o","name":"
You"}}
2018-01-13T19:29:53.515801796Z ----------------------------
2018-01-13T19:29:53.545361425Z Incoming message: John
2018-01-13T19:29:53.545373525Z ----------------------------
2018-01-13T19:29:53.802571982Z Outgoing message: Welcome!
2018-01-13T19:29:53.802593382Z {"type":"message","agent":"botbuilder","source":"
webchat","textLocale":"en","address":{"id":"8f8399d115774c86b83634bf7086f354|000
0002","channelId":"webchat","user":{"id":"AvfenKwcS1o","name":"You"},"conversati
on":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OUxKYkEpQ","n
ame":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"},"text":"Welcome!
"}
2018-01-13T19:29:53.802600382Z ----------------------------
2018-01-13T19:29:53.802602782Z Outgoing message: What's your first name?
2018-01-13T19:29:53.802604982Z {"text":"What's your first name?","inputHint":"ex
pectingInput","type":"message","address":{"id":"8f8399d115774c86b83634bf7086f354
|0000002","channelId":"webchat","user":{"id":"AvfenKwcS1o","name":"You"},"conver
sation":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OUxKYkEpQ
","name":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"},"textLocale"
:"en"}
2018-01-13T19:29:53.802610082Z ----------------------------
2018-01-13 19:30:01.878 INFO - Container logs 2018-01-13T19:29:57.806548081Z
UserConversation message: John, user: You 2018-01-13T19:29:57.809735285Z {"type"
:"message","timestamp":"2018-01-13T19:29:57.6990081Z","textFormat":"plain","text
":"John","textLocale":"en","sourceEvent":{"clientActivityId":"1515871784086.6213
104132628995.2"},"attachments":[],"entities":[],"address":{"id":"8f8399d115774c8
6b83634bf7086f354|0000005","channelId":"webchat","user":{"id":"AvfenKwcS1o","nam
e":"You"},"conversation":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"
mybot#j4OUxKYkEpQ","name":"MyBot"},"serviceUrl":"https://webchat.botframework.co
m/"},"source":"webchat","agent":"botbuilder","user":{"id":"AvfenKwcS1o","name":"
You"}}
2018-01-13T19:29:57.809755085Z ----------------------------
2018-01-13T19:29:57.828015903Z Incoming message: John
2018-01-13T19:29:57.828028303Z ----------------------------
2018-01-13T19:29:58.122706697Z Outgoing message: Got response as: John
2018-01-13T19:29:58.122972998Z {"type":"message","agent":"botbuilder","source":"
webchat","textLocale":"en","address":{"id":"8f8399d115774c86b83634bf7086f354|000
0005","channelId":"webchat","user":{"id":"AvfenKwcS1o","name":"You"},"conversati
on":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OUxKYkEpQ","n
ame":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"},"text":"Got
response as: John"}
2018-01-13T19:29:58.122997998Z ----------------------------
2018-01-13T19:29:58.123366398Z Outgoing message: Hello John! What is your last
name? 2018-01-13T19:29:58.123377798Z {"text":"Hello John! What is your last name
?","inputHint":"expectingInput","type":"message","address":{"id":"8f8399d115774c
86b83634bf7086f354|0000005","channelId":"webchat","user":{"id":"AvfenKwcS1o","na
me":"You"},"conversation":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":
"mybot#j4OUxKYkEpQ","name":"MyBot"},"serviceUrl":"https://webchat.botframework.c
om/"},"textLocale":"en"}
2018-01-13T19:29:58.123395698Z ----------------------------
2018-01-13T19:30:00.551811524Z UserConversation
message: Doe, user: You 2018-01-13T19:30:00.552098924Z {"type":"message","timest
amp":"2018-01-13T19:30:00.4252782Z","textFormat":"plain","text":"Doe","textLocal
e":"en","sourceEvent":{"clientActivityId":"1515871784086.6213104132628995.4"},"a
ttachments":[],"entities":[],"address":{"id":"8f8399d115774c86b83634bf7086f354|0
000008","channelId":"webchat","user":{"id":"AvfenKwcS1o","name":"You"},"conversa
tion":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OUxKYkEpQ",
"name":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"},"source":"webc
hat","agent":"botbuilder","user":{"id":"AvfenKwcS1o","name":"You"}}
2018-01-13T19:30:00.552114924Z ----------------------------
2018-01-13T19:30:00.590356662Z Incoming message: Doe
2018-01-13T19:30:00.590371762Z ----------------------------
2018-01-13T19:30:00.857187129Z Outgoing message: Got last name as: Doe
2018-01-13T19:30:00.857206229Z {"type":"message","agent":"botbuilder","source":"
webchat","textLocale":"en","address":{"id":"8f8399d115774c86b83634bf7086f354|000
0008","channelId":"webchat","user":{"id":"AvfenKwcS1o","name":"You"},"conversati
on":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OUxKYkEpQ","n
ame":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"},"text":"Got last
name as: Doe"}
2018-01-13T19:30:00.857220329Z ----------------------------
2018-01-13T19:30:00.857222929Z Outgoing message: End of "mainConversationFlow"
dialog. 2018-01-13T19:30:00.857225229Z {"type":"message","agent":"botbuilder","s
ource":"webchat","textLocale":"en","address":{"id":"8f8399d115774c86b83634bf7086
f354|0000008","channelId":"webchat","user":{"id":"AvfenKwcS1o","name":"You"},"co
nversation":{"id":"8f8399d115774c86b83634bf7086f354"},"bot":{"id":"mybot#j4OUxKY
kEpQ","name":"MyBot"},"serviceUrl":"https://webchat.botframework.com/"},"text":"
End of \"mainConversationFlow\" dialog."}
2018-01-13T19:30:00.857230729Z ----------------------------
Code I have used for logs:
const logUserConversation = (event) => {
console.log('UserConversation message: ' + event.text + ', user: ' + event.address.user.name);
console.log(JSON.stringify(event));
console.log('----------------------------');
};
const logIncomingMessage = function (session) {
console.log('Incoming message: ' + session.message.text);
console.log(JSON.stringify(session.user));
console.log('----------------------------');
};
const logOutgoingMessage = function (event) {
console.log('Outgoing message: ' + event.text);
console.log(JSON.stringify(event));
console.log('----------------------------');
};
bot.use({
receive: function (event, next) {
logUserConversation(event);
next();
},
botbuilder: function (session, next) {
logIncomingMessage(session);
next();
},
send: function (event, next) {
logOutgoingMessage(event);
next();
}
})

Actually, when the bot connecter first connect to bot server, the bot firstly joins in the conversation, so conversationUpdate event will be triggerred for your bot, which do not contain the session.userData object.
And once the user inputs someting in the bot webchat, when there will be a second conversationUpdate for the user. At this time, bot beginDialog '\' inside the conversationUpdate event with the session contains session.userData object.
you can add the following middleware to detect this issue:
bot.use({
receive: function (event, next) {
console.log(event)
next();
},
send: function (event, next) {
console.log(event)
next();
}
});
Unfortunately, I cannot find a method to let bot triggers conversationUpdate for user when the webchat init.
update
You can leverage webchat js sdk on website and the backchannel mechanism to achieve your requirement.
website client:
//define a user
const user = {id:'userid',name:'username'};
const botConnection = new BotChat.DirectLine({
domain: params['domain'],
secret: '<secrect>',
webSocket: params['webSocket'] && params['webSocket'] === 'true' // defaults to true
});
botConnection .postActivity({ type: "event", from: user, name: "ConversationUpdate", value: "" }) .subscribe(id => console.log("Conversation updated"));
BotChat.App({
botConnection: botConnection,
bot: bot,
user: user,
resize: 'detect'
}, document.getElementById("BotChatGoesHere"));
bot server:
bot.on('event',(event)=>{
console.log(event)
if(event.name==='ConversationUpdate'){
bot.beginDialog(event.address, '/');
}
})

To the people who still get the issue
When the first conversation is established between the web channel and the bot, the ConversationUpdate activity is raised twice. One by the user and another by the channel, therefore we get a welcome message twice. We need to make sure that we send the welcome message for the activity raised by the user. Find the working code here

Related

Access Denied when added participant to conference in Twilio Voice

I have 2 endpoints in my api, one to create a Voice conference and another one to add a participant to a conference.
The first one is the following and works correctly.
module.exports.call = function (req, res) {
let name = 'conf_' + req.body.CallSid
const twiml = new twilio.twiml.VoiceResponse()
const dial = twiml.dial({ callerId: req.configuration.twilio.callerId })
dial.conference(
{
endConferenceOnExit: true,
statusCallbackEvent: 'join',
statusCallback: `/api/phone/call/${req.body.CallSid}/add-participant/${encodeURIComponent(req.body.phone)}`
},
name
)
res.set({
'Content-Type': 'application/xml',
'Cache-Control': 'public, max-age=0',
})
res.send(twiml.toString())
}
As you can see, the statusCallback URL points to the controller below, which should add a participant to the conference.
module.exports.addParticipant = function (req, res) {
console.log('addParticipant', req.params)
if (req.body.CallSid === req.params.sid) {
/* the agent joined, we now call the phone number and add it to the conference */
conference = client.conferences('conf_' + req.params.sid)
console.log('conference', conference)
client
.conferences('conf_' + req.params.sid)
.participants.create({
to: '+34XXXXXXXXX',
from: req.configuration.twilio.callerId,
earlyMedia: true,
endConferenceOnExit: true
}).then(participant => {
res.status(200).end()
})
.catch(error => {
console.error(error)
res.status(500).end()
})
} else {
res.status(200).end()
}
}
However, I'm getting the following error:
[RestException [Error]: Access Denied] {
status: 403,
message: 'Access Denied',
code: 20006,
moreInfo: 'https://www.twilio.com/docs/errors/20006',
detail: undefined
}
I have enabled the geo permissions for this numbers country, but still no success.
What am I missing?
Did you make sure to enable Agent Conference in your Account?
Voice Conference Settings
https://www.twilio.com/console/voice/conferences/settings

Botframework v4 Directline integration: Is there a way to get the conversation id generated from directline transfer to the Chatbot (nodejs code)

This might be very simple, but I cannot find any reference regarding this.
I integrated the chat bot in the web app using direct line API; I’m using this API to generate conversation id:
POST: https://directline.botframework.com/v3/directline/conversations
I’m trying to get the generated conversation id from the above API (from web app code) to the chatbot code (NodeJS). Is there a way or any reference to do this?
one way as per this issue comment is to send data to bot before starting the conversation using:
var params = BotChat.queryParams(location.search);
var my_token = params['my_token'];
var botConnection = new BotChat.DirectLine({
secret: 'DIRECTLINE_SECRET'
});
BotChat.App({
botConnection: botConnection
,user: { id: 'USER_ID', name: 'User' } // user.id auto updates after first user message
}, document.getElementById("bot"));
botConnection.connectionStatus$.subscribe(function (status) {
if (status == 2) { // wait for connection is 'OnLine' to send data to bot
var convID = botConnection.conversationId;
botConnection.postActivity({
from: { id: convID } // because first time user ID == conversation ID
,type: 'event'
,name: 'registerUserData' // event name as we need
,value: my_token // data attached to event
}).subscribe(function (activityId) {
// This subscription is a MUST
// If I remove this handler the postActivity not reaches the bot
});
}
});
Here you subscribe to the botConnection.connectionStatus$ and when the status is equal to 2, you get the conversation ID from the botConnection object.
Then, you can add this middleware code in the bot code to get the data:
bot.use({ receive: function(event, next) {
if (!!event && !!event.address && event.name == 'registerUserData') {
var message = new builder.Message().address(event.address).text('my_token:' + event.value);
bot.send(message, function (err) {}); // simulate proactive message to user
}
next();
} });
Hope this helps.
I resolve it using Botframework Web Chat back channel, here's the link for reference:
https://github.com/Microsoft/BotFramework-WebChat
After I generated the conversation id using directline API:
POST: https://directline.botframework.com/v3/directline/conversations
I send data from the web app to the chatbot via backchannel.
<div id="webchat"></div>
<script>
(async function () {
// We are using a customized store to add hooks to connect event
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
// When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { conversation_id: conversationID }
}
});
}
return next(action);
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
//Note: conversationID and token is generated in the backend code of the web app.
</script>

Facebook chat bot - catch post title or link sent by "Send message" button

I am creating chat bot for fb messenger, so far so good. I am facing the following problem: When I create new fb post using the request
{myPageID}/feed?message=For all Math geniuses :)&payload={"value":"test"}&call_to_action={"type":"MESSAGE_PAGE","value":"test"}&link=someLink&access_token={my_token}
I am attaching CTA Button "MESSAGE_PAGE" which add "Send message button to my post"
When I click on the button "Send message" I got auto-response from my page with link preview
I am subscribed for all messenger events and the only event I receive is delivery event. Is there any way I can catch the title or the link of this auto-response messenge? When I am posting with request I added payload, post back even value to the button and nothing is coming except this delivery event
Here is my receive message so far:
app.post('/webhook', (req, res) => {
let body = req.body; // Checks this is an event from a page subscription
if (body.object === 'page') {
// Iterates over each entry - there may be multiple if batched
body.entry.forEach(function (entry) {
// Iterate over each messaging event
entry.messaging.forEach(function (event) {
console.log(event);
if (event.message) {
receivedMessage(event);
}
else if (event.delivery) {
//TO DO
}
else {
payloadMessage(event);
}
});
});
// Returns a '200 OK' response to all requests
res.status(200).send('EVENT_RECEIVED');
} else {
// Returns a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
and this is the delivery event
{ sender: { id: 'senderID' },
recipient: { id: 'recipientID' },
timestamp: 1558957571235,
delivery:
{ mids:
[ '8KsvyN2iL2upEhwddr_uQXeOJLgKhhdQtqQ8RzPxlPczGgR2T1w7Inqg8TJK-4gpWNQS-HZvLUBS5R-g1FcWdQ' ],
watermark: 1558957571029,
seq: 0 } }

Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM

I got this code from my client iOS app on XCode console
Firebase registration token: diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
NodeJS
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Result
When I run it
node app.js
I kept getting
START
END
Successfully sent with response: {"results":[{"error":{"code":"messaging/invalid-registration-token","message":"Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM."}}],"canonicalRegistrationTokenCount":0,"failureCount":1,"successCount":0,"multicastId":7577724855311354000}
How would one go about debugging this further?
your token has some additional random string such as
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
just remove : diWY78iar8s: from your token string
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Response from FCM :
Successfully sent with response: { results: [ { messageId: '0:1543448946734425%479ec0e2479ec0e2' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6133765431734591000 }
One of the interesting reasons for invalid registration is: that device have a different token. Maybe you are trying to use a past token.
In my case what happened was I was getting the FCMRegistrationToken from my colleague via Discord and the Ctrl+C Ctrl+V was modifying the token. On obtaining the token via email solved the issue.

user validation error with mailgun connector loopback: email exists

I took the example project here and added the loopback-connector-mailgun. I configured it like this:
In datasources.json added the following:
{
"mailgun": {
"connector": "loopback-connector-mailgun",
"apikey": "[my api key here]",
"domain": "[my domain here]"
}
}
then in model-config.json:
{
"Email": {
"dataSource": "mailgun",
"public": false
}
}
When I register a client by doing a post in localhost:3000/api/clients the verification email is sent successfully but the server does not redirect me to the home page and after some time (it hangs for around 30 seconds) I get the following error:
{"name":"ValidationError","status":422,"message":"The `client` instance is not valid. Details: `email` Email already exists (value: \"a#b.com\") ...
The full stack is reported in this gist.
My client.js function:
Client.afterRemote('create', function(context, client, next) {
console.log('> client.afterRemote triggered');
//console.log(typeof client);
//var auth = dsConfig.emailDs.transports[0].auth;
var options = {
type: 'email',
to: client.email,
from: "noreply#loopback.com",
subject: 'Thanks for registering.',
template: path.resolve(__dirname, '../../server/views/verify.handlebars'),
redirect: '/verified',
user: client
};
client.verify(options, function(err, response) {
console.log(err + 'Debug point 1');
if (err) return next(err);
console.log('> verification email sent:', response);
context.res.render('response', {
title: 'Signed up successfully',
content: 'Please check your email and click on the verification link ' +
'before logging in.',
redirectTo: '/',
redirectToLinkText: 'Log in'
});
});
});
The execution never reaches Debug Point 1. Thanks!

Resources