How to configure Twilio on parse server? - heroku

I am attempting to incorporate Twilio into my application that is running on my parse server deployed with Heroku and MongoLab. I am trying to configure by using this code in my cloud/main.js file
var twilio = require("twilio");
twilio.initialize("87se46bovanw4v5aiwy4o57","ia8o57awyov57yn875vyboe");
Parse.Cloud.define("inviteWithTwilio", function(request, response) {
// Use the Twilio Cloud Module to send an SMS
twilio.sendSMS({
From: "6543211234",
To: 8065456703,
Body: "Start using Parse and Twilio!"
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
however, I get this response
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} [NSDebugDescription: JSON text did not start with array or object and option to allow fragments not set.]
I have determined that the problem lies in the first two lines when trying to initialize Twilio. I figure this is because the Twilio Cloud Module isn't integrated into my parse server like it was with Parse Hosted cloud code, but I'm not sure. How can I fix this problem? Thanks for your time.

Twilio developer evangelist here.
It sounds like, from our conversation in the comments, like you have not installed the Twilio npm module just yet. On Parse, you didn't have to install the module as it was included by default. To use the Twilio module using Parse server you need it installed.
To install the module, open up your application in the terminal and type:
$ npm install twilio --save
The --save flag is important as it saves the dependency to your package.json file. Check in the updated package.json and deploy your code again. Now, when deploying to Heroku the npm modules, including the Twilio module, will be installed.
Marin, who already answered as well, had a good point. I also recommend using twilio.sendMessage. It uses the newer and better featured Messages resource (rather than the deprecated SMS resource).
Let me know if this helps at all.

I think this is problem for Twilio version.
you should use twilio.sendMessage.
var twilio = require("twilio");
twilio.initialize("87se46bovanw4v5aiwy4o57","ia8o57awyov57yn875vyboe");
Parse.Cloud.define("inviteWithTwilio", function(request, response) {
// Use the Twilio Cloud Module to send an SMS
twilio.sendMessage({
From: "6543211234",
To: 8065456703,
Body: "Start using Parse and Twilio!"
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});
Hope to help you.
Thanks
///////////////////////////////
Here is my code work fine.
Parse.Cloud.define("sendSMS", function(request, response) {
console.log(request);
var twilio = require("twilio")("ACCOUNT_SID","AUTH_TOKEN");
twilio.sendMessage({
to: request.params.number,
from: request.params.from,
body: request.params.message
}, function(err, responseData) {
if (err) {
response.error(err);
} else {
response.success("SMS sent.");
}
});
});

Related

Svelte/Sveltekit and socket.io-client not working in dev (works in preview)

I'm trying to make socket.io-client work in a svelte front end app to talk to an existing API server that already uses socket.io. After a number of challenges, I managed to make this work but I can only get this to work with sveltekit's preview and not in dev mode. Wondered if someone with some knowledge of those could explain why or suggest what I need to do to get it connecting in dev?
svelte 3.34.0
sveltekit next-169
socket.io(-client) 4.2.0
basic code as follows, currently within a file $lib/db.js where I define a few stores that are pulled into the layout for general use..
import { io } from "socket.io-client";
import { browser } from '$app/env';
const initSocket = async () => {
console.log('creating socket...');
let socket = io('http://192.168.1.5:4000', { 'connect timeout': 5000 });
socket.on("connect", () => {
// always works in preview...
console.log('socket created with ID:', socket.id);
});
socket.on("connect_error", (error) => {
// permanently fired in dev...
console.error('Failed to connect', error);
});
socket.on("error", (error) => {
console.error('Error on socket', error);
});
socket.on("foo", data => {
// works in preview when server emits a message of type 'foo'..
console.log("FOO:", data);
});
};
if (browser) {
initSocket();
}
// stores setup and exports omitted..
with svelte-kit preview --host I see the socket creation log message with the socket ID and the same can be seen on the api server where it logs the same ID. The socket works and data is received as expected.
with svelte-kit dev --host however, the log message from socket.on("connect").. is never output and I just see an endless stream of error messages in the browser console from the socket.on("connect_error").. call..
Failed to connect Error: xhr poll error
at XHR.onError (transport.js:31)
at Request.<anonymous> (polling-xhr.js:93)
at Request.Emitter.emit (index.js:145)
at Request.onError (polling-xhr.js:242)
at polling-xhr.js:205
Importantly, there is no attempt to actually contact the server at all. The server never receives a connection request and wireshark/tcpdump confirm that no packet is ever transmitted to 192.168.1.5:4000
Obviously having to rebuild and re-run preview mode on each code change makes development pretty painful, does anyone have insight as to what the issue is here or suggestions on how to proceed?
I've had a similar problem, I solved it by adding this code to svelte.config.js:
const config = {
kit: {
vite: {
resolve: {
alias: {
"xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js",
},
},
},
},
};
The solution was provided by this comment from the vite issues.

Push via parse server cloud code: Url not found

After working with Parse for a considerable time on multiple project I recently started moving data to a local Parse server and writing a sample app to get familiar with the system. I managed to get most working so far including Push using het Parse Dashboard.
Unfortunately I can't seem to get Parse Push to work using cloud code.
This is my code:
Parse.Cloud.define('push', function(req, res) {
var logMessage = "Push test";
console.log(logMessage);
var pushQuery = new Parse.Query(Parse.Installation);
Parse.Push.send({
where: pushQuery,
data: {
alert: 'Test'
}
}, {
useMasterKey: true,
success: function() {
// Push sent, send re
res.success('Push Sent');
var logMessage = "Push Sent!";
console.log(logMessage);
},
error: function(error) {
res.error(error)
var logMessage = error;
console.log(logMessage);
// There was a problem :(
}
});
var logMessage = "Push should be sent.";
console.log(logMessage);
});
Unfortunately no push is sent and the following error message is returned:
{
code: 107,
message: 'Received an error with invalid JSON from Parse: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>404 Not Found</title>\n</head><body>\n<h1>Not Found</h1>\n<p>The requested URL /push was not found on this server.</p>\n<hr>\n<address>Apache/2.4.7 (Ubuntu) Server at localhost Port 80</address>\n</body></html>\n' }
It seems to indicate the push request is sent to the /push directory of the main server, however I have no clue how I can change this to the appropriate location and I presumed parse-server would automatically choose the right path.
I hope someone might know how to fix this because I'm out of ideas at the moment..
For all that deal with this same issue, here is the solution.
Thanks to Anbarasi for the correct answer. My server settings were incorrect. Upon changing the server URL to the correct settings (address + port) everything started working!

Parse Cloud Code multiple push dilemma

My app has notifications based on zip code and channels.
When a user changes zip code the app updates the Installation with the new zip.
In my beforeSave on Installation I grab the new zip and subscribed channels and search for relevant notifications.
Then I need to send the notifications as pushes back to that installation.
Two questions:
Can I just push to the Installation object that came into the beforeSave as such:
return Parse.Push.send({
where: request.object
data: data
})
or do I have to do an Installation query for that objectId?
I can't just push the notification object. I need to configure the data. If there are multiple notifications (not likely but possible) what's the best way to send multiple pushes back to that installation (assuming I don't want to put them all in one push)?
I can't send the pushes from a for loop. Can I do something like this:
return notificationQuery.each().then( function(notification) {
//configure push from that notification
return Parse.Push.send ... etc
})
Thanks!
You can send Push notifications in parse based on channels or where(query) but not both.
So you can do a query on Installation class with channel and zipcode:
var query = new Parse.Query(Parse.Installation);
query.equalTo('channels', 'Indians');
query.equalTo('zipcode', "345678");
Parse.Push.send({
where: query,
data: {
action: "com.example.UPDATE_STATUS"
alert: "Ricky Vaughn was injured in last night's game!",
name: "Vaughn",
newsItem: "Man bites dog"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
Hope this helps.

How can I get the user first name from facebook in cloud code?

How can I get the user first name from facebook in cloud code?
I can do it using objC and in the app, but I want from the server, cloud code.
How can I send a facebook request from cloud code? do I have to use the access token saved in authData in any way? Thanks
It seems that you can use a graph search
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
});
But they donĀ“t recommend you to get Facebook data of a user using the Parse Cloud
Check it out
https://www.parse.com/questions/get-user-info-from-facebook-javascript-sdk-after-login
For those browsing this now that docs are getting out of synch after FB drop this was not officially supported as per https://groups.google.com/forum/#!topic/parse-developers/mw7qhHGIsOc
IMHO best bet ATM is to use the graph API directly. Within a Parse.Cloud function:
let access_token = request.user.get('authData').facebook.access_token
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.8/' + path + '&access_token=' + access_token
})
.then(function(result) {
console.log(result)
}, function(error) {
console.log(error)
})
for the original question let path='me?fields=first_name' or FB_ID if not me

Mojo SDK retrieve all contacts

I'm playing with the Mojo SDK and I want to get all contacts.
this.controller.serviceRequest('palm://com.palm.contacts/crud', {
method: 'listContacts',
parameters: {
limit: 100
},
onSuccess: this.handleListResponse.bind(this),
onFailure: function(errResp){
Mojo.Log.info(errResp.errorText)
}.bind(this),
onerror: function(errResp){
Mojo.Log.info(errResp.errorText)
}.bind(this)
});
This is what I have right now, but I don't get anything back. And Mojo.Log.info doesn't seem to work. Any suggestions?
Thanks
I'm also fairly new at PRE development but here is what I think the issue is.
The error that comes back is "Account Not Found". You need to add accountId: as a parameter to the service request.
That account id, according to the documentation, is a Synergy account and needs to be created for your application. Click here for reference about the accountId and createAccount methods

Resources