Receiving SMS and MMS
Inbound texts are delivered via a webhook to your server. The webhook will be an HTTP POST
request that includes a payload with information about the inbound SMS or MMS. To receive the message, you’ll need to create a minimal web application that will accept the webhook request.
Prerequisites
Check out the API prerequisites to setup your Python development environment for this guide.
Receive an SMS or MMS with Telnyx
- First, you’ll need to install Flask, a minimal web framework written in Python.
pip install flask
- Create a Flask application to accept webhooks. Create a new file called receive.py and copy the code below into the file:
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/webhooks', methods=['POST'])
def webhooks():
body = request.json
print(body)
return '', 200
if __name__ == "__main__":
app.run(port=5000)
This file does a few things, so we'll step through each line one by one.
import os
from flask import Flask, request
Make the code from the Flask library available in the receive.py
file.
app = Flask(__name__)
Create a new instance of the Flask class, passing in the module attribute __name__
as the name of the Flask application.
@app.route('/webhooks', methods=['POST'])
Next, you’ll define a route using a decorator function. We define the path as /webhooks
and specify that the path will respond to the HTTP POST
method. This route will accept webhooks from Telnyx when your Telnyx number receives an SMS or MMS.
def webhooks():
Finally, the print function will print the body of the request so you can see it in your terminal. For the purposes of this demo, you'll print the body of the message to the terminal to see the contents of the message. But in a real application, you'd most likely take some action based on the type of event that was received.
print(body)
The last lines in the file check to see if the name of the module is __main__
, and if it is, starts the application on the port 5000.
if __name__ == "__main__":
app.run(port=5000)
- Now that you’ve set up your application, make sure it's ready to receive requests. From your terminal, run the below:
python receive.py
You should see something like the following:
* Serving Flask app "receive" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
This means our server is listening on port 5000. You're almost ready to receive an SMS or MMS.
- The final step involves making your application accessible from the internet. So far, we've set up a local web server. This is typically not accessible from the public internet, making testing inbound requests to web applications difficult.
The best workaround is a tunneling service. They come with client software that runs on your computer and opens an outgoing permanent connection to a publicly available server in a data center. Then, they assign a public URL (typically on a random or custom subdomain) on that server to your account. The public server acts as a proxy that accepts incoming connections to your URL, forwards (tunnels) them through the already established connection and sends them to the local web server as if they originated from the same machine. The most popular tunneling tool is
ngrok
. Check out the ngrok setup walkthrough to set it up on your computer and start receiving webhooks from inbound messages to your newly created application.
- Once you've set up
ngrok
or another tunneling service you can add the public proxy URL to your Messaging Profile. To do this, click the edit symbol ✎ next to your Messaging Profile. Under “Inbound”, paste the forwarding address from ngrok into the Webhook URL field. Add/webhooks
to the end of the URL to direct the request to the webhook endpoint in your Flask app.
> For now you'll leave “Failover URL” blank, but if you'd like to have Telnyx resend the webhook in the case where sending to the Webhook URL fails, you can specify an alternate address in this field.
Now that your Messaging Profile is configured, you're ready to receive an SMS or MMS.
Send a message from your phone to your Telnyx number. Soon after you’ll see an event printed in your terminal when the inbound SMS or MMS request is received by your Flask application.
Congrats, you’ve learned how to recieve messages with Telnyx.
Receiving SMS and MMS
Inbound texts are delivered via a webhook to your server. The webhook will be an HTTP POST
request that includes a payload with information about the inbound SMS or MMS. To receive the message, you’ll need to create a minimal web application that will accept the webhook request.
Install Dependencies
We will use the express framework to setup a webserver that will receive webhooks. Create a new npm project and install express
and body-parser
. This will allow you to receive incoming HTTP requests
npm init
npm install express body-parser --save
Create an express application to accept webhooks
Now create a new file, receive.js
, and import the dependencies.
const express = require('express');
const bodyParser = require('body-parser');
Next, setup the Node app to parse requests as JSON.
const app = express();
app.use(bodyParser.json());
Handling the request
Then create a POST handler, this should be the same endpoint that you have configured Telnyx to send requests to.
app.post('/webhook', (req, res) => {
console.log(`New message from ${req.body.from}: ${req.body.body}`);
});
Start the server.
const port = 8080;
app.listen(port, () => console.log(`App running on port ${port}`));
From your terminal run this command to start the server.
node receive.js
A sample webhook from Telnyx would look like this:
{
"sms_id": "8d7b47fc-be08-4820-8ce3-58fd4fe42a76",
"direction": "inbound",
"from": "+15555555",
"to": "+16666666",
"body": "Hello world"
}
The final step involves making your application accessible from the internet. So far, we've set up a local web server. This is typically not accessible from the public internet, making testing inbound requests to web applications difficult.
The best workaround is a tunneling service. They come with client software that runs on your computer and opens an outgoing permanent connection to a publicly available server in a data center. Then, they assign a public URL (typically on a random or custom subdomain) on that server to your account. The public server acts as a proxy that accepts incoming connections to your URL, forwards (tunnels) them through the already established connection and sends them to the local web server as if they originated from the same machine. The most popular tunneling tool is ngrok
. Check out the ngrok setup walkthrough to set it up on your computer and start receiving webhooks from inbound messages to your newly created application.
Once you've set up ngrok
or another tunneling service you can add the public proxy URL to your Messaging Profile. To do this, click the edit symbol ✎ next to your Messaging Profile. Under “Inbound”, paste the forwarding address from ngrok into the Webhook URL field. Add /webhooks
to the end of the URL to direct the request to the webhook endpoint in your Flask app.
For now you'll leave “Failover URL” blank, but if you'd like to have Telnyx resend the webhook in the case where sending to the Webhook URL fails, you can specify an alternate address in this field.
Now that your Messaging Profile is configured, you're ready to receive an SMS or MMS.
Send a message from your phone to your Telnyx number. Soon after you’ll see an event printed in your terminal when the inbound SMS or MMS request is received by your Flask application.
Congrats, you’ve learned how to recieve messages with Telnyx.
Receiving SMS and MMS
Inbound texts are delivered via a webhook to your server. The webhook will be an HTTP POST
request that includes a payload with information about the inbound SMS or MMS. To receive the message, you’ll need to create a minimal web application that will accept the webhook request.
Install Dependencies
First you'll need to install Sinatra
, a minimal HTTP server for Ruby.
gem install sinatra
Create an express application to accept webhooks
Create a Sinatra application to accept webhooks by pasting the following code into a file called receive.rb
:
require 'sinatra'
require 'json'
post '/webhooks' do
payload = JSON.parse(request.body.read)
puts payload.inspect
end
Let's step through this code one line at a time. At the top we make the Sinatra
and JSON
libraries available to the application.
require 'sinatra'
require 'json'
Next we create the route /webhooks
. This tells sinatra what URL path to handle requests on and the post
function specifies POST as the request type.
post '/webhooks' do
# ...
end
Once inside the request handler, first parse the JSON body into a structured object.
payload = JSON.parse(request.body.read)
Finally, print out a summary of the payload
object
puts payload.inspect
Running the application
From your terminal, run the following command to start your server
ruby receive.rb
You should see something similar to the following
[2019-11-11 14:27:50] INFO WEBrick 1.4.2
[2019-11-11 14:27:50] INFO ruby 2.5.1 (2018-03-29) [x86_64-linux-gnu]
== Sinatra (v2.0.7) has taken the stage on 4567 for development with backup from WEBrick
[2019-11-11 14:27:50] INFO WEBrick::HTTPServer#start: pid=278 port=4567
Our server is now listening on port 4567. You're almost ready to receive an SMS or MMS. However, when you run this program on your computer you will not be able to receive the inbound webhooks from Telnyx. A web address exposed to the public internet is required for this. The best solution for this is a tunneling tool, such as Ngrok
. These applications run on your local computer and connect to servers with public addresses, they then form a tunnel and provide a web address that forwards all requests to your local machine. Check out the ngrok setup walkthrough for more details.
Once you've set up ngrok
or another tunneling service you can add the public proxy URL to your Messaging Profile. To do this, click the edit symbol ✎ next to your Messaging Profile. Under “Inbound”, paste the forwarding address from ngrok into the Webhook URL field. Add /webhooks
to the end of the URL to direct the request to the webhook endpoint in your Sinatra server.
For now you'll leave “Failover URL” blank, but if you'd like to have Telnyx resend the webhook in the case where sending to the Webhook URL fails, you can specify an alternate address in this field.
Now that your Messaging Profile is configured, you're ready to receive an SMS or MMS.
Send a message from your phone to your Telnyx number. Soon after you’ll see an event printed in your terminal when the inbound SMS or MMS request is received by your Sinatra application.
Receiving SMS and MMS
Inbound texts are delivered via a webhook to your server. The webhook will be an HTTP POST
request that includes a payload with information about the inbound SMS or MMS. To receive the message, you’ll need to create a minimal web application that will accept the webhook request.
Install XAMPP or another server application
Note: This step is only if you want to test locally rather than on a currently live server application.
First you'll need to install XAMPP
, a simple web server solution package. Information on setting up XAMPP
can be found here here. This is required in order to run the web server locally.
Create a simple PHP application to accept webhooks
Create a simple index.php
file that will accept web hooks and write received messages to a text file log.txt
. Make sure that when you run XAMPP you see the title as Text Message Receiver and the same for the header of the page.
require_once __DIR__.'/vendor/autoload.php';
\Telnyx\Telnyx::setApiKey('YOUR_API_KEY ');
$json = json_decode(file_get_contents("php://input"), true);
if($json){
print_r($json);
$record_type = $json['data']['record_type'];
if($record_type == "event") {
$call_control_id = $json['data']['payload']['call_control_id'];
$event_type = $json['data']['event_type'];
if($event_type == "call.initiated") {
//NEEDS WORK HERE TO CREATE CALL AND ANSWER (Currently does not work)
$call = \Telnyx\Call::Create($call_control_id);
$result = $call.answer();
} elseif($event_type == "call.answered") {
//Add call to array of calls
// If it is the first call create the conference
// If it is not first, add it to the conference
}
}
}
Let's step through this code one line at a time. At the top we define our html file to just be a simple page with the title of PHP Conference Demo.
<html>
<head>
<title>PHP Conference Demo</title>
</head>
<body>
<h1>PHP Conference Host</h1>
Next we setup our Telnyx API Key and the php code to accept incoming webhooks. The json is decoded and stored in the variable $json
and from there we extract the information we need.
require_once __DIR__.'/vendor/autoload.php';
\Telnyx\Telnyx::setApiKey('YOUR_API_KEY ');
$json = json_decode(file_get_contents("php://input"), true);
Running the application
Fire up XAMPP to run our index.php
file locally. You should ensure Apache and MySQL are running.
Our XAMPP server is listening on the default port 80. You're almost ready to receive an SMS or MMS. However, when you run this program on your computer you will not be able to receive the inbound webhooks from Telnyx. A web address exposed to the public internet is required for this. The best solution for this is a tunneling tool, such as Ngrok
. These applications run on your local computer and connect to servers with public addresses, they then form a tunnel and provide a web address that forwards all requests to your local machine. Check out the ngrok setup walkthrough for more details.
Once you've set up ngrok
or another tunneling service you can add the public proxy URL to your Call Control Application. To do this, click the edit symbol ✎ next to your Call Control Application. Paste the forwarding address from ngrok into the Webhook URL field. Add /index.php
or the extension from localhost to get to our index.php
file on the server to the end of the URL to direct the request to the webhook endpoint in XAMPP server. This section is shown below:
For now you'll leave “Failover URL” blank, but if you'd like to have Telnyx resend the webhook in the case where sending to the Webhook URL fails, you can specify an alternate address in this field.
Now that your Call Control Application is set up, we can start using our Conference.