How to Send Translated Messages with Google and Django

July 26, 2024
Written by
Kabaki Antony
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by
Diane Phan
Twilion

The world has increasingly become connected, and you might have friends from various regions around the globe. You will want to call them, leave automated voice messages, or send emails to them. This, however, might be a challenge if you don’t share a language.

In this tutorial, you will build a service named heart2heart where you will pass short messages over a call using Twilio Programmable Voice, or emails using SendGrid. The recipient will receive the message in their own language, with the translation service provided by Google Translation API.

Prerequisites

To follow through with this tutorial successfully, you will need the following:

Set up the voice translation application

For this tutorial, you will have access to a scaffold project that you can use as a starting point.

The scaffold project will include the bare structure and the initial dependencies needed to set it up. By starting with a common foundation, you can focus on the specific concepts and techniques covered in the tutorial without worrying about the initial project setup complexities.

Clone the repository

Get the scaffold project by cloning the repository as shown below:

git clone -b ch-scafold https://github.com/KabakiAntony/heart2heart.git

To start working on the project, get into the project directory using the below command:

cd heart2heart

Create and activate a virtual environment

A virtual environment allows you to create a project in isolation without affecting the global Python installation, meaning you can work on different projects, each with its distinct dependencies.

To create the virtual environment you will utilize the virtualenv package. It is not part of the standard Python library, so install it using the following command:

pip install virtualenv

That will install the virtualenv package to be part of your global Python packages. Upon successful installation of the package, proceed and create a virtual environment in the "heart2heart" project using the following command:

virtualenv venv

The command creates a virtual environment named "venv". Activate the virtual environment with the commands appropriate for your operating system:

For Linux/ MacOS

. venv/bin/activate

For Windows

. venv\Scripts\activate

Install dependencies

The scaffold project has a few dependencies that you will need to enable you to set it up and run successfully. Install them using the following command:

pip install -r requirements.txt
python manage.py runserver

This will launch a development server. You can see if the project is set up correctly by pointing your browser to http://127.0.0.1:8000. If all is well you should see the page below:

The project comes with the essential files and configurations to get you up and running quickly. Take a moment to explore the project structure and familiarize yourself with any pre-configured settings. If you encounter any issues during setup, see this guide on how to set up a Django project.

Create a .env file

In this project, you will utilize the SendGrid API and the Twilio Programmable Voice API. To be able to communicate with these services you will need API keys. It is a recommended practice to keep those keys away from your code and fetch them from an environment file or some key management solution whenever you need to use them. In the root of your project create a file named .env and place the following variables in it:

# .env
SENDGRID_API_KEY=
DEBUG=on
DEFAULT_FROM_EMAIL=
TWILIO_ACCOUNT_SID=
TWILIO_AUTH_TOKEN=
TWILIO_PHONE_NO=
TEMPLATE_ID=

Save the file as it is for now. You will fill in the required variables in the steps that follow.

Set up the project to make calls

If you haven’t signed up for your free Twilio number yet, please follow this guide on how to get a phone number. This will give you a trial account that is sufficient for this tutorial.

Log in to the Twilio dashboard. It should look like this:

Twilio Console Dashboard

To get your API keys, scroll down to the Account Info part of your dashboard. There you will see your Account SID, Auth Token , and the phone number Twilio has assigned to you.

Account info section of Twilio console

Copy the values and update the . env file in the following sections.

TWILIO_ACCOUNT_SID=ACXXXXXXX
TWILIO_AUTH_TOKEN=baXXXXXX
TWILIO_PHONE_NO=+12XXXXXXX

Save the changes and close the file.

Install the necessary helper libraries

For the application to make outbound calls, it has to connect to Twilio servers. To do that, you have to install the Twilio helper library. The library will connect to Twilio APIs and make API calls on your behalf.

Install it with the following command:

pip install twilio

Once the library has been installed, you can now create functionality that will receive the user message and pass it as a voice message. In the project, navigate to the messageHandler app, then open up the views.py file. Update it with the following code:

