Tutorial - Aprende a como enviar mensajes de texto (sms) via Twilio con Node.js usando codigo javascript moderno ES6 (Babel) / Learn how to send text messages (sms) via Twilio with Node.js using modern javascript code ES6 (Babel)

in GEMS3 years ago



Hoy aprenderemos a enviar un sms y recibir una respuesta usando los servicios de Twilio a través de Node con su framework Express usando código moderno ES6 (Babel) Today we will learn to send an SMS and receive a response using Twilio services through Node with its Express framework using code Today we will learn to send an SMS and receive a response using Twilio services through Node with its Express framework using code modern ES6 (Babel)

Twilio es una compañía que ofrece una plataforma de comunicaciones así como de servicios en la nube, ubicada en San Francisco, California. Twilio permite desarrollar aplicaciones que hagan y reciban llamadas, mensajes de texto, elaboren funciones de comunicación y registro, usando APIs, propias del servicio web.

Twilio is a company that offers a communications platform as well as cloud services, located in San Francisco, California. Twilio allows you to develop applications that make and receive calls, text messages, develop communication and registration functions, using APIs, typical of the web service.



Empezaremos instalando todos los modulos necesarios para nuestro ejemplo: We will start by installing all the necessary modules for our example:
npm install express twilio @babel/node @babel/cli @babel/core @babel/preset-env

Crearemos un archivo nuevo llamado .babelRC que contendrá lo siguiente: We will create a new file called .babelRC that will contain the following:
{
    "presets":[
        "@babel/env"
    ]
}
Ahora procedemos a navegar hasta twilio.com y crear nuestra cuenta para obtener nuestro número de teléfono y la cuenta SID y el Auth token necesario para este ejemplo Now we proceed to navigate to twilio.com and create our account to obtain our phone number and SID account and the Auth token required for this example

En nuestra raíz del proyecto creamos un archivo llamado .env que contendrá dichas claves de autenticación, el contenido del archivo es este: In our project root we create a file called .env that will contain these authentication keys, the content of the file is this

Index.js

Procedemos a copiar el siguiente código We proceed to copy the following code
import dotenv from 'dotenv'
dotenv.config()
const accound_sid = process.env.ACCOUND_SID
const auth_token = process.env.AUTH_TOKEN
const port = process.env.PORT || 4000
import client from 'twilio'
const MessagingResponse = client.twiml.MessagingResponse
import express from 'express'
const app = express()
app.use(express.json())
app.get('/', (req,res)=>{
    res.send('Welcome!!')
})
app.get('/send', async(req,res) => {
    try{
        const message =  await client(accound_sid,auth_token).messages.create({
                    body: 'Mensaje de prueba - sms from twilio',
                    from: '+xxxxxxxx',
                    to:'+xxxxxxx'
        })
        res.json(message.sid)
    }catch(err){
        console.log(err)
    }
})
app.post('/sms', (req,res) => {
    const twiml = new MessagingResponse();
    twiml.message('He recibido tu mensaje.');
    res.writeHead(200,{'Content-Type':'text/xml'});
    res.end(twiml.toString());
})
app.listen(port, () => {
    console.log('Server on port', port)
})

Antes de ejecutar nuestro ejemplo modificaremos el package.json de la siguiente manera: Before running our example we will modify the package.json as follows:
package.json
"scripts": {
        "start": "babel-node index.js"
  }
Ahora desde nuestra terminal procedemos a ejecutar el sguiente comando Now from our terminal we proceed to execute the following command
npm start

Vamos en nuestro navegador y colocamos http://localhost:4000/send We go in our browser and put http://localhost:4000/send
Y con eso debería de llegar un sms a al numero indicado en el código arriba (to) de parte de (from) And with that a sms should arrive at the number indicated in the code above (to) from (from)
Para probar la respuesta automática (endpoint sms/) habría que subirla a un hosting (recomiendo heroku para ello) To test the automatic response (endpoint sms /) it would be necessary to upload it to a hosting (I recommend heroku for this)

Adjunto captura de mi teléfono / Attached capture of my phone






Y con esa amigos llegamos al final del tutorial, espero que lo hayan disfrutado y hasta la próxima! / And with that friend we come to the end of the tutorial, I hope you enjoyed it and until next time!


Visite mi sitio web oficial / Visit my official website

tupaginaonline.net

Sort:  

Excelente tutorial y bien explicado, ya hace mucho deje de trabajar con Twilio, pero es una gran herramienta, sobre todo cuando quieres hacer KYC y confirmar que un número telefónico es dueño.

Gracias, pronto subiré mas contenido, así voy puliendo los tutoriales acá en hive

Genial, me encantara ver tu contenido dentro de la comunidad de Develop Spanish o desde el tag #developspanish, poco a poco tendremos mas desarroladores hablando de programación :D

Excelente! mañana subiré otro post a la comunidad para hacer crecer la comunidad

Congratulations @jfdesousa7! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 800 upvotes. Your next target is to reach 900 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Next Hive Power Up Day is February 1st 2021