Google Dialogflow is Google’s platform for natural language understanding. With the help of this platform, it is easy to create a chat bot capable of answering many questions and working within all sorts of scenarios. For example, answering questions asked in an online store or managing a smart home by receiving commands in natural language.
Through the Dialogflow control console, you can integrate your project into various instant messengers such as Skype, Twitter, Facebook, Telegram and others directly from the control panel. I will show you another way to integrate the dialog flow agent into your telegram bot. To do this, we modify our echo bot.
So:
pip install google-cloud-dialogflow
Go to https://dialogflow.cloud.google.com/. Create a new agent.
Then you need to get the key in the form of a json file. To do this, follow the instructions https://cloud.google.com/dialogflow/es/docs/quick/setup.
Now we have a new agent in DialogFlow and we have a key to it. Bot code below under the spoiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import settings from telegram.ext import * from telegram import * from google.cloud import dialogflow from google.api_core.exceptions import InvalidArgument import os DIALOGFLOW_PROJECT_ID = 'your dialogflow project id' DIALOGFLOW_LANGUAGE_CODE = 'en' SESSION_ID = 'current-user-id' os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.getcwd()+"/your json key.json" def start(update, context): update.message.reply_text("Hi! I am a bot with Google Dialogflow") def echo(update, context): text_to_be_analyzed = update.message.text session_client = dialogflow.SessionsClient() session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID) text_input = dialogflow.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE) query_input = dialogflow.QueryInput(text=text_input) try: try: response = session_client.detect_intent(session=session, query_input=query_input) except InvalidArgument: update.message.reply_text('Something went wrong') return update.message.reply_text (response.query_result.fulfillment_text) except Exception as err: update.message.reply_text(err) def main(): updater = Updater(settings.TELEGRAM_API_KEY, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.text, echo)) # Start the Bot updater.start_polling() updater.idle() if __name__ == '__main__': main() |
It is good to set the Dialogflow on the “first line of defense” of your chat bot to answer general questions such as “What is your name?”, “Who can you do?”, “Who created you?” etc. Also, Dialogflow does a good job of detecting user intentions and finding named entities in a request. In the nearest future I will tell you how it can be used.
126