Handle an incoming message

Note:

Before you can get started, you need to do the following:

Using the Conversation API, you can receive and respond to messages from any channel you have configured. This tutorial shows you how to set up a Flask application using Python that receives and responds to messages.

Note:

This tutorial is easier to accomplish if you have already completed the steps for sending a message.

Steps:
  1. Set up your Flask Python application
  2. Configure your Conversation API webhook
  3. Test the application

Set up your Flask Python application

  1. Create a new folder where you want your app project and open a command prompt to that location.
  2. Create a new environment with the following command:
    Copy
    Copied
    py -3 -m venv venv
  3. Activate the environment using the following command:
    Copy
    Copied
    venv/Scripts/activate
  4. Install the Flask and requests modules by executing the following commands:
    Copy
    Copied
    pip install Flask
    pip install requests

Modify your application

Note:

This tutorial uses basic authentication for testing purposes. We recommend OAuth 2.0 authentication in a production environment. Read more about authentication methods here.

  1. In your project folder, create a new file named app.py. Populate that file with the provided "app.py" code found on this page. This code starts a server that listens for incoming messages. It then sends a text message in response.
Note:

This sample code is configured for the US region. If your Conversation API app wasn't created in the US region, replace all instances of https://us.conversation.api.sinch.com with https://eu.conversation.api.sinch.com in the sample code.

app.py

This code sample is to be used with the instructions on this page to build a web server that will handle and respond to incoming messages.

# Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys
from flask import Flask 
from flask import request
import requests
import base64

accessKey = ""
accessSecret = ""

app = Flask(__name__)

@app.route('/', methods=['POST'])
def result():

    res = request.get_json()
    
    if 'message' in res:

        projectId = res["project_id"]
        appId = res["app_id"]
        channel = res["message"]["channel_identity"]["channel"]
        identity = res["message"]["channel_identity"]["identity"]
        text = res["message"]["contact_message"]["text_message"]["text"]
        print(projectId)
        print(channel)
        print(identity)

        url = "https://us.conversation.api.sinch.com/v1/projects/" + projectId + "/messages:send"

        data = accessKey + ":" + accessSecret
        encodedBytes = base64.b64encode(data.encode("utf-8"))
        accessToken = str(encodedBytes, "utf-8")

        payload = {
        "app_id": appId,
        "recipient": {
            "identified_by": {
                "channel_identities": [
                {
                    "channel": channel,
                    "identity": identity
                }  
                ]
            }
        },
        "message": {
            "text_message": {
                "text": "Thank you for using the Sinch Conversation API. You sent: " + text
            }
        }  
        }

        headers = {
        "Content-Type": "application/json",
        "Authorization": "Basic " + accessToken
        }

        response = requests.post(url, json=payload, headers=headers)

        data = response.json()
        print(data)

    return "200 OK"
  1. Assign your values to the following parameters:
ParameterYour value
accessKeyFind your access key on your Sinch dashboard.
accessSecretFind your access secret on your Sinch dashboard.
Note: Access secrets are only available during initial key creation.
  1. Save the file.

Start your web server and set up a tunnel

  1. Start the server by executing the following command:
    Copy
    Copied
    flask run

    By default, your web server is started on port 5000.

  2. Now you need to open a tunnel to the server you just set up. We are using ngrok for this. If you don't have ngrok installed already you can install it with the following command:
    Copy
    Copied
    npm install ngrok -g
  3. Open a terminal or command prompt and enter:
    Copy
    Copied
    ngrok http 5000
  4. Copy the HTTPS address that ends with .ngrok.io.

Configure your webhook

In order for your application to receive messages from Conversation API, you must configure a webhook in your Conversation API app. For detailed instructions on configuring a webhook, click here.

  1. Set your webhook URL to the HTTP address you copied in the previous step.
  2. Assign the following triggers:
    • CONVERSATION_START
    • CONVERSATION_STOP
    • EVENT_DELIVERY
    • EVENT_INBOUND
    • MESSAGE_DELIVERY
    • MESSAGE_INBOUND
    • UNSUPPORTED

Test the application

Now that your server is running and your webhook is configured, you can test the application.

From your messaging platform, send your Conversation API app a message. You will receive a message back in response on the messaging platform.

Additional resources

Read the links below to learn more:

Was this page helpful?

app.py

This code sample is to be used with the instructions on this page to build a web server that will handle and respond to incoming messages.

# Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys
from flask import Flask 
from flask import request
import requests
import base64

accessKey = ""
accessSecret = ""

app = Flask(__name__)

@app.route('/', methods=['POST'])
def result():

    res = request.get_json()
    
    if 'message' in res:

        projectId = res["project_id"]
        appId = res["app_id"]
        channel = res["message"]["channel_identity"]["channel"]
        identity = res["message"]["channel_identity"]["identity"]
        text = res["message"]["contact_message"]["text_message"]["text"]
        print(projectId)
        print(channel)
        print(identity)

        url = "https://us.conversation.api.sinch.com/v1/projects/" + projectId + "/messages:send"

        data = accessKey + ":" + accessSecret
        encodedBytes = base64.b64encode(data.encode("utf-8"))
        accessToken = str(encodedBytes, "utf-8")

        payload = {
        "app_id": appId,
        "recipient": {
            "identified_by": {
                "channel_identities": [
                {
                    "channel": channel,
                    "identity": identity
                }  
                ]
            }
        },
        "message": {
            "text_message": {
                "text": "Thank you for using the Sinch Conversation API. You sent: " + text
            }
        }  
        }

        headers = {
        "Content-Type": "application/json",
        "Authorization": "Basic " + accessToken
        }

        response = requests.post(url, json=payload, headers=headers)

        data = response.json()
        print(data)

    return "200 OK"