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

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)

Related

Fitbit URL callback giving a response of NULL

I'm having trouble getting a response from a callback uri and I would really appreciate any help you could give me.
I am trying to use the Fitbit API which requires you to use a callback url to get an Auth Code.
Workflow:
1. Go to Fitbit url to get user to allow the app access to their personal data.
2. User agrees to the conditions
3. User gets redirected to my API
4. The API returns the code from (Code is located in URL and I can access it)
5. I console.log the code out to verify it
6. API returns the code
7. I work with code then exchanging it for an access token.
The problem is that I don't return the code (Or anything )when I return to the app even though I can console.log it on the API. The response I get is NULL
Here is the URL:
url = "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=https://REDIRECT_URL&scope=activity%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight&expires_in=604800";
I then open the URL in the InAPPBrowser successfully:
if (url !== "") {
const canOpen = await Linking.canOpenURL(url)
if (canOpen) {
try {
const isAvailable = await InAppBrowser.isAvailable()
if (isAvailable) {
const result =InAppBrowser.open(url, {
// iOS Properties
dismissButtonStyle: 'done',
preferredBarTintColor: 'gray',
preferredControlTintColor: 'white',
// Android Properties
showTitle: true,
toolbarColor: '#6200EE',
secondaryToolbarColor: 'black',
enableDefaultShare: true,
}).then((result) => {
console.log("Response:",JSON.stringify(result))
Linking.getInitialURL().then(url => {
console.log("Tests: ",url)
this._setTracker(url as string);
});
})
} else Linking.openURL(url)
} catch (error) {
console.log("Error: ",error)
}
}
}
From here the URL opens successfully.
Here is the API now which is done in Typescript on AWS serverless and Lambda
export const handler: APIGatewayProxyHandler = async (event, _context, callback) =>{
let provider = event.path
//prints code
let x = event.queryStringParameters
console.log("Code: ",x)
const response = {
statusCode: 200,
body: "Success"
};
return response;
}
Please let me know if further detail is required?
Thank you!
Right so it turns out what I was doing was correct apart from the response should have been 301 which is a redirect response.
const response= {
statusCode: 301,
headers: {
"location": `app://CALLBACK RESPONSE ADDRESS?type=${provider}`
},
body: "Boom"
}

"[Network] undefined" when trying to use subscriber - URQL

I am trying to set up a subscriber to log some output on the creation of a new Message.
Currently using Urql, with ApolloServerExpress on the backend.
I am receiving an error from the useSubscription method which I am logging to the console :
message: "[Network] undefined"
name: "CombinedError"
I know for sure my backend is working as I can subscribe using the Graphiql playground just fine.
As far as front end goes, I have followed almost exactly as the example in the Urql docs.
WS Client:
const wsClient = createWSClient({
url: "ws://localhost:4000/graphql",
});
Subscriber Exchange:
subscriptionExchange({
forwardSubscription(operation) {
return {
subscribe: (sink) => {
const dispose = wsClient.subscribe(operation, sink);
return {
unsubscribe: dispose,
};
},
};
},
}),
MessageList Component:
const newMessages = `
subscription Messages {
newMessage {
content
status
sender {
id
email
}
recipient {
id
email
}
}
}
`;
...
const handleSub = (messages: any, newMessage: any) => {
console.log("Messages: ", messages);
console.log("newMessages: ", newMessage);
};
const [res] = useSubscription({ query: newMessages }, handleSub);
console.log("Res: ", res);
I was getting the same error when using subscriptions with urql. In my case, I was able to do console.log(error.networkError); which gave a much more helpful error message than [Network] undefined.
You can read more about errors in urql here.
The error I got from error.networkError was:
Event {
"code": 4400,
"isTrusted": false,
"reason": "{\"server_error_msg\":\"4400: Connection initialization failed: Missing 'Authorization' or 'Cookie' header in JWT authenticati",
}
I was able to fix it by adding authentication to my subscription exchange setup. Here's the code I'm using now:
const wsClient = createWSClient({
url: "wss://your-api-url/graphql",
connectionParams: async () => {
// Change this line to however you get your auth token
const token = await getTokenFromStorage();
return {
headers: {
Authorization: `Bearer ${token}`,
},
};
},
});
Ended up chalking graphql-ws and switched over to subscriptions-transport-ws.
Fixed my issues.

