Skip to content

rking32/ai_python_bot

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 

Repository files navigation

ai_python_bot

Telegram Bot with Artificial intelligence

(30 lines of Python)


So, to create a telegram chat-bot with AI all we need is:

  1. Telegram API. As a wrapper, I took a proven library of python-telegram-bot
  2. API AI. I chose a product from Google, specifically Dialogflow. It provides a fairly good free API. The Dialogflow wrapper for Python

Step 1. Let's create a bot in Telegram

We choose a name and send it to @botfather. After the creation of the bot, we will get the API Token, save it somewhere, since in the future we will need it.

Step 2. Let's write the basics of our bot

Create a folder named "Bot", in which then create the bot.py file. Here will be 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 the installation, we can already write the "basics", which for now will simply respond with the same type of messages. Let's import the necessary modules and register our API token:

# Settings
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
updater = Updater(token='YOURE API TOKEN') # Telegram API Token
dispatcher = updater.dispatcher

Next, we write 2 command handlers. These are callback functions that will be called when the update is received. Let's write two such functions for the / start command and for any plain text message. Two parameters are passed there as arguments: bot and update. Bot contains the necessary methods for interacting with the API, and update contains information about the incoming message.

# Command processing
def startCommand(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text='Hello, do you want to talk?')
def textMessage(bot, update):
    response = 'Got youre message: ' + update.message.text
    bot.send_message(chat_id=update.message.chat_id, text=response)

Now all we need is to assign these handlers to notifications and start searching for updates. This is done very simply:

# Handlers
start_command_handler = CommandHandler('start', startCommand)
text_message_handler = MessageHandler(Filters.text, textMessage)
# Here we add the handlers to the dispatcher
dispatcher.add_handler(start_command_handler)
dispatcher.add_handler(text_message_handler)
# Start search for updates
updater.start_polling(clean=True)
# Stop the bot, if Ctrl + C were pressed
updater.idle()

Now we can test the performance of our new bot. Let's paste our API token on line 2, then save the changes, move it to the console and run the bot:

python bot.py

After the start send him a message. If everything were done correctly you will see this:

The basiscs for the bot are written, let's proceed to the next step!
P.s. do not forget to turn off the bot. To do that go back to the console and press Ctrl + C, wait a couple of seconds and the bot will successfully complete the work.

Step 3 AI Settings

First of all, sing up on Dialogflow (just log in with your Google account). Immediately after the authorization, we get to the control panel.

Click on Create Agent and fill in the fields with you're with whatever you want (this will not play any role, it is only necessary for the next action).
After that click on Create.

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

Click on Import. Then, without changing anything click on Ok. The agent was imported and now we can configure it. To do this, in the upper left corner click on the gear near the Small-Talk and get to the settings page. Now we can change the agent's name as desired (I leave it as it was). We change the time zone and in the Languages tab we make sure that the English language has been set.

Now we go back in General and copy the Client acess token

Now that our AI is completly ready we can go back to the bot

Step 4. Let's put it all together

AI is ready, bot basics are ready, what's next?


Next, we need to download the API wrapper from Dialogflow for python.

pip install apiai

Perfect. Now let's go back to our bot.


Let's add to our "Settings" section the import of apiai and json modules (you need to disassemble the responses from dialogflow in the future). Now it looks like this:

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

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

def textMessage(bot, update):
    request = apiai.ApiAI('YOURE API TOKEN').text_request() # Dialogflow API Token
    request.lang = 'en' 
    request.session_id = 'YoureBot' # ID dialog session (for bot training)
    request.query = update.message.text # Send request to AI with the user message

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

def textMessage(bot, update):
    request = apiai.ApiAI('YOURE API TOKEN').text_request() # Dialogflow API Toke
    request.lang = 'en' 
    request.session_id = 'BatlabAIBot' # ID dialog session (for bot training)
    request.query = update.message.text # Send request to AI with the user message
    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
    response = responseJson['result']['fulfillment']['speech'] # Take JSON answer
    if response:
        bot.send_message(chat_id=update.message.chat_id, text=response)
    else:
        bot.send_message(chat_id=update.message.chat_id, text='I dont understand!')

Some explanations:

request.getresponse().read()

get the response from the server, encoded in bytes. To decode it, we simply apply the method:

decode('utf-8')

And after that we "wrap" everything in:

json.loads()

Now all you need is ti save everything and check the bot

Step 5.

It took us 10 minutes to create our first AI bot. Of course it still need some massive training. You can do it in the section Training on Dialogflow.

Now if you want to host youre bot you can use the Where to host Telegram Bots guide.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 100.0%