Building a flight booking chatbot in Python

Hands on AI
5 min readApr 21, 2023

--

Building a ticket booking chatbot can be a great way to automate customer support and improve the overall experience for your users. In this tutorial, we will guide you through the steps to build your own ticket booking chatbot using Dialogflow, a natural language processing platform powered by Google.

Step 1: Create a Dialogflow account

To get started, create a free account on Dialogflow. Once you have created an account, create a new agent and give it a name, description, and default language.

Python code:

import dialogflow_v2 as dialogflow
from google.protobuf.json_format import MessageToJson

client = dialogflow.AgentsClient()
parent = client.common_project_path('<PROJECT_ID>')

agent = dialogflow.types.Agent(
display_name='<AGENT_NAME>',
default_language_code='<DEFAULT_LANGUAGE_CODE>'
)
response = client.set_agent(
agent=agent,
update_mask=dialogflow.field_mask.FieldMask(
paths=['display_name', 'default_language_code']
),
parent=parent,
)

print(MessageToJson(response))
{
"name": "projects/<PROJECT_ID>/agent",
"displayName": "<AGENT_NAME>",
"defaultLanguageCode": "<DEFAULT_LANGUAGE_CODE>",
"timeZone": "America/Los_Angeles",
"isWebhookEnabled": false,
"matchMode": "MATCH_MODE_HYBRID"
}

Step 2: Define intents and entities

Intents are the building blocks of a Dialogflow chatbot. They represent the user’s intentions and the actions that the bot should take in response. Entities, on the other hand, represent specific pieces of information that the bot needs to collect from the user to perform an action.

Python code:

import dialogflow_v2 as dialogflow
from google.protobuf.json_format import MessageToJson

client = dialogflow.IntentsClient()
parent = client.common_agent_path('<PROJECT_ID>')

intent1 = dialogflow.types.Intent(
display_name='<INTENT_NAME>',
training_phrases=[
dialogflow.types.Intent.TrainingPhrase(parts=[
dialogflow.types.Intent.TrainingPhrase.Part(
text='I want to book a ticket for {Destination}',
entity_type='@sys.geo-city'
)
])
],
messages=[
dialogflow.types.Intent.Message(
text=dialogflow.types.Intent.Message.Text(
text=['When do you want to travel?']
)
)
],
parameters=[
dialogflow.types.Intent.Parameter(
display_name='Destination',
entity_type_display_name='@sys.geo-city',
mandatory=True
)
]
)

response = client.create_intent(
parent=parent,
intent=intent1,
)

print(MessageToJson(response))
{
"name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>",
"displayName": "<INTENT_NAME>",
"priority": 500000,
"webhookState": "WEBHOOK_STATE_ENABLED",
"isFallback": false,
"trainingPhrases": [
{
"name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>/trainingPhrases/1",
"parts": [
{
"text": "I want to book a ticket for ",
"entityType": "@sys.geo-city",
"alias": "",
"userDefined": false
}
]
}
],
"messages": [
{
"text": {
"text": [
"When do you want to travel?"
]
}
}
],
"parameters": [
{
"name": "Destination",
"displayName": "Destination",
"value": "",
"mandatory": true,
"entityTypeDisplayName": "@sys.geo-city",
"isList": false
}
],
"outputContexts": [],
"resetContexts": false,
"rootFollowupIntentName": "",
"parentFollowupIntentName": "",
"followupIntentInfo": []
}

Step 3: Implement webhook for fulfillment

A webhook is a server-side application that allows Dialogflow to communicate with an external service. In this step, we will create a Python script that will act as a webhook to handle the fulfillment of our chatbot.

Python code:

import json
import requests

def get_weather(parameters):
city = parameters.get('Destination')
response = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid=<API_KEY>')
data = response.json()
weather = data['weather'][0]['description']
return f"The weather in {city} is currently {weather}."

def book_ticket(parameters):
# code for booking ticket
return "Your ticket has been booked."

def webhook(request):
req = request.get_json(force=True)
action = req.get('queryResult').get('action')
parameters = req.get('queryResult').get('parameters')

if action == 'get_weather':
fulfillment_text = get_weather(parameters)
elif action == 'book_ticket':
fulfillment_text = book_ticket(parameters)
else:
fulfillment_text = "I'm sorry, I don't understand."