import os
from twilio.rest import Client
# … other code
def voice_message(request):
	if request.POST:
    	sender_name = request.POST.get('sender_name')
    	recipient_name = request.POST.get('recipient_name')
    	recipient_phone_no = request.POST.get('recipient_phone_no')
    	message = request.POST.get('message')
    	language = request.POST.get('language')
    	constructed_message = f"""
        	Hello {recipient_name}, we have a heart2heart message
        	from {sender_name}, {message}."""
    	client = Client(
        	os.environ.get('TWILIO_ACCOUNT_SID'),
        	os.environ.get('TWILIO_AUTH_TOKEN')
    	)
    	client.calls.create(
        	twiml=f"""
        	<Response>
            	<Say voice="Alice">
                	{constructed_message}
            	</Say>
        	</Response>""",
        	to=recipient_phone_no,
        	from_=os.environ.get('TWILIO_PHONE_NO')
    	)
    	messages.add_message(request, messages.SUCCESS,
                         	"Your message is sent successfully.")
		return redirect('messageHandler:home')

The code defines a view function named voice_message. The function will handle POST requests triggered by the user submitting the form on the homepage of the heart2heart service. The form has various fields such as sender name, recipient name, and recipient phone number. Upon receiving the form data through the request.POST object, the function extracts the relevant information, constructs a personalized message, assigns it to constructed_message, and proceeds to initiate an automated voice call using the Twilio Programmable Voice API.

To communicate with the Twilio API, the code utilizes the Twilio Client object and passes the Twilio account SID and authentication token (TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN) that have been obtained from the . env file. Once the connection is established, the client.calls.create method is invoked to initiate a phone call. The twiml parameter within the method represents Twilio Markup Language, which contains the message to be read out to the recipient.

Save the changes and close the file.

Set up the project to send emails

To send emails, you need to have a SendGrid account and create an API key for the service. If you do not have one already, create a free SendGrid account here.

Create an API Key

Navigate to your SendGrid dashboard. Go to Settings, then API Keys, and select Create API Key on the top left corner of the view.

Screenshot showing creation of SendGrid API keys

Give the key a descriptive name so that you will know what service it belongs to if you come back to the dashboard later. Leave the key permission on the default selection for full access and click on the Create & View button.

Create API key view

Upon creation of the key, you will be redirected to a new window, with the key shown in plain text.

Copy the key and paste it into the .env file assigning it to the SENDGRID_API_KEY key in the file.

SENDGRID_API_KEY=SG….

After adding the SENDGRID_API_KEY, update the DEFAULT_FROM_EMAIL key too, with the email address you used to sign up on SendGrid. Save the changes and close the . env file.

Create a dynamic template with SendGrid

SendGrid can send plain text emails, but for this service, you will utilize SendGrid's ability to send dynamic templates.

To send emails with dynamic templates, you can reuse available templates provided by SendGrid, or create some yourself. For this application, you may utilize the built-in templates. Go to the Email API section, and click on the Dynamic Templates.

Create dynamic template option

Click on the Create a Dynamic Template button. You will be prompted to give the template a name. After entering a name, click on the Create button.

Naming a dynamic template

Upon the creation of the template, you will be redirected to the templates page. Select the template you have created. This will show you the template ID.

A selected template screenshot

Copy the id and paste it under the TEMPLATE_ID key in the .env file.

TEMPLATE_ID=d-

Save the .env file and close it. Click on the Add Version button to continue working on the template. This will take you to a new page where you will be required to select the design of the template you want to use. The default option for designs is “ Your Email Designs.”

Use this option if you want to design the template yourself. However, for this tutorial, you will utilize the SendGrid provided designs, so select SendGrid Email Designs.

Select a  template design

Once you select the design you want to use, your browser will redirect you, to where you can edit the template to suit your liking.

Template desgin edit.

Twilio templates utilize handlebars.js to pass values to templates, so recipient_nameand message will be replaced by values you will pass to the template at the time of sending the email. Once you are satisfied with the design, click on the Save button to save it.

Update the email_message function

To send emails with the dynamic template you have created, you have to set up the email_message function and install the SendGrid client library into the project using the following command:

pip install sendgrid

