Building a Currency Converter Chatbot using Dialogflow and Python: A Step-by-Step Guide with Telegram Deployment

Yogeshwar Purushottam Kaulwar
18 min readMay 9, 2023

--

Introduction

Hello everyone. I hope everything is well with you. In this lesson, we will learn how to build chatbots with Dialogflow and Python, as well as how to deploy chatbots to Telegram. In earlier articles, we learned how to build a simple rule-based chatbot with Python and the NLTK libraries. To gain a fundamental understanding and application of chatbots, I would recommend reading the article Creating a Simple Chatbot Using Python.

Source: Internet

Table of Contents

  • What is a chatbot?
  • Brief on Dialogflow
  • Implementing the Currency Converter Chatbot
  • Agent
  • Intent
  • Small Talk
  • Creating Flask APP
  • Testing with Ngrok
  • currency converter API
  • Deployment on Telegram
  • End Notes

What is a chatbot?

A chatbot is a natural language understanding program that is commonly utilized by both product- and service-based businesses to reduce human labour and respond as quickly as possible to preserve client satisfaction. Chatbots are even employed for marketing purposes, such as recommending products and increasing site traffic.

Chatbots have many applications in today’s world, and most businesses are transforming and increasing productivity by utilizing chatbots designed with cutting-edge technologies. We already learned about applications and chatbot types in the previous article.

Brief on Dialogflow

Google’s Dialogflow platform is used to develop chatbots. It is a major chatbot implementation platform that uses natural language understanding to create an interactive conversational interface for websites and Android, and the concept is also referred to as "conversational AI."

Features of Dialogflow

  • Develop serverless apps.
  • Design a voice-first world.
  • understand user sentiments
  • reply to an automatic spelling correction.

Many other businesses, such as AS Flower, Facebook wit.ai, IBM Watson, and others, provide platforms for creating chatbots, so why do we select Google Dialogflow to get started?

Because Dialogflow is user-friendly and backed by Google Cloud machine learning technology, most people chose it to begin learning and implementing chatbots. Aside from that, Dialogflow provides easy multi-channel integration of chatbots, as well as a free edition to work with it and work on the concept of NLP technology.

Currency Converter Chatbot Implementation in Practice

We now have a basic understanding of chatbots and the foundation for their execution. Let’s get our hands dirty and build a basic end-to-end currency converter bot.

Create a Dialogflow account.

Visit the Dialogflow cloud website in your browser and establish an account with an email address.

Agents

The fundamental application of a chatbot is the agent, and the name of the agent characterizes your chatbot. Its responsibility is to manage end-user dialogues. All of our conversations are with agents alone. There are several terminologies used to convey distinct commands to the agent.

The chatbot agent is the same as a human call center representative. Both are taught in specific settings and do not breach their instructions under any circumstances; this is a chatbot’s specialty.

When you sign in to Dialogflow, you will notice the agent option on the left panel at the top. Click it, and then click Create New Agent. Name your preferred agent.

Source: Dialogflow.com

Intents

The intent is a user expression created for use in a dialogue with an agent. In layman’s terms, the intent is an expression expressed by the end-user, and the chatbot matches the phrase with his training data to discover the appropriate response for the user.

So, in addition to the purpose, we must train the chatbot on answer generation. There may be numerous types of responses for a specific intent, or the intent may be expressed differently and have only one response.

The intent option is located underneath the agent section. When you click on it, two default intents are established for your chatbot. One is a welcome intent, and the other is a fallback intent. You can change their response if you wish. For the time being, click on "Create New Intent" and name it "Help." Now, various users can query for aid in different ways, so try to add a few with diverse tastes. As indicated here, the intent will be specified throughout the training phase.

Source: Dialogflow.com

After you’ve created your intent, scroll down to locate a response option. Because this is a chatbot response for a certain purpose, define some responses that you want to provide.

Small Talk

Dialogflow supplies some groups with a set of questions that are commonly asked of a chatbot by users. We, as humans, strive to test every program before putting it to use, and whenever we engage with a chatbot, we try to ask it strange things. As a result, Dialogflow gives us questions on which we can train our chatbot to handle similar queries sent by users.