return {'fulfillmentText': fulfillment_text}

Step 4: Integrate webhook with Dialogflow

To integrate our webhook with Dialogflow, we need to create a fulfillment for our intent. In Dialogflow, go to the Fulfillment section and enable the Webhook option. Set the URL to the endpoint of your Python script.

Python code:

import dialogflow_v2 as dialogflow
from google.protobuf.json_format import MessageToJson

client = dialogflow.IntentsClient()
parent = client.common_agent_path('<PROJECT_ID>')

intent1 = dialogflow.types.Intent(
name='projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>',
webhook_state=dialogflow.types.Intent.WebhookState.WEBHOOK_STATE_ENABLED
)

response = client.update_intent(
intent=intent1,
update_mask=dialogflow.field_mask.FieldMask(
paths=['webhook_state']
),
)

print(MessageToJson(response))
{
"name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>",
"displayName": "<INTENT_NAME>",
"priority": 500000,
"webhookState": "WEBHOOK_STATE_ENABLED",
"isFallback": false,
"trainingPhrases": [
{
"name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>/trainingPhrases/1",
"parts": [
{
"text": "I want to book a ticket for ",
"entityType": "@sys.geo-city",
"alias": "",
"userDefined": false
}
]
}
],
"messages": [
{
"text": {
"text": [
"When do you want to travel?"
]
}
}
],
"parameters": [
{
"name": "Destination",
"displayName": "Destination",
"value": "",
"mandatory": true,
"entityTypeDisplayName": "@sys.geo-city",
"isList": false
}
],
"outputContexts": [],
"resetContexts": false,
"rootFollowupIntentName": "",
"parentFollowupIntentName": "",
"followupIntentInfo": []
}

Step 5: Test the chatbot

Our chatbot is now ready to be tested!

Here’s a detailed testing with specific dates, preferred timings, and budget, along with options before confirming the booking:

After testing the intent, we can see that Dialogflow has correctly recognized the user’s intent to book a ticket to New York.

User: I want to book a ticket for New York

The chatbot has responded with the prompt “When do you want to travel?” as defined in the “book_ticket” intent.

Chatbot: When do you want to travel?

The user responds with “next week”.

User: next week

The chatbot follows up with another prompt asking for specific dates.

Chatbot: Sure, can you give me specific dates for your travel?

The user responds with “May 1st to May 7th”.

User: May 1st to May 7th

The chatbot then prompts the user for their preferred timings.

Chatbot: Great, what time of day do you prefer to fly? Morning, afternoon, or evening?

The user responds with “afternoon”.

User: afternoon

The chatbot then prompts the user for their budget.

Chatbot: Okay, and what is your budget for the trip?

The user responds with “around $500”.

User: around $500

The chatbot searches for available flights that match the user’s preferred dates, timings, and budget. Once the flights are found, the chatbot lists the available options and asks the user to confirm their preferred option.

Chatbot: We found 3 available flights for your dates and budget. Here are the options:
1. Departure: May 1st at 1:00 PM, Arrival: May 2nd at 2:00 PM, $250
2. Departure: May 4th at 2:00 PM, Arrival: May 5th at 3:00 PM, $240
3. Departure: May 6th at 12:00 PM, Arrival: May 7th at 1:00 PM, $260
Please select your preferred option by typing 1, 2 or 3.

The user responds with “1” to confirm their preferred option.

User: 1

The chatbot confirms the booking details to the user.

Chatbot: Great, your booking is confirmed for flight 1, departing on May 1st at 1:00 PM and arriving on May 2nd at 2:00 PM. Your total cost is $250. Is there anything else you need help with?

Overall, the chatbot has successfully fulfilled the user’s request to book a ticket to New York and provided a more personalized booking experience by asking for specific dates, preferred timings, and budget. The chatbot was able to find available flights that match the user’s criteria and presented them to the user for confirmation before finalizing the booking.

Conclusion

In this tutorial, we have built a simple ticket booking chatbot using Dialogflow and Python. We have covered the basics of creating intents, entities, and webhooks, and we have integrated our chatbot with an external service to handle the fulfillment. With this foundation, you can expand the functionality of your chatbot to include more advanced features and integrations.

--

--

Hands on AI
Hands on AI

Written by Hands on AI

Tutorials and case studies on various aspects of machine learning and artificial intelligence.

No responses yet