Open the messageHandler/views.py file, and add the following lines of code to the file.

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, From, To
# … other code
def sendgrid_send_mail(recipientEmail, specialMessage, recipientName):
	mail = Mail()
	mail.from_email = From(
    	email=os.environ.get('DEFAULT_FROM_EMAIL'),
    	name="heart2heart"
	)
	mail.to = [
    	To(
        	email=recipientEmail,
        	name=recipientName
    	)
	]
	mail.dynamic_template_data = {
    	"recipient_name": recipientName,
    	"message": specialMessage
	}
	mail.template_id = os.environ.get('TEMPLATE_ID')
	try:
    	sg_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    	sg_client.send(mail)
	except Exception as e:
    		print(f"Error sending email: {str(e)}")
def email_message(request):
	if request.POST:
    	sender_name = request.POST.get('sender_name')
    	recipient_name = request.POST.get('recipient_name')
    	recipient_email = request.POST.get('recipient_email')
    	message = request.POST.get('message')
    	language = request.POST.get('language')
    	constructed_message = message + f" ,from {sender_name}"
    	sendgrid_send_mail(
        	recipientEmail=recipient_email,
        	specialMessage=constructed_message.capitalize(),
        	recipientName=recipient_name,
    	)
    	messages.add_message(request, messages.SUCCESS,
                         	"Your special email has been sent.")
	return redirect('messageHandler:home')

The code update imports the SendGridAPIClient class that will enable the code to interface with the SendGrid API and send your emails. In this code, you have a helper function called sendgrid_send_mail. This function takes in three arguments: the email of the recipient, the message you want to pass to them, and their name.

In the sendgrid_send_mail function, you create a mailobject that you will use to construct the various object parameters needed to send a dynamic email. The first thing you assign to it is the from_email . This object contains the email address and name of the sender. Then you create a to object that contains the email address and name of the recipient.

Since you are using dynamic templates in this project, the data you want to be inserted in the template when the email is sent is passed into the dynamic_template_data as key-value pairs.

The next thing you attach to the mail object is the ID of the template. Implement a try-and-catch block at the end of the function to send the email or print a message to the console in case of a failure.

To assemble the final mail, you call the sendgrid_send_mail function in the email_message function and pass it the required data as you get it from the request.POST object.

Set up the translation API on Google Cloud Platform

For your friends to receive your messages in the language you select, the messages need to be translated from your sending language to their language. To do that you will utilize Google Translation API.

To get access to the Google Translation API you will need to have a Gmail account, then use it to log in to Google Cloud. If you don’t have a Gmail, create one here. Then log in to GCP (Google Cloud Platform).

Note that to sign up to GCP you will need to provide a payment method, but you will not be charged initially. The payment information is only used to confirm that a human is signing up to use the platform. The 90-day trial account will initially award you with $300 in free credits.

Navigate to the Google Cloud console.

Project creation on GCP

Create a new project by clicking on the NEW PROJECT button in the top right corner of the window. That will take you to the page below.

Create new project on GCP

You can leave the default name for the project, or you can give the project a new name. Once that is done click on the CREATE button. Upon successful creation of a new project, it is selected by default.

On the search bar next to the project selection, search for "Cloud Translation API".

Cloud translation API

Click on the result for "Cloud Translation API". This will take you to the below page:

Cloud Translation API selection

Click on the ENABLE button to enable the translation API for the selected project.

Enable billing

For the Translation API to work for the selected project, you need to enable billing. To do that, open the console Navigation menu – or the hamburger menu on the left – and then select Billing . Click on the Enable buttonto enable billing for your project.

Install the translation client library

Google provides official client libraries to assist you in making requests to the API. GCP offers two APIs for translation: Basic and Advanced. Each service has its own client library. For this use case, you will use the basic translation API. To install the library for the basic translation service use the following command:

pip install google-cloud-translate==2.0.1

Authentication to Google Cloud Platform 

Upon installation of the translation library, you have to authenticate with Google. Google offers different ways of authenticating. To run translation from a development environment, Google recommends Application Default Credentials, which look for credentials in environment variables or credentials set by the Google Cloud CLI. This is the method you are going to use to authenticate your application.

Install the Google Cloud CLI

There are various ways in which you can install the Google Cloud CLI. You can choose the one that works for you here. For demonstration purposes, this is how you install it in Ubuntu:

sudo snap install google-cloud-cli --classic

Initialize it after installation using the following command:

