Node.js code isn't running in javascript function - javascript

I'm working with Twilio and sending an example message when the provided code is ran in the terminal:
var accountSid = '...';
var authToken = '...';
var twilio = require('twilio');
var client = new twilio(accountSid, authToken);
client.messages.create({
body: 'Hello World!',
to: '+1-555-555-5555', // Text this number
from: '+18885555555' // From a valid Twilio number
})
.then((message) => console.log(message.sid));
However, when I place it in a function to be called on when a button is pressed, then nothing happens.
function messageNow() {
var accountSid = '...';
var authToken = '...';
var twilio = require('twilio');
var client = new twilio(accountSid, authToken);
client.messages.create({
body: 'Hello World!',
to: '+1-555-555-5555', // Text this number
from: '+18885555555' // From a valid Twilio number
})
.then((message) => console.log(message.sid));
}
And call from HTML button:
<button type="submit" id="Btn" class="buttons" onclick="messageNow()">SUBMIT</button>
Any help is appreciated.

Twilio developer evangelist here.
It sounds as though you are trying to run the Twilio Node.js module in the browser. This won't work as the module is only built for server side Node.js, not client side/browser JavaScript.
If you want to send messages via an interface with buttons, you will need to build a web application that can run the Twilio code on the server and present an interface in HTML, CSS and JavaScript that can call the server application.
There are a number of tutorials that take you through different ways you can build apps to send SMS messages with Twilio and Node.js. It might help to take a look there.

Related

Firestore function deployment error when using Twilio

I'm trying to integrate Twilio into a triggered Firestore function. The problem I'm having is when I add this code, I am unable to deploy ANY functions. As far as I know this is how to use twilio inside a cloud function. At the top I have this and I think firebase doesn't like something here because ALL functions stop deploying with this code.
// Used to send text messages
const twilio = require('twilio')
// const accountSid = functions.config().twilio.sid
// const authToken = functions.config().twilio.token
/* eslint new-cap: ["error", { "newIsCap": false }] */
const client = new twilio('ACblahblahblah', 'ccblahblahblah') // sid and token
const twilioNumber = '+13344714571' // your twilio phone number
Within the triggered function I have this. But I don't think the issue is here:
return client.messages.create({
to: someNumber,
from: twilioNumber,
body: 'Some message.'
}).then((data) => {
console.log(data)
}).catch((error) => {
console.log(error)
})
I have a valid Twilio account set up. The function logs don't tell me much other than that the function cannot be initialized. What am I missing? Seems like this has worked for others.
Figured it out about 5 minutes after posting the question. I had not installed twilio in the functions folder but rather the root of the project. Once I executed
npm install twilio
in the functions folder, the functions started deploying. Too bad there was no error in the logs that said something like "required package is missing" or something like that.

New to Twilio and struggling to pass data from database to Twilio so it sends text message with information with a serverless function on Azure

I only started using Twilio last week and am getting confused with how to set up my Twilio account so it can receive information from a database when a field changes and then text it to a number.
I have gone through the docs to set it up with node and can get the text message to be sent if I sent a text to my Twilio number, but getting the data from a different source is seeming a lot harder.
I'm using JavaScript with Windows Azure. Any suggestions are greatly appreciated.
One approach would be to add the Twilio SDK to your Azure function, trigger the function when the database is updated, and use the SMS client to send a message when the function is triggered.
Here is a code sample for sending a simple message from the quickstart docs (https://www.twilio.com/docs/sms/quickstart/node):
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'AC0840e531a54515afbda482d80c48fb10';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => console.log(message.sid))
.done();

get data from mqtt broker -6lbr

I followed this tutorial :
Running the CC26xx Contiki Examples
but instead of using the cc26xx-demo I used the cc26xx-web-demo and successfully manged to get everything up and running and I can access the 6lbr web page, when I access the sensorTag page I see a mqtt configuration page as shown:
and if I click index in the sensorTag page (pic above) I get to see the data:
the question is , how can I write a simple nodejs js file that uses the mqtt broker information to grab all the sensorTag sensors data and save it in an local object.
I tried to do run this example but no luck
var mqtt = require('mqtt')
client = mqtt.createClient(1883, '192.168.1.109');
client.subscribe(what do I write here);
client.on('message', function(topic, message) { console.log(message); });
I don't know what I'm doing wrong
UPDATE:
mqtt configuration page :
javascript file :
and I run the js with node and listen on port 1883:
tcpdump seems to detect mqqt packets on 1883 port but I can't to seem to be able to console.log the sensor data when I run the js file with node ??
I went on the contiki wiki and came across this info
"You can also subscribe to topics and receive commands, but this will only work if you use "Org ID" != 'quickstart'. Thus, if you provide a different Org ID (do not forget the auth token!), the device will subscribe to:
iot-2/cmd/+/fmt/json"
does this mean that the topic to subscribe to is quickstart but even if that's so, I used '+/#' which subrcibes to all topics and still got nothing printing on the console ?
Hope this works for you:
var mqtt = require('mqtt');
var fs = require('fs');
var options = { port: PORT, host: HOST };/*user, password and others authentication if there.*/
var client = mqtt.connect('HOST', options);
client.on('connect', function ()
{
client.subscribe("topic, command or data");
client.publish("topic, command or data", data, function () {
});
});
client.on('error', function () { });
client.on('offline', function () { });
client.on('message', function (topic, message) {
console.log(message.toString());
});

