SMS autoresponders are powerful tools for getting information out fast.

Imagine you rent out apartments. You can automatically send apartment listings to interested people. Or, you can ask new clients to join a mailing list via automatic SMS. Entire conversations can be fully automated — a guest can talk to a virtual agent to schedule cleaning, ask for more supplies, and other common requests.

When you do the up-front work to build an autoresponder into your application, you can interact with end users with minimal effort. Increased customer engagement, satisfaction and time saving are all added benefits.

In this tutorial, you’ll learn how to build an SMS autoresponder for an event venue using Python and ClickSend.

What is an SMS autoresponder?

An SMS autoresponder is a mobile number with an automation rule that takes action whenever it receives messages with certain keywords.

However, autoresponders can do much more than provide information.

You can use autoresponders to collect user data for customer support and to subscribe customers to SMS automations and/or mailing lists. Or, to create a virtual assistant for customer service.

Setting up SMS autoresponders in Python

In this example, the autoresponder will answer queries for a hypothetical event venue via SMS. Visitors will be able to send messages with the word “Friday”, “Saturday”, or “Sunday” and receive information about the event scheduled on that day.

For example, a request such as “Hey, what’s happening on Sunday?” will be answered with a message like this: “Local pop star concert. Performer: Ariana Grandeur. Starts at 9 p.m. Entry: $15.”

Note: This tutorial explains how to use ClickSend’s SDK. ClickSend also offers an intuitive web UI with similar features (in case you’re looking for a no-code solution).

Prerequisites

Here’s what you’ll need to follow this tutorial:

Install the Python SDK

To call our API from Python, you’ll need to install the official SDK package so you can import it into your code. Find our official Python SDK at our Github repo.

To install, run the following command:

pip install git+https://github.com/ClickSend/clicksend-python.git

Your first automation rule

To create the autoresponder, you’ll need to set up some automation rules. In this tutorial, we’ll submit 3 rules to the ClickSend API — one for each day there will be an event.

To submit an automation rule to ClickSend, create a new file called autoresponder.py and open it in an editor.

Next, import all the necessary packages. You’ll need to use clicksend_client, which is ClickSend’s SDK, and ast, which, among other things, can convert a string to a dictionary:

import clicksend_client
from clicksend_client.rest import ApiException
import ast

Add your authorisation details:

configuration = clicksend_client.Configuration()
configuration.username = 'USERNAME'
configuration.password = 'API_KEY'

Substitute USERNAME with your username and API_KEY with your API key. You can find the API key in the ClickSend dashboard:

Screenshot of the ClickSend dashboard showing where to find the API key

You’re ready to create your first SMS rule. First, initialise an API instance:

api_instance = clicksend_client.InboundSMSRulesApi(
clicksend_client.ApiClient(configuration))

Create a rule object:

This contains the instructions for an automation called Thursday. Since the message_search_type is 2 and message_search_term is Thursday, it will automatically respond to messages that contain the word “Thursday”. For more information on these parameters, you can check the official docs.

 inbound_sms_rule = clicksend_client.InboundSMSRule(
    dedicated_number="*",
    rule_name="Thursday",
    message_search_type=2,
    message_search_term="Thursday",
    action="AUTO_REPLY",
    action_address="",
    enabled=1
)

Unfortunately, the function has no parameter for the response body — the text that the autoresponder should send back to the user — so you cannot add it to the object via SDK methods.

But the API does contain a field for this parameter. If you send a body field in the JSON message to the API, it will add it to the automation so that you can add the response text manually.

To do that, convert the object you’ve created to a dictionary and add the body property manually:

try:
    api_response = api_instance.sms_inbound_automation_post(rule)
    print(api_response)
except ApiException as e:
    print("Exception when calling InboundSMSRulesApi->sms_inbound_automation_post: %s\n" % e)

Submit this automation to ClickSend:

try:
    api_response = api_instance.sms_inbound_automation_post(rule)
    print(api_response)
except ApiException as e:
    print("Exception when calling InboundSMSRulesApi->sms_inbound_automation_post: %s\n" % e)

After running the script, you should get the following response:

{
    "http_code": 200,
    "response_code": "SUCCESS",
    "response_msg": "Your record has been added.",
    "data": {
        "inbound_rule_id": 799903,
        "dedicated_number": "*",
        "rule_name": "Thursday",
        "message_search_type": 2,
        "message_search_term": "Thursday",
        "action": "AUTO_REPLY",
        "action_address": "",
        "body": "Thursday, never looking back",
        "enabled": 1,
        "webhook_type": "post"
    }
}

Automatically generating autoresponders

Manually adding events by editing rules can take time. It’s better to do this automatically with Python so that the script for the venue automatically generates the rules from event descriptions. In real life, you would run this script at the start of each week to set the SMS automations for the week.