How to get space Id of users who have not added Google Chat Bot to their coversation

We are implementing a Google hangout Chat Bot , Which will send proactive notification to the user in domain. To do this Google chat Bot API requires the space Id to send proactive notification to user.
Reference document: https://developers.google.com/hangouts/chat/reference/rest/v1/spaces/list
code :
jwtClient.authorize(function (err) {
if (err) {
console.log(err);
return;
}
else {
chat.spaces.list({
auth: jwtClient
}, function (err, resp) {
if (err)
console.log(err);
else {
chat.spaces.list({
auth: jwtClient
}, function (err, resp) {
if (err)
console.log(err);
else {
var spaceList = resp.data.spaces;
spaceList.forEach(element => {
var spaceUrl = `https://chat.googleapis.com/v1/${element.name}/messages?key=${apiKey}`;
request({
url: spaceUrl,
method: "POST",
headers: {
'Content-Type': 'application/json'
},
json: customMessage
},
function (error, response, body) {
callback(error, body)
}
);
})
};
});
}
});
}
});
}
}
But This API returns space list of only those user , who has added the Bot to their coversation.
Is their any work around to get/create space of/to every user in google domain?
Unfortunately there is no way to extract the Space ID without the user ever interacting with the bot. Allowing this would give the bot ability to spam any user whenever without consent.
I would suggest storing space IDs to a database. So once a user has started a conversation with a bot, you can later message them whenever you want. Adding the bot or interacting with it in a room is the "consent" that is needed for a bot to message a user.

Parse Push's not delivered cloud code only

I'm running parse-server on ubuntu and can't seem to get push notifications working when sent in cloud code.
Push's work when using a REST api call (passing master key) but don't work when cloud code calls them.
What's interesting is that the cloud code Parse.Push() method returns a success and thus no error message.
My hypothesis is that this is a configuration problem, and the Parse.Push() method is referencing somethign I have incorrectly configured on the server.
here is my cloud function. This call works when sent via REST. and the success callback in cloud is always called.
Parse.Push.send(
{
// where: pushQueryClient,
channels: ["user_tkP7gurGzc"],
data:
{
alert: pushTextClient
}
},
{
success:function(){
console.log("push sent");
},
error: function(error){
console.log("push failed");
console.dir(error);
},
useMasterKey: true});
i think you have an issue with the useMasterKey parameter.
Please try to use this code in order to send the push notification:
Parse.Push.send({
where: whereQuery,
data: {
alert: {
title: request.params.title,
body: request.params.body
},
type: request.params.type,
sound: 'default'
}
}, {
useMasterKey: true
}).then(function() {
response.success();
}, function(error) {
response.error("Push failed " + error);
});
In this code i use Promises which is the best practice and also wrap useMasterKey in a separate object

How to handle authentication errors in socket.io with socketio-jwt

Following the example for https://github.com/auth0/socketio-jwt , I couldn't get the authentication failure to fire.
How are you supposed to handle and configure authentication errors using this library? I see in the source code that it is supposed to throw an UnauthorizedError but I just can't seem to trigger it.
Server side
io
.on('connection', socketioJwt.authorize({
secret: 'test',
timeout: 7000
}))
.on('authenticated', (socket) => {
console.log('connected user: ' + socket.decoded_token.name);
});
Client side
socket.on('connect', function () {
socket.emit('authenticate', {token: 'badtoken'}); //send the jwt
});
socket.on("error", function(error) {
// this never fires
if (error.type == "UnauthorizedError" || error.code == "invalid_token") {
alert("User's token has expired");
}
});
Do I need to add an .on('error, function(error)) on the server code as well?
Looking at the source code for jwt, they are actually emitting "unauthorized", not "error". Change to
socket.on("unauthorized", function(error) {
// this should now fire
if (error.data.type == "UnauthorizedError" || error.data.code == "invalid_token") {
alert("User's token has expired");
}
});
This bug in the doc and examples was also reported here.

Resources