how can I send an IP messaging using twilio-csharp library

I just start create a live chat app with Twilio.
I have downloaded the twilio-csharp library from twilio.com/docs/csharp/install and started with a sample console application.
code example from Twilio:
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio.IpMessaging;
class Example {
static void Main (string[] args) {
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "accountSid";
const string authToken = "authToken";
const string serviceSid = "serviceSid";
const string channelSid = "channelSid";
// List all Messages
var client = new IpMessagingClient(accountSid, authToken);
MessageResult result = client.ListMessages(serviceSid, channelSid);
Console.WriteLine(result);
}
}
But this code doesn't work in my case, I got always an errors "type or namespace could not be found".
I have these like reference:
I tried tutorial of IP Messaging , it works. But in the tutorial, they used Javascript SDK to initialize the IP messaging client
tc.accessManager = new Twilio.AccessManager(tokenResponse.token);
tc.messagingClient = new Twilio.IPMessaging.Client(tc.accessManager);
So I just don't understand how can I use this C# library to send an IP Messaging, or maybe I can just control my IP Messaging applications from the client side?
I unstand why I got this error.
I just follow the steps of installation on twilio-csharp library gitHub. But this project's README is only for SMS project. If we want to use Library for IpMessaging, we must also import another Library, Twilio.IpMessaging.
So What I got know like reference and the project IP Messaging works.
Hope this will help the others.

Phonegap PushNotification, how to use my node push-server with phonegap?

So, i'm on Phonegap, i use :
https://github.com/phonegap-build/PushPlugin/
https://github.com/argon/node-apn
So, i install the first plugin and i can get my phone token. After that, i created a node server.js file in my root directory with :
var apn = require('apn');
var token = "MY TOKEN";
var device = new apn.Device(token);
var notification = new apn.Notification();
notification.expiry = Math.floor(Date.now() / 1000) + 3600;
notification.badge = 1;
notification.alert = "This is a Push Notification=)";
notification.payload = {'prop': 'special value'};
notification.device = device;
var options = {
gateway: 'gateway.sandbox.push.apple.com',
cert: 'CER.pem',
key: 'KEY.pem',
passphrase: 'password'
}
var apnsConnection = new apn.Connection(options);
apnsConnection.pushNotification(notification, device);
When i start my server with node server.js in command line, i can see my push notification on my phone, so all it's ok.
But my question, i need to send push notification in different place in my code (phonegap). How can i do that ?
When my server.js is running, how can i send other push notification from my phonegap application ?
What you have above is code that you can collect together, and expose a function to call it multiple times. For example, a very simple implementation would be:
var apn = require('apn');
var options = {
gateway: 'gateway.sandbox.push.apple.com',
cert: 'CER.pem',
key: 'KEY.pem',
passphrase: 'password'
};
var apnsConnection = new apn.Connection(options);
module.exports.pushNotification = function(token, alert) {
var device = new apn.Device(token);
var notification = new apn.Notification();
notification.alert = alert;
notification.device = device;
apnsConnection.pushNotification(notification, device);
};
Imagine you name this file pns.js for "push notification service". Now in your server.js, you could instead require that module you just created and call the pushNotification function:
var pns = require("./pns.js");
pns.pushNotification("MY TOKEN", "This is a Push Notification");
Now you've got the same function when you execute the server.js. From here, you could instead pull this function into other modules that need to call it from the Node.js side of things.
If you need to call it from a remote process, you could look into a web framework like Express, and build an API which calls the same code. The token and alert message could then be passed in to this function call. Doing this would likely turn your server.js into a running web server which listens for requests and sends push notifications on demand.
A bit late, but for people with the same question, look at this tool:
https://www.npmjs.com/package/node-pushserver
...it does exactly what you want. It supports both iOS and Android.
Run this on a server and your app can: register the device by POSTing to http://yourserver:8000:/subscribe. Devices are stored in a mongodb database. By POSTing a http request to http://yourserver:8000/send, you can send push notifications to a single registered device, a subset or all of them.
Have fun!

Categories

Resources