Before following this part, delete everything in your file up until the initialisation of the API instance.

First, you need to create a function that will mock an API response. It will get the week’s event descriptions as a dictionary. In real life, this would be an API call to your event management system. Use the following code:

def get_events():
    return {
        "Friday": "A rowdy punk-rock concert. Band: The Mash. Starts at 10 p.m. Entry: free.",
        "Saturday": "Warm indie get-together. Band: Antarctic Monkeys. Starts at 8 p.m. Entry: $5",
        "Sunday": "Local pop star concert. Performer: Ariana Grandeur. Starts at 9 p.m. Entry: $15"
    }

Next, create a helper function that will generate a rule when given a day and a description:

def create_rule(day, description):
    inbound_sms_rule = clicksend_client.InboundSMSRule(
        dedicated_number="*",
        rule_name=day,
        message_search_type=2,
        message_search_term=day,
        action="AUTO_REPLY",
        action_address="",
        enabled=1
    )
    rule = inbound_sms_rule.to_dict()
    rule["body"] = description
    return rule

Loop through the dictionary of events and upload the rules to ClickSend.

If a rule is already there, you want to update it and not create a new one. This makes sure that you only have one rule for each day so that you’re not sending multiple messages to the user. You can create a helper function that checks for the existence of a rule and, if it exists, updates it instead of posting another one.

The code for such a function is below:

def post_or_update_rule(new_rule):
    search_term = new_rule["message_search_term"]
    try:
        sresponse = api_instance.sms_inbound_automations_get()
        response = ast.literal_eval(sresponse)
        rules = response['data']['data']
        id = None
        for rule in rules:
            if rule["message_search_term"] == search_term:
                id = rule["inbound_rule_id"]
                break
        if id is None:
            api_response = api_instance.sms_inbound_automation_post(new_rule)
            print(api_response)
        else:
            api_response = api_instance.sms_inbound_automation_put(id, new_rule)
            print(api_response)
    except ApiException as e:
        print("Exception: %s\n" % e)

This code fetches all the rules from ClickSend and uses ast.literal_eval() to convert the response (which is a string) to a valid Python dictionary. If a rule has the same trigger phrase as the rule you’re submitting, it gets the ID and updates it. You’re assuming that the function doesn’t need to be defined for cases where there are multiple items with the same trigger phrase.

If there are no rules with the given trigger phrase, it will post the rule.

All that’s left is to call these functions:

events = get_events()
for day in events:
    rule = create_rule(day, events[day])
    post_or_update_rule(rule)
{
    "http_code": 200,
    "response_code": "SUCCESS",
    "response_msg": "Your record has been updated.",
    "data": {
        "inbound_rule_id": 799928,
        "dedicated_number": "*",
        "rule_name": "Friday",
        "message_search_type": 2,
        "message_search_term": "Friday",
        "action": "AUTO_REPLY",
        "action_address": "",
        "body": "A rowdy punk-rock concert. Band: The Mash. Starts at 10 p.m. Entry: free.",
        "enabled": 1,
        "webhook_type": "post"
    }
}
{
    "http_code": 200,
    "response_code": "SUCCESS",
    "response_msg": "Your record has been updated.",
    "data": {
        "inbound_rule_id": 799929,
        "dedicated_number": "*",
        "rule_name": "Saturday",
        "message_search_type": 2,
        "message_search_term": "Saturday",
        "action": "AUTO_REPLY",
        "action_address": "",
        "body": "Warm indie get-together. Band: Antarctic Monkeys. Starts at 8 p.m. Entry: $5",
        "enabled": 1,
        "webhook_type": "post"
    }
}
{
    "http_code": 200,
    "response_code": "SUCCESS",
    "response_msg": "Your record has been updated.",
    "data": {
        "inbound_rule_id": 799930,
        "dedicated_number": "*",
        "rule_name": "Sunday",
        "message_search_type": 2,
        "message_search_term": "Sunday",
        "action": "AUTO_REPLY",
        "action_address": "",
        "body": "Local pop star concert. Performer: Ariana Grandeur. Starts at 9 p.m. Entry: $15",
        "enabled": 1,
        "webhook_type": "post"
    }
}

Note: this example calls the lookup on every call for simplicity, you may want to move the call to reduce lookups.

Testing automations

Screenshot showing the Quick SMS page in the ClickSend dashboard

You can view all of your active automations in Inbound SMS. If you want to test a specific automation, use the ClickSend dashboard to send a quick SMS to yourself:

The messages should show up in your message history:

Screenshot of message history with received message and automatically generated response

As you see, the automation successfully responds to any inquiry using weekend day names with information about the event scheduled for that day.

Try it yourself

Building software or components in Python? Not only can you add autoresponders, but you can call our other endpoints to add/edit contact lists, manage your account or send messages via MMS, voice, fax and more. Check out our Python API documentation here.