gcloud init

That command will initialize the CLI, redirect you to a browser, and ask you to log in using a Gmail account. If you have more than one account, log in with the one you used to activate GCP. After a successful login, select the project you have created above.

Create Application Default Credentials

In the final step, you will create credentials for your project. These credentials can be used by any library that accepts them. Create them using the following command:

gcloud auth application-default login

The above command will open your browser, asking you to log in to Google Cloud one more time. On success, a credentials file will be created and saved in your home directory. That completes the authentication setup. Your application is now ready to communicate with the translation API.

Create the translation function

If you’ve come this far, you’ve finalized the creation of a GCP project, and login credentials. It is time to create the function that will handle translation in your application. Update the messageHandler/views.py file with the following code.

from google.cloud import translate_v2 as translate
def translate_text(target, text):
	translate_client = translate.Client()
	if isinstance(text, bytes):
    	text = text.decode("utf-8")
	result = translate_client.translate(text, target_language=target)
	return result

The above code imports the translate_v2 library from google.cloud module. It then creates a custom translate_text function that takes in two arguments: the target which is the language you want your text translated into, and the text that is being translated.

Update the voice_message and add the following lines of code to it after the line containing the constructed_message variable assignment and before the messages.add_message() method.

# messageHandler/views.py 
def voice_message(request):
	# … other code
    	result = translate_text(language, constructed_message)
    	translated_message = result.get('translatedText')
    	client = Client(
        	os.environ.get('TWILIO_ACCOUNT_SID'),
        	os.environ.get('TWILIO_AUTH_TOKEN')
    	)
    	client.calls.create(
        	twiml=f"""
        	<Response>
            	<Say voice="Alice">
                	{translated_message}
            	</Say>
        	</Response>""",
        	to=recipient_phone_no,
        	from_=os.environ.get('TWILIO_PHONE_NO')
    	)
	# … other code

The updated voice_message view function can now call the translate_text function to pass in the text and the language you want a user to receive a message in. When you press the Place Call button, the message will be translated. When a call is placed to the user, they will receive it in the language you set on the homepage.

Update the email_message function, and add the following lines of code to it after the line containing the constructed_message variable assignment and before the messages.add_message() method.

def email_message(request):
	# … other code
    	result = translate_text(language, constructed_message)
    	translated_message = result.get('translatedText')
    	sendgrid_send_mail(
        	recipientEmail=recipient_email,
        	specialMessage=translated_message.capitalize(),
        	recipientName=recipient_name,
    	)
  # … other code

Similar to the voice_message view function, the message you pass will be translated. When an email is sent the user will receive the email in their language.

Test the translation voice message application

Having followed all the steps of the tutorial, you should have a complete application.

To test if everything works, save all files and close them. In the command line of your project activate the virtual environment, and run the development server using the following commands:

. venv/bin/activate && python manage.py runserver

That will give you the following link: http://127.0.0.1:8000. Visit it, and you will see the home page. Here, you can follow the CTA and select if you want to send a voice message or an email message.

Test sending an email by selecting Email message, which will give you the following window. Enter all the required information as shown below, and click on the Send email button.

Upon sending the above message, the user will receive the below message translated to French from English.

You can now go ahead and try the voice message option.

Few things to note

  • Making calls using a Twilio trial account will only make calls to verified numbers.
  • Sending emails using a SendGrid trial account will only send a hundred emails per day.
  • The Google Trial account is only valid for 90 days with a credit of $300 for use.
  • If you want to read further on how to configure Google Cloud CLI, see their documentation here.

What's next for translating message apps?

You have built a way to send automated voice messages and dynamic emails to your friends that will automatically translate the message to their language.

You can find the source code for the completed project here. To build similar or more advanced applications, please visit Twilio.com or SendGrid.com, and upgrade your account to enjoy the full benefits of a paid account.

Have a look at the following articles on the Twilio blog to build similar applications:

Kabaki Antony is a full-stack software engineer and a technical writer with a passion for creating innovative digital experiences. When not coding, he enjoys sharing knowledge with others by writing technical articles to help developers hone their skills. He can be reached at kabaki[dot]antony [atl] gmail [dot] com or on X [at] kabakiantony