You can make small talk by scrolling down the left side. Simply click on it to see different groups, such as "About the Agent," "Emotions," and so on. And within this group are a series of questions. First, allow a small conversation, and then add an answer to any questions you want to include and save it. This is how the Dialogflow chatbot’s small talk works.

Create currency convertor intent

Return to the intent section and add another intent for the currency converter. Here, we’ll use the action and parameters sections to match the currency and unit to convert, as well as the currency name to convert in. During the training phase, it aims to incorporate statements such as “convert 500 dollars to rupees.” When you press enter, Dialogflow will automatically recognize the unit and current as units and the second as a currency name and add them to a parameter in the Action and Parameter section box.

Source: Dialogflow.com

If it matches it incorrectly, simply click on it to correct it. There are many default options in Dialogflow, but our main application aim is to convert currency from one unit to another. After adding some intent to the action and parameter sections, make both actions mandatory. If a user wishes to utilize our chatbot, he must specify the unit currency and the currency name in which to convert.

The prompt option is visible in actions and parameters. If a user does not supply any parameters, this prompt will appear. As a result, provide an appropriate message for the user to enter the currency value and name. If the chatbot fails to recognize the argument, provide a meaningful response from the chatbot side to the response area, such as "server down." "Please try again later.”

Connect Flask with the Dialogflow chatbot.

The flask will be used to communicate with Dialogflow. If you try to communicate with your chatbot using the try it now sections on the right side, you will see the diagnostic info option, which is a JSON file providing details about your conversation with a chatbot. This will be passed to the flask packet, which will convert it and provide the outcome to us.

Because Dialogflow is operating on a server and Flask is running on a local system, we’ll need to figure out how to connect with it. One option is to host the flask code, but we are currently in progress and need to double-check the code; therefore, we cannot launch it again and again. So one option is to use software such as ngrok, which gets your machine code online. It is tunnelling software that temporarily gets your machine code online so you can test your errors while building your project.

Build a Flask Template

If you are new to Python development, you should know that Flask is a Python microweb framework that is used to construct web apps or work on server-side scripting. Create a simple flask template that will serve as a packet for the chatbot and execute it from a terminal or any Python IDE.

from flask import Flask
app = Flask("__name__")
@app.route("/")
def index():
return "hello world"
if __name__ == "__main__":
app.run(debug=True)

Download ngrok

Visit the ngrok website and download ngrok according to your operating system. When you run the zip file, you will be prompted with a ngrok command prompt.

Enter the following command in the ngrok command prompt:

ngrok HTTP 5000

The default Flask operating port is 5000. Open a browser and paste the second URL that appears on the command prompt. You will notice that your Flask app is now connected and online.

Connect Dialogflow to the URL.

in your case, Dialogflow Enable webhooks by clicking on fulfillment in the left column. When you enable it, it will prompt you for a URL. Copy and paste the URL we acquired from ngrok and save the changes. This Dialogflow will send a POST request as a response to a user question.

The second step is to allow webhook calls in the currency converter intent we’ve constructed. Scroll down and enable webhook calls for the currency converter.

Convert one currency to another currency

The entire connection setup is finished. Now we must accept the Dialogflow POST response and gain access to data in the form of JSON. After converting, we must submit the result back to Dialogflow. We will use an online API (application programming interface) from the currency converter API to convert amounts from one currency to another.

Please go to this page and click on the "Get API Key" button. Enter and submit your email address. Check and confirm your email. You can then use your API key after it has been confirmed. Now that we have an API key, we can make requests through the website and get the appropriate results. Visit the site’s documentation and copy the URL to which we need to submit a request. We need to update the currency name in our Flask app so that we can format the URL dynamically.

#The complete code is here, and its explanation is given below the code.

from flask import Flask, request, jsonify
import requests
app = Flask("__name__")
def fetch_conversion_factor(source, target):
url = "https://free.currconv.com/api/v7/convert?q={}_{}&compact=ultra&apiKey=c6676f7365214fddb240".format(source, target)
response = requests.get(url)
response = response.json()
return response['{}_{}'.format(source,target)]
@app.route("/", methods=['POST'])
def index():
data = request.get_json()
#print(data)
source_currency = data['queryResult']['parameters']['unit-currency']['currency']
amount = data['queryResult']['parameters']['unit-currency']['amount']
target_currency = data['queryResult']['parameters']['currency-name']
#print(source_currency)
#print(amount)
#print(target_currency)
cf = fetch_conversion_factor(source_currency, target_currency)
final_amount = amount * cf
final_amount = round(final_amount,2)
response = {
'fulfillmentText':"{} {} is {} {}".format(amount,source_currency,final_amount,target_currency)
}
return jsonify(response)
if __name__ == "__main__":
app.run(debug=True)

EXPLANATION

We wrote a separate function to conduct URL queries with the source currency and target currency, and it returns a JSON object with the value of 1 unit of source currency to the target currency. We calculate the required amount and round it to two decimal places after converting one unit. The fulfilment text is a name that Dialogflow captures and prints as the default answer when it receives a POST request. As a result, write the same name as in the response. The response is then returned to Dialogflow in JSON format.

Try it now when you run the application or test your chatbot on the right pane. And pass on some intentions to see whether a response is forthcoming. If you try to convert some currency to another unit, you will get the default response.

Source: Dialogflow.com

Web Demo of the Currency Converter

Navigate to the integration section on the left panel of Dialogflow and select the web demo. It will provide you with a URL; click on it to access the web version of your chatbot.

Source: Dialogflow.com

Deployment of Chatbot to Telegram

Now I’ll teach you how to connect your Dialogflow chatbot to Telegram.

First, launch Telegram Web in the browser you’re using.

There is no need to search for bot father in Telegram and visit the first result that appears.

It will present you with several alternatives, the first of which is for my bot. Simply click or type "start" on that.

It will request your chatbot’s name and username. You must choose a distinct name that does not already exist on the platform.

Following that, your bot will be built, and you will be given one token to access the chatbot. Simply copy that token.

Enable Telegram in the Dialogflow integration area by clicking on it. It will request a token and copy the token you obtained from Telegram. And with that,

Have fun speaking with your chatbot on Telegram. And with that,

This article was published as a part of the Data Science Blogathon

Introduction

Hello all, Hope you are fine. In this tutorial we will learn how to create chatbots using Dialogflow and python, as well we will learn the deployment of chatbots to telegram. In our previous articles, we have learned to create a simple rule-based chatbot using simple python and NLTK libraries. I would like to request you to have a look at the article creating a simple chatbot using python to get a basic understanding and application of chatbots.

Table of Contents

  • What is Chatbots
  • Brief on Dialogflow
  • Implementing Currency Converter Chatbot
  • Agent
  • Intent
  • Small Talk
  • Creating Flask APP
  • testing with ngrok
  • currency converter API
  • Deployment on Telegram
  • End Notes

What is Chatbot?

A chatbot is a natural language understanding application that is widely used by product-based as well as service-based companies to reduce human work and response as soon as possible to maintain customer satisfaction. Chatbots are even used as a marking purpose to recommend products, and also to increase the traffic of a site.

Chatbots have much application in today’s era and most of the business is transforming and increasing productivity using chatbots built using the latest technologies. Applications, types of chatbots already we have learned in the previous article.

Brief on Dialogflow

Dialogflow is a platform introduced by Google used to implement chatbots. It is a leading chatbot implementation platform that works on a natural language understanding to create an interactive conversational interface for websites and android, and the term is also known as conversational AI.

Features of Dialogflow

  • Develop serverless Apps
  • Design Voice-first world
  • understand user sentiments
  • Reply to an automatic spelling correction

Many other companies also provide platforms to implement chatbots like AS lily, Facebook wit.ai, IBM Whatson, etc. then why do we prefer Google Dialogflow to get started?

Dialogflow is user-friendly and powered by Google Cloud machine learning technology hence most people preferred Dialogflow to start learning implementation of chatbots. Apart from this Dialogflow offers Multi-channel integration of chatbots in an easy way, Dialogflow offers a free edition to work with it and work on the concept of NLP technology.

If you want to read more on Dialogflow please refer to this Blogspot article.

Practical Implementation of Currency Convertor Chatbot

Now we have a theoretical understanding of chatbots and their implementation framework. let’s get our hands dirty with implementing a simple end-to-end currency convertor bot.

Create Dialogflow account

In your browser itself visit the Dialogflow cloud website and create an account using an email address.

Agents

An agent is the main application of a chatbot or the name of the agent defines your chatbot. its task is to manage end-user conversations. All the conversations we are doing are with agents only. There are different terms used through which agent gets different commands to perform.

The chatbot agent is the same as a human agent working in a call centre. Both are trained under certain scenarios, and they do not violate their training in any circumstances, that’s the speciality of chatbots.

As you are signed in to Dialogflow, in the left panel at the top you can see the option of the agent. Click on it and click create a new agent. Name your agent what you prefer.

Intents

The intent is an end-user expression made for a conversation with an agent. In simple words, the intent is an expression made by the end-user and the chatbot matches the expression in his training data and finds the relevant response for the user.

so, along with intent, we need to train the chatbot on responses to generate. for a particular intent, there can be multiple kinds of responses or intent can be written differently and can have a single response.

Below the agent section, you can see the intent option. Click on it, and as you click there is two default intent created for your chatbot. one is welcome and one is fallback intent. If you want you can modify their response. for now, click on create new intent and name it as help. Now for help different users can query in a different way, so try to include a few with different tastes. The intent is to be defined in the training phase as shown below.

After creating intent scroll down and you will find an option for a response. This is a chatbot response for a particular intent, so define some responses that you want to give.

Small Talk

Dialogflow provides some groups with a set of questions that are mostly asked by the users to a chatbot. We humans first try to test any application before in use and whenever we communicate with any chatbot, we try to ask some weird questions to it. so Dialogflow provides us that questions on which we can train our chatbot so that It is reliable to handle such queries fired by users.

When you scroll down the left panel, you have an option of small talk. just click on it and you can see some groups like About agent, emotions, etc. And this group contains a set of questions. first, enable the small talk, and whichever question you want to include just add an answer for that and save it. This is how the small talk for Dialogflow chatbot works.

Create currency convertor Intent

Again visit the Intent section and create new intent for the currency converter. here we will be using the action and parameters section to match the currency and unit to convert and the currency name in which to convert. In the training, phase tries adding some expressions like convert 500 dollars to rupees. as you press enter you will see Dialogflow automatically identify the unit and current as a unit and second as currency name and add to a parameter in the Action and parameter section box.

If in any intent it matches it wrong, correct it by just clicking on it. There are lots of parameters present at default in Dialogflow, But our main application goal is to convert currency from one unit to another. After adding some intent in action and parameter section make both the action as compulsory to give if any user wants to use our chatbot then he needs to provide unit currency and currency name in which to convert.

You can see the prompt option in action and parameter. If any user does not provide anyone parameter then this prompt will be displayed. so write an appropriate message for the user to provide the currency value and name. If the chatbot fails to identify the parameter then add relevant response from the chatbot side in the response section like server down, please try again later.

Connect Flask with Dialogflow chatbot

How we will communicate to Dialogflow through the flask. If you try to communicate to your chatbot using the try it now sections on the right side then you’ll observe the diagnostic info option which is a JSON file containing details of your talk with a chatbot. we will pass this to the flask packet which will convert the value and return the result to us.

How we will communicate Dialogflow with Flask code because Dialogflow is running on a server and flask is running on a local system. One method is to host the flask code but we are currently in a development stage, and we need to check the code again and again so we cannot deploy it again and again. So there is one solution to use software like ngrok which brings your machine code online. It is tunneling software that brings your machine code online for some time and you can test your errors online while developing your project.

Build Flask Template

If you are new to python development then understand that Flask is a micro web framework of python which is used to develop web applications or to work on server-side scripting. First, build a basic flask template that will work as a packet for the chatbot and run it using a terminal or any Python IDE.

from flask import Flask
app = Flask("__name__")
@app.route("/")
def index():
return "hello world"
if __name__ == "__main__":
app.run(debug=True)

Download ngrok

Visit the ngrok website and according to the operating system you are using download ngrok. Extract the zip file and run it and you will see a ngrok command prompt is prompted.

In ngrok command prompt write below command

ngrok HTTP 5000

Flask default running port is 5000. Copy the second URL it displays on the command prompt and open it in a browser. you will observe that your flask app is connected and it’s now online.

Connect Dialogflow to URL

In your, Dialogflow click on fulfillment in the left panel and enable webhook. As you enable it, it will ask for an URL. paste the same URL we got from ngrok and save the changes. Using this Dialogflow will make a POST request in a form of a response to a user query.

One second thing to do is enable webhook calls in the currency converter intent that we have created. Visit currency converter intent and scroll down and enable webhook calls.

Convert one currency to another currency

The complete connection setup is complete. Now we have to accept the response of the Dialogflow POST request and get access to data in form of JSON. And again after converting we need to send the result back to Dialogflow. For converting amounts from one currency to another currency we will take the help of online API(Application programming interface) from currency convertor API.

Please visit here and click on the get API key. enter your email address and submit it. Check your mail and verify it. After that you also got your API key verified and can use it. Now we have an API key so we can request through the website and can get desired results. Visit documentation of the site and copy the URL to which we have to make a request. In our flask app, we need to change the currency name so we will format the URL in a dynamic way.

The complete code is here, and its explanation is given below the code.

from flask import Flask, request, jsonify
import requests
app = Flask("__name__")
def fetch_conversion_factor(source, target):
url = "https://free.currconv.com/api/v7/convert?q={}_{}&compact=ultra&apiKey=c6676f7365214fddb240".format(source, target)
response = requests.get(url)
response = response.json()
return response['{}_{}'.format(source,target)]
@app.route("/", methods=['POST'])
def index():
data = request.get_json()
#print(data)
source_currency = data['queryResult']['parameters']['unit-currency']['currency']
amount = data['queryResult']['parameters']['unit-currency']['amount']
target_currency = data['queryResult']['parameters']['currency-name']
#print(source_currency)
#print(amount)
#print(target_currency)
cf = fetch_conversion_factor(source_currency, target_currency)
final_amount = amount * cf
final_amount = round(final_amount,2)
response = {
'fulfillmentText':"{} {} is {} {}".format(amount,source_currency,final_amount,target_currency)
}
return jsonify(response)
if __name__ == "__main__":
app.run(debug=True)

EXPLANATION ~

We have created a separate function to make requests to URL with source currency and target currency which in return the JSON object which contains the value of 1 unit of source currency to target currency. after getting one unit conversion we calculate the required amount and round it to 2 decimal places. fulfillment text is a name that is captured by Dialogflow and print as the default response when it made a POST request. so write the same name as written in response. After that, we return the response in JSON format to Dialogflow.

Now when you run the application or test your chatbot on the right panner try it now. And pass some intents and check whether a response is coming or not. Try converting some currency to another unit and you will see the default response.

Web Demo of Currency Converter

Visit the integration section from the left panel in Dialogflow, and click on the web demo. It will give you a link, visit it and enjoy the web version of your chatbot.

Deployment of Chatbot to telegram

Now I will show you how you can integrate your Dialogflow chatbot with a telegram.

  1. First open telegram web in a browser you are working in
  2. No search for bot father in telegram and visit at the top which comes.
  3. It will give you many options, and at first, the option is for my bot. just click on that and click or type start.
  4. It will ask the name and username of your chatbot. you have to pick a unique name that does not already exist on the platform.
  5. After that, your bot is created and It will give you one token to access the chatbot. just copy that token.
  6. In the Dialogflow integration section, click on telegram and enable it. It will ask for a token and paste the token you received from the telegram. And that done.

Enjoy chatting with your chatbot through telegram.

End Notes

Thank you for sticking with me this far. Using Python Flask, we built a complete end-to-end Dialogflow chatbot. There are more powerful chatbots that can contain various applications in addition to converting currency and performing multiple jobs. My goal was to introduce you to the Dialogflow platform and show you how to use it in chatbot apps. You can also publish your Flask software to any cloud service, such as AWS or Heroku.

If you have any questions or concerns, please leave them in the comments section below. I’d be delighted to assist you.

--

--

Yogeshwar Purushottam Kaulwar
Yogeshwar Purushottam Kaulwar

Written by Yogeshwar Purushottam Kaulwar

Navigating the Data-Driven World: A Python Developer & Enthusiastic Data Analyst Sharing Insights & Experiences.

No responses yet