Skip to content

Arsey-Tracy/AT-API_DOCS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

Building a Simple Voice-Based Balance Inquiry system with AfricasTalking Voice API using Flask.

AfricasTalking Products

Hello their fellow nerds, Arsey here and welcome to this tutorial! In this guide, we’ll walk through how to build a simple voice-based balance inquiry system using flask and AfricasTalking Voice API. The idea is simple: when a user calls our service, the will hear a voice response informing them of the account balance.

Let’s get started!

What Are We Building?

We’re creating a Flask web service that integrates with AfricasTalking Voice API to:

  1. Receive incoming calls.
  2. Check the caller’s balance in a simulated database.
  3. Read out the balance using text-to-speech.
  4. End the cal gracefully.

This is a great way to build IVR (Interactive Voice Response) systems for services like banking, customer support and more!

Setting Up Our AfricasTalking Account, Phone Number, and Callback URL

Before we can test our voice-based inquiry system, we need to set up our AfricasTalking account, register phonenumber, and configure our callback URL. Sounds like hard work, no… just follow these steps to get everything ready!

Create an AfricasTalking Account

If you don’t have an account yet, sign up for free on AfricasTalking or else login into their platform.

Steps to create an account:

  1. Go to AfricasTalking Sign-up Page.
  2. Click Sign Up and enter your details.
  3. Verify your email and log in to your account
  4. Now due to security purposes they might send a Two-Factor Authentication so make sure you check your email for the OTP sent.
  5. Now you’ll be logged in into your account

Getting a phone Number for Voice calls

AfricasTalking provides sandbox numbers for testing in their developer environment. But for the sandbox environment it’s not supported yet so we we’ll use a live environment, and that's good approach to test in a live enviroment.

Steps to get a test phone number:

  1. Log in to your AfricasTalking Dashboard

  2. Click on the prominent green plus icon to create a new team and enter the team name and save

  3. A new team will be created, click on it and look for the create app button, enter the your app name, your username ( let’s say you appname is InquireBal, the username could be the same but with lowercase letters like inquirebal), then choose a country and currency code, and save.

  4. Now you’ll have your app ready, now navigate to the side panel and choose voice, under voice click on phone Numbers, if you don’t have a phone Number, create one by navigating to the side panel, click on request this will display a form so enter the fields.

    - In the category section, choose regular: business Number
    - Enter your name/organization and email.
    - choose a country and a telecom provider 
    - You can add additional comments but it’s optional then hit the submit request button
    

Wait for some few minutes and you’ll have your phone number ready to verify go back to phone numbers under the voice product if you see number, congrats, you have done the first part. Sip on some coffee, have some snacks because we’re now going to build our Voice based inquiry system. Done, let’s now build our product.

Building our Voice-based Balance inquire System

Before we dive into code, ensure you hve Python and flask installed. If not, install python form their official website and then install flask using this command in your terminal or command prompt on you PC pip install flask

Now let’s build th flask App

from flask import Flask, request, Response  # Import necessary modules from Flask and for XML handling
import xml.etree.ElementTree as ET  # Import ElementTree for XML parsing (not used in this example)

app = Flask(__name__)  # Create an instance of the Flask class, which represents the web application

@app.route('/checkBalance')  # Define a route for the URL path '/checkBalance'
def check_balance():
    return "Check MyBalance"  # Return a simple string response when this route is accessed

if __name__ == '__main__':  # Ensure the script runs only when executed directly (not imported as a module)
    app.run(debug=True)  # Start the Flask development server with debugging enabled

This code sets up a basic Flask web server. It defines a single route (/checkBalance) that responds with the text "Check MyBalance" when accessed. Flask is a lightweight web framework that allows you to define routes and handle HTTP requests easily. The debug=True option enables debugging features, such as auto-reloading the server on code changes and providing detailed error messages.

from flask import Flask, request, Response
import xml.etree.ElementTree as ET

app = Flask(__name__)

BALANCE_DB = {
    # use your phone number instead
    '+256707522509': 2000,
}

@app.route('/checkBalance', methods=['POST'])
def check_balance():
    session_id = request.form.get('sessionId')
    is_active = request.form.get('isActive')
    
    if is_active == '1':
        caller_number = request.form.get('callerNumber')
        
        if caller_number in BALANCE_DB:
            balance = BALANCE_DB[caller_number]
            text = f"Arsey, you balance is {balance} shillings. Good bye."
        else:
            text = "Sorry, your phone number is not registered for this service. Good Bye."
            
            # Creae XML Response
            response = ET.Element('Response')
            say_element = ET.SubElement(response, 'Say')
            say_element.text = text
            
            # Convert XML to String
            xml_response = ET.tostring(response, encoding='utf-8', method='xml')
            
            return Response(xml_response, mimetype='text/xml')
    else:
        duration = request.form.get('durationSeconds')
        currency_code = request.form.get('currencyCode')
        amount = request.form.get('amount')
        
        # In a real world application, you would store these details in a database.
        # For Example:
        #    log_call_details(duration, currency_code, amount)

        return '', 204 # No Content response

if __name__ == '__main__':
    app.run(debug=True)

How does this code work

Let's break dow the key parts of the code.

Handling incoming calls

When a call comes in, AfricasTalking sends a post request to our /checkBalance endpoint with details like:

  • sessionId --> a unique ID for the call.
  • isAcive --> indicates if the call is still ongoing (1) or has ended (0).
  • callerNumber --> the phone number of the caller.

Here we first check if the call is active:

is_actve = request.form.get('isActive')

if is_active == '1':

Retrieving the caller's balance

We then get the caller's phone number and check of it exists in our BALANCE_DB:

caller_number = request.form.get('callerNumber')
        
if caller_number in BALANCE_DB:
    balance = BALANCE_DB[caller_number]
    text = f"Arsey, you balance is {balance} shillings. Good bye."
else:
    text = "Sorry, your phone number is not registered for this service. Good Bye."

And if the caller is found, we read out their balance. otherwise, we let them know they are not registered.

Responding with a voice

AfricasTalking expects an XML response for voice interactions. we create one like this:

response = ET.Element('Response')
say_element = ET.SubElement(response, 'Say')
say_element.text = text

then, we convert it to XML and return it.

xml_response = ET.tostring(response, encoding='utf-8', method='xml')
            
return Response(xml_response, mimetype='text/xml')

Handling Call Completion.

When a call ends, we get additional details like call duration, currency_code, amout charged. we can log thes details if needed.

    else:
        duration = request.form.get('durationSeconds')
        currency_code = request.form.get('currencyCode')
        amount = request.form.get('amount')

Deploying the Flask App

To test this locally, run: python main.py

However, AfricasTalking cannot acess your localhost, so you need to have live url or expose it using ngrok, there are many tools for the job but i recommend using replit or pythonanywhere for simplicity in this guide we'll use replit.

Create a Replit Account

If you don't have one already,, signup for free at Replit.

Create an App in Replit

To deploy your Flask app, we’ll use Replit for simplicity. Follow these steps:

Step 1: Create a Replit Account

If you don’t already have an account, sign up for free at Replit.

Step 2: Create a Flask App

  1. Click the Create App button.
  2. Choose the Flask template.
  3. Give your app a name and click Create App.

This will load your development environment.

Step 3: Add Your Flask Code

  1. Open the main.py file in your Replit project.
  2. Delete the existing code in main.py.
  3. Paste your voice-based Flask code into the file.

Step 4: Run the Server

  1. Click the green Run button to start the server.
  2. In the webview preview, click the URL provided by Replit.
  3. Copy the URL for the next step.

Step 5: Configure AfricasTalking Callback

  1. Go to your AfricasTalking dashboard.
  2. Under Phone Numbers, click the three horizontal dots next to your number.
  3. Select Callback and paste your Replit URL, appending /checkBalance to it.


Make sure to append /checkBalance after the url you pasted

  1. Save the changes.

Step 6: Test Your Application

  1. Dial the phone number provided by AfricasTalking.
  2. You should hear the account balance or a message indicating the phone number is not registered.

Congratulations! Your voice-based balance inquiry system is now live.

About

AT-API_DOCs is well crafted environment for AfricasTalking Developers to easily learn and build production ready products that utilize AfricasTalking APIs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages