|

|  How to Integrate Rasa with Twilio

How to Integrate Rasa with Twilio

January 24, 2025

Learn how to seamlessly integrate Rasa with Twilio to enhance your chatbot capabilities. Follow our step-by-step guide for a smooth integration process.

How to Connect Rasa to Twilio: a Simple Guide

 

Set Up Rasa Environment

 

  • Ensure you have Rasa installed. You can install it using pip if not already done:

 

pip install rasa

 

  • Create a new Rasa project (if you haven't). Use following command in your terminal:

 

rasa init

 

  • Navigate to your Rasa project directory:

 

cd your_project_name

 

Set Up Twilio Account

 

  • Go to the Twilio website and create an account if you don't have one.
  •  

  • Get your Account SID and Auth Token from the Twilio Console. You will need these for authentication.
  •  

  • Buy a phone number within Twilio which will be used for sending and receiving messages.

 

Install Twilio Python SDK

 

  • Install the Twilio Python client which will be used to interact with Twilio services:

 

pip install twilio

 

Create Custom Twilio Channel for Rasa

 

  • Create a new file under `your_project_name` named `twilio_channel.py`.
  •  

  • Add the following code to initialize your custom Twilio input channel:

 

from twilio.rest import Client
from rasa.core.channels.channel import InputChannel, UserMessage
from sanic import Blueprint, response
import json

class TwilioInput(InputChannel):
    def name(self) -> str:
        return "twilio"
        
    def blueprint(self, on_new_message):
        twilio_webhook = Blueprint("twilio_webhook", __name__)
        
        @twilio_webhook.route("/", methods=["POST"])
        async def receive_message(request):
            sender = request.json.get("From")
            message = request.json.get("Body")
            
            if message:
                await on_new_message(UserMessage(message, self.get_output_channel(), sender))
            
            return response.text("Message received")
        
        return twilio_webhook

 

Configure Rasa to Use Twilio Channel

 

  • Edit your Rasa project’s `credentials.yml` file to include Twilio channel custom configuration:

 

twilio_channel.TwilioInput:

 

Run Your Action Server

 

  • Start your Rasa actions server if you have custom actions defined:

 

rasa run actions

 

Run Rasa Server with Twilio Channel

 

  • Run the Rasa server with the custom Twilio input channel by specifying the `endpoint.yml` and `credentials.yml` files:

 

rasa run -m models --enable-api --cors "*" --debug

 

Configure Twilio Webhook

 

  • Login to your Twilio console and navigate to the phone numbers section.
  •  

  • Select the number you're using for your bot, then scroll to the Messaging section.
  •  

  • Set the "A Message Comes In" webhook URL to point to your Rasa server's public URL with `/webhooks/twilio/webhook` appended. e.g., `https://your-custom-url.com/webhooks/twilio/webhook`.

 

Test Your Bot

 

  • Send a message to your Twilio phone number and observe your Rasa bot interact through your terminal logs and respond accordingly.

 

This should effectively integrate Rasa with Twilio, allowing your Rasa bot to send and receive messages through Twilio. Adjust your configurations as necessary depending on specific requirements or additional settings within Twilio.

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

How to Use Rasa with Twilio: Usecases

 

Use Case: Intelligent Customer Support Chatbot

 

  • Integrate Rasa, an open-source machine learning framework for building conversational AI, with Twilio, a cloud communications platform, to deploy an intelligent customer support chatbot.
  •  

  • Utilize Rasa to design an advanced conversational model that understands and processes user intent efficiently.
  •  

  • Employ Twilio's API to send and receive messages, enabling communication with users through SMS, WhatsApp, or other messaging services.
  •  

  • Set up Rasa on your server and configure a webhook to connect it with Twilio's messaging interface.
  •  

  • Develop a conversational flow using Rasa's dialogue management tools, formulating responses that could include FAQs, troubleshooting guides, or informational queries.
  •  

  • Leverage Rasa's NLU capabilities to adapt to varied customer inputs and improve over time through machine learning feedback loops.
  •  

  • Ensure compliance with privacy and data protection regulations by securing the communication channels and handling sensitive user information appropriately.
  •  

 

Code Example: Integrating Rasa with Twilio

 

from twilio.rest import Client  
from rasa_core.channels.twilio import TwilioInput  
from rasa_core.agent import Agent

# Twilio credentials  
account_sid = 'your_account_sid'  
auth_token = 'your_auth_token'  

# Initialize the Twilio client  
twilio_client = Client(account_sid, auth_token)  

# Load your trained Rasa model  
agent = Agent.load("path_to_your_model")  

# Create the Twilio input channel  
input_channel = TwilioInput(  
    account_sid=account_sid,  
    auth_token=auth_token,  
    phone_number="your_twilio_phone_number"  
)

# Start the Rasa server  
agent.handle_channels([input_channel], 5004, serve_forever=True)  

 

Advantages

 

  • Seamless communication with customers through preferred messaging platforms enhances customer satisfaction.
  •  

  • Customizable interactions ensure the chatbot can adapt to a variety of business use cases.
  •  

  • Cost-effective solution for businesses to automate routine customer service tasks, freeing human agents for more complex issues.
  •  

 

Use Case: Personalized Healthcare Assistant

 

  • Combine Rasa, an open-source conversational AI framework, with Twilio, to create a personalized healthcare assistant that offers advice, schedules appointments, and provides medication reminders.
  •  

  • Utilize Rasa's capabilities to design a sophisticated dialogue system that processes user queries related to health issues, symptoms, and recommended actions.
  •  

  • Leverage Twilio's robust API to send alerts, reminders, and confirmations through SMS or WhatsApp, ensuring patients receive timely healthcare updates.
  •  

  • Deploy Rasa on a secure server and establish a webhook for seamless integration with Twilio's messaging services.
  •  

  • Craft personalized interactions by using Rasa's dialogue management features, allowing the assistant to provide tailored recommendations and manage appointment bookings.
  •  

  • Enhance flexibility by training Rasa's NLU component to recognize diverse patterns in patient input, supporting ongoing improvement via feedback and learning loops.
  •  

  • Ensure strict adherence to healthcare privacy regulations, maintaining confidentiality and security of all patient communications through encrypted channels.
  •  

 

Code Example: Integrating Rasa with Twilio for Healthcare

 

from twilio.rest import Client
from rasa_core.channels.twilio import TwilioInput
from rasa_core.agent import Agent

# Twilio credentials  
account_sid = 'your_account_sid'  
auth_token = 'your_auth_token'  

# Initialize the Twilio client  
twilio_client = Client(account_sid, auth_token)  

# Load your trained Rasa model  
agent = Agent.load("path_to_your_model")  

# Create the Twilio input channel  
input_channel = TwilioInput(  
    account_sid=account_sid,  
    auth_token=auth_token,  
    phone_number="your_twilio_phone_number"  
)

# Start the Rasa server  
agent.handle_channels([input_channel], 5004, serve_forever=True)  

 

Advantages

 

  • Improves patient engagement by facilitating easy and continuous communication through preferred messaging services.
  •  

  • Offers customizable pathways in patient interactions, thus adapting to unique healthcare needs efficiently.
  •  

  • Streamlines administrative tasks such as appointment handling and medication reminders, granting healthcare professionals more time to focus on critical patient care.
  •  

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

Troubleshooting Rasa and Twilio Integration

How to connect Rasa chatbot to Twilio SMS?

 

Setup Your Environment

 

  • Install Rasa by running:
    \`\`\`shell pip install rasa \`\`\`
  • Ensure you have a Twilio account and a verified phone number.

 

Configure Rasa for Twilio

 

  • Edit your `credentials.yml` in Rasa project:
    \`\`\`yaml twilio: account_sid: 'YOUR_ACCOUNT\_SID' auth_token: 'YOUR_AUTH\_TOKEN' twilio_number: 'YOUR_TWILIO\_NUMBER' \`\`\`

 

Test Your Setup

 

  • Run your Rasa server:
    \`\`\`shell rasa run --enable-api \`\`\`
  • Send a test SMS to your Twilio number to check Rasa receives it correctly.

 

Set Up Twilio Webhook

 

  • In your Twilio console, navigate to the phone numbers settings.
  • Set the webhook URL to your Rasa server's endpoint:
    `http://yourdomain.com/webhooks/twilio/webhook`

 

Deploy and Monitor

 

  • Ensure your Rasa server is accessible over the internet.
  • Monitor Twilio logs for messages sent and received.

 

Why is my Twilio number not responding to Rasa messages?

 

Check Configuration

 

  • Verify your Twilio number is set up correctly with a Webhook URL in the Twilio console pointing to your Rasa server.
  •  

  • Ensure the Twilio number has Messaging capabilities enabled. Double-check Rasa endpoint settings.

 

Test Webhook

 

  • Use a simple HTTP client like Postman to send a test message to the Webhook URL. Ensure Rasa listening for incoming requests.
  •  

  • Check for status codes. HTTP 200 indicates your webhook is working.

 

Debugging Rasa

 

  • Enable debug mode in Rasa. Check logs for incoming requests and processing issues. The command is:

 


rasa run --enable-api --debug

 

Verify Twilio Setup

 

  • Ensure credentials in Rasa’s credentials.yml match Twilio account SID, Auth Token, and phone numbers.
  •  

  • Navigate to Twilio Debugger to spot any errors with messages sent or delivered.

 

How to handle Twilio session timeouts in Rasa?

 

Handle Twilio Session Timeouts in Rasa

 

  • Understand the Root Cause: Twilio timeouts can occur due to inactivity or session length exceeding your Twilio settings.
  •  

  • Configure Session Length: Adjust the session expiry time in the Twilio console to match your Rasa bot's session management.
  •  

  • Implement Webhook for Session Management: Create a Rasa action to send a "keep-alive" message or handle timeouts with graceful exits and alerts.
  •  

  • Example Rasa Custom Action: Use a custom action to check session status and respond accordingly.

 


from rasa_sdk import Action
from rasa_sdk.events import SessionStarted

class ActionSessionTimeout(Action):
    def name(self):
        return "action_session_timeout"
    
    def run(self, dispatcher, tracker, domain):
        dispatcher.utter_message(text="Your session has timed out. Let's start anew!")
        return [SessionStarted()]

 

  • Test and Validate: Engage the bot with various session lengths to ensure timeouts are handled smoothly.
  • Don’t let questions slow you down—experience true productivity with the AI Necklace. With Omi, you can have the power of AI wherever you go—summarize ideas, get reminders, and prep for your next project effortlessly.

    Order Now

    Join the #1 open-source AI wearable community

    Build faster and better with 3900+ community members on Omi Discord

    Participate in hackathons to expand the Omi platform and win prizes

    Participate in hackathons to expand the Omi platform and win prizes

    Get cash bounties, free Omi devices and priority access by taking part in community activities

    Join our Discord → 

    OMI NECKLACE + OMI APP
    First & only open-source AI wearable platform

    a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
    a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
    online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
    online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
    App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
    App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

    OMI NECKLACE: DEV KIT
    Order your Omi Dev Kit 2 now and create your use cases

    Omi Dev Kit 2

    Endless customization

    OMI DEV KIT 2

    $69.99

    Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

    Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

    • Real-time conversation transcription and processing;
    • Develop your own use cases for fun and productivity;
    • Hundreds of community apps to make use of your Omi Persona and conversations.

    Learn more

    Omi Dev Kit 2: build at a new level

    Key Specs

    OMI DEV KIT

    OMI DEV KIT 2

    Microphone

    Yes

    Yes

    Battery

    4 days (250mAH)

    2 days (250mAH)

    On-board memory (works without phone)

    No

    Yes

    Speaker

    No

    Yes

    Programmable button

    No

    Yes

    Estimated Delivery 

    -

    1 week

    What people say

    “Helping with MEMORY,

    COMMUNICATION

    with business/life partner,

    capturing IDEAS, and solving for

    a hearing CHALLENGE."

    Nathan Sudds

    “I wish I had this device

    last summer

    to RECORD

    A CONVERSATION."

    Chris Y.

    “Fixed my ADHD and

    helped me stay

    organized."

    David Nigh

    OMI NECKLACE: DEV KIT
    Take your brain to the next level

    LATEST NEWS
    Follow and be first in the know

    Latest news
    FOLLOW AND BE FIRST IN THE KNOW

    thought to action

    team@basedhardware.com

    company

    careers

    events

    invest

    privacy

    products

    omi

    omi dev kit

    personas

    resources

    apps

    bounties

    affiliate

    docs

    github

    help