📜 ⬆️ ⬇️

Learned Telegram chat bot with AI in 30 lines of Python code

image

Today, the thought came to my mind: “Why not write a Telegram chat bot with AI, which you can then train?”


Now it is quite easy to do this, so without thinking twice, I began to write code.
Language I chose Python, because it is easiest to work with such applications.

So, to create a Telegram chat bot with AI, we need:
')
1. API Telegram. As a wrapper, I took the proven library python-telegram-bot

2. API AI. I chose a product from Google, namely Dialogflow . It provides a pretty good free API. Dialogflow wrapper for Python

Step 1. Create a bot in Telegram


We come up with the name of our bot and write @botfather . After creating the bot, we will receive an API token, which we would like to save somewhere, because in the future we need it.

image

Step 2. We write the basis of the bot


Create a Bot folder, in which we create a bot.py file. Here is the code of our bot.
Open the console and go to the directory with the file, install python-telegram-bot .

pip install python-telegram-bot --upgrade 

After installation, we can already write a “framework”, which for now will simply respond with messages of the same type. We import the necessary modules and prescribe our API token:

Code settings and import
 #  from telegram.ext import Updater, CommandHandler, MessageHandler, Filters updater = Updater(token=' API ') #  API  Telegram dispatcher = updater.dispatcher 


Next, write 2 command handlers. These are callback functions that will be called when an update is received. We will write two such functions for the / start command and for a normal text message. Two parameters are passed as arguments: bot and update . The bot contains the necessary methods for interacting with the API, and the update contains information about the incoming message.

Callback code
 #   def startCommand(bot, update): bot.send_message(chat_id=update.message.chat_id, text=',  ?') def textMessage(bot, update): response = '  : ' + update.message.text bot.send_message(chat_id=update.message.chat_id, text=response) 


All that remains is to assign these handlers to the notifications and start searching for updates.
This is done very simply:

Handler Code
 #  start_command_handler = CommandHandler('start', startCommand) text_message_handler = MessageHandler(Filters.text, textMessage) #     dispatcher.add_handler(start_command_handler) dispatcher.add_handler(text_message_handler) #    updater.start_polling(clean=True) #  ,    Ctrl + C updater.idle() 


So, the full basis of the script looks like this:

Full bot code
 #  from telegram.ext import Updater, CommandHandler, MessageHandler, Filters updater = Updater(token=' API ') #  API  Telegram dispatcher = updater.dispatcher #   def startCommand(bot, update): bot.send_message(chat_id=update.message.chat_id, text=',  ?') def textMessage(bot, update): response = '  : ' + update.message.text bot.send_message(chat_id=update.message.chat_id, text=response) #  start_command_handler = CommandHandler('start', startCommand) text_message_handler = MessageHandler(Filters.text, textMessage) #     dispatcher.add_handler(start_command_handler) dispatcher.add_handler(text_message_handler) #    updater.start_polling(clean=True) #  ,    Ctrl + C updater.idle() 


Now we can check the performance of our new bot. We paste our API token on line 2, save the changes, transfer to the console and launch the bot:

 python bot.py 

After launch, write to him. If everything is set up correctly, you will see this:

image

The basis of the bot is written, proceed to the next step!
Ps do not forget to turn off the bot, to do this, go back to the console and press Ctrl + C, wait a couple of seconds and the bot will finish successfully.

Step 3. Configuring AI


First of all, go and register on Dialogflow (just log in using your Google account). Immediately after authorization, we get to the control panel.

image

Click on the Create agent button and fill in the fields at your discretion (this will not play any role, this is only necessary for the next step).

image

Click on Create and see the following picture:

image

I will tell why the “Agent” created by us earlier does not play any role. In the Intents tab there are “commands” for which the bot works. Now he can only respond to phrases like "Hello", and if he does not understand, he answers "I did not understand you." Not very impressive.
After creating our empty agent, we got a bunch of other tabs. We need to click on Prebuilt Agents (these are already specially trained agents that have many teams) and select Small Talk from the entire list provided.

image

Direct it and click Import . Next, without changing anything, click Ok . The agent has been imported and now we can configure it. To do this, in the upper left corner click on the gear near Small-Talk and get to the settings page. Now we can change the name of the agent as we want (I leave it as it was). Change the time zone and in the Languages tab, check that the Russian language is installed (if not set, then set).

image
image

Go back to the General tab, go down a bit and copy Client access token

image

Now our AI is fully configured, you can return to the bot.

Step 4. Putting it all together


AI is ready, bot base is ready, what next? Next we need to download the API wrapper from Dialogflow for python.

 pip install apiai 

Installed? We return to our bot. Add to our section "Settings" import modules apiai and json (it is necessary in the future to disassemble json answers from dialogflow). Now it looks like this:

Updated Settings Code
 #  from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import apiai, json updater = Updater(token=' API ') #  API  Telegram dispatcher = updater.dispatcher 


Go to the textMessage function (which is responsible for receiving any text message) and send the received messages to the Dialogflow server:

Code sending messages to Dialogflow
 def textMessage(bot, update): request = apiai.ApiAI(' API ').text_request() #  API  Dialogflow request.lang = 'ru' #       request.session_id = 'BatlabAIBot' # ID   (,    ) request.query = update.message.text #         


This code will send a request to Dialogflow, but we also need to extract the response. Add a couple of lines, total textMessage looks like this:

The complete code of the textMessage function
 def textMessage(bot, update): request = apiai.ApiAI(' API ').text_request() #  API  Dialogflow request.lang = 'ru' #       request.session_id = 'BatlabAIBot' # ID   (,    ) request.query = update.message.text #         responseJson = json.loads(request.getresponse().read().decode('utf-8')) response = responseJson['result']['fulfillment']['speech'] #  JSON    #      -  ,   -     if response: bot.send_message(chat_id=update.message.chat_id, text=response) else: bot.send_message(chat_id=update.message.chat_id, text='    !') 


A little bit of explanation. Via

 request.getresponse().read() 

the response from the server is encoded in bytes. To decode it, just use the method

 decode('utf-8') 

and after that "we wrap" everything in

 json.loads() 

to parse json answer.

If there is no answer (more precisely, json always arrives, but there is not always the array itself with the answer of the AI), then this means that Small-Talk did not understand the user (it will be possible to study later). Therefore, if there is no “answer”, then we write to the user “I didn’t quite understand you!”.
Total, the full code of the bot with the AI ​​will look like this:

The full code of the bot with AI
 #  from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import apiai, json updater = Updater(token=' API ') #  API  Telegram dispatcher = updater.dispatcher #   def startCommand(bot, update): bot.send_message(chat_id=update.message.chat_id, text=',  ?') def textMessage(bot, update): request = apiai.ApiAI(' API ').text_request() #  API  Dialogflow request.lang = 'ru' #       request.session_id = 'BatlabAIBot' # ID   (,    ) request.query = update.message.text #         responseJson = json.loads(request.getresponse().read().decode('utf-8')) response = responseJson['result']['fulfillment']['speech'] #  JSON    #      -  ,   -     if response: bot.send_message(chat_id=update.message.chat_id, text=response) else: bot.send_message(chat_id=update.message.chat_id, text='    !') #  start_command_handler = CommandHandler('start', startCommand) text_message_handler = MessageHandler(Filters.text, textMessage) #     dispatcher.add_handler(start_command_handler) dispatcher.add_handler(text_message_handler) #    updater.start_polling(clean=True) #  ,    Ctrl + C updater.idle() 


Save the changes, run the bot and go check:

image

That's all! The bot in 30 lines with AI is written!

Step 5. Final part


I think you made sure that writing a bot with an AI is a matter of 10 minutes. It remains only now to teach and teach him. By the way, this can be done in the Training tab. There you can see all the messages that were written and that the bot responded to them (or did not respond). You can also train him there, telling the bot where he answered correctly and where not.

image

I hope the article was useful to you, good luck in learning!

Source: https://habr.com/ru/post/346606/


All Articles