Add conversation function to slack bot (made by python) using Recruit's Talk API

What to do in this article

Add conversational capabilities to your slack bot. bot is made with python3 series If you make a bot normally, you just return a fixed word for a fixed word, but that's kind of dull. Make it possible to talk as follows every time you make a cute

スクリーンショット 2017-08-09 23.05.54.png

How to make a bot

Please refer to the following for how to issue API and register to slack. Create a Slack bot with Python's slackbot library

If you proceed with the procedure after pip install slackbot, files will be created with the following directory structure.

slackbot         #A directory that organizes programs. Any name is fine
├─ run.py        #Start the bot by running this program
├─ slackbot_settings.py   #File to write settings related to bot
└─ plugins                #Add bot functionality to this directory
   ├─ __init__.py         #A file to indicate the module. Sky is fine
   └─ my_mention.py       #A file that adds each function of the bot. Edit this file this time

First, delete the DEFAULT_REPLY part of the file slackbot_settings.py.

[root@localhost slackbot]# more slackbot_settings.py
# coding: utf-8

#Specify token for bot account
API_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

#Response string when a message addressed to this bot does not apply to any response
#List of subdirectory names where plugin scripts are located
PLUGINS = ['plugins']

#Delete this!
DEFAULT_REPLY = "I don't know what you're talking about"

Next, edit my_mention.py

I think the initial state is as follows. I will modify this

# coding: utf-8

from slackbot.bot import respond_to     # @botname:Decoder that reacts with
from slackbot.bot import listen_to      #Decoder that responds to in-channel remarks
from slackbot.bot import default_reply  #Decoder that reacts when there is no corresponding response

# @respond_to('string')Message to bot
#string can be a regular expression "r'string'」
# @listen_to('string')Posts other than to bots in the channel
#                           @botname:Note that it does not react
#React when mentioning to others
#Regular expression possible
# @default_reply()          DEFAULT_Same function as REPLY
#If you specify a regular expression, it will not hit other decoders,
#Reacts when matching a regular expression
#... But is it an error if I specify a regular expression?

# message.reply('string')   @Speaker name:Send message with string
# message.send('string')Send string
# message.react('icon_emoji')Reaction to the speaker's message(stamp)To do
#In the string':'I don't need
@respond_to('Mention')
def mention_func(message):
    message.reply('What do you do when you say mention to me') #Mention

@listen_to('Listen')
def listen_func(message):
    message.send('Someone seems to have posted with listen')      #Just a post
    message.reply('You?')                           #Mention

Implementation of conversation function

For implementation, we will utilize the Talk API provided by Recruit. I compared it by looking at the following, but it seems that the accuracy of the returned message is high because it is free. Summary of conversation APIs, libraries, and services that can be used with BOT

Talk API

■Talk API The Talk API is an API for creating Chatbots. It provides a daily conversation response function by generating a response sentence from an input sentence using a Recurrent Neural Network (LSTM). Chatbot, which utilizes the Talk API, can automate user interactions on various applications and respond instantly to user inquiries at any time.

Register as a member and get an API Key. After registration, try hitting api with curl as below and you should get a reply

root@localhost slackbot]# curl -X POST https://api.a3rt.recruit-tech.co.jp/talk/v1/smalltalk -F "apikey=XXXXXXXXXXXXXXXXXXXX" -F "query=Good morning"

{"status": 0, "message": "ok", "results": [{"perplexity": 0.07743213382788067, "reply": "\u304a\u306f\u3088\u3046\u3054\u3056\u3044\u307e\u3059"}]}

It's very easy to implement. It seems that python provides a library called pya3rt, so let's use it Get ** pip install pya3rt **.

The code itself just adds the following part to my_mention.py

import pya3rt
@default_reply()
def send_message(message):
    apikey = "XXXXXXXXXXXXXXXXXXXXXXX"
    client = pya3rt.TalkClient(apikey)
    reply_message = client.talk(message.body['text'])
#Since json is returned in the following format, take out the reply part
# {'status': 0, 'message': 'ok', 'results': [{'perplexity': 1.2802554542585969, 'reply': 'I'm not sure'}]}
    message.reply(reply_message['results'][0]['reply'] + "Pome" )

@default_reply () is a collator that is called when you skip a mention to the bot and it doesn't match any word in my_mention.py. Go to Post to the Talk API provided by Recruit with pya3rt.TalkClient (apikey). You can get the following contents with json by default.

# {'status': 0, 'message': 'ok', 'results': [{'perplexity': 1.2802554542585969, 'reply': 'I'm not sure'}]}

Since the only part required above is the value of reply, it feels like taking it out with ['results'] [0] ['reply'] and storing it in the reply message of the bot.

If you do it with curl, you can also implement it as follows using the subprocess method. However, the result of check_output is not returned by json, so it is necessary to get reply with split or something.

import subprocess
@default_reply()
def send_message(message):
    curl_cmd = 'curl -X POST https://api.a3rt.recruit-tech.co.jp/talk/v1/smalltalk -F "apikey=XXXXXXXXXXXXXXXXXXXXXX" -F "query=message.body['text']"'
    message = subprocess.check_output(curl_cmd, shell=True)

After implementation, if you start slack bot with python run.py, I think that the bot can talk like the beginning

Recommended Posts

Add conversation function to slack bot (made by python) using Recruit's Talk API
Add a function to tell the weather of today to slack bot (made by python)
[Python] Conversation using OpenJTalk and Talk API (up to voice output)
Ask the bot to tell you the weather (precipitation information) using the weather information API (YOLP) provided by Yahoo ~ slack bot development with python ④ ~
Simple Slack API client made with Python
Log in to Slack using requests in Python
Function to save images by date [python3]
Develop slack bot in python using chat.postMessage
Try to make BOT by linking spreadsheet and Slack with python 2/2 (python + gspread + slackbot)
Try to make BOT by linking spreadsheet and Slack with python 1/2 (python + gspread + slackbot)
Procedure to use TeamGant's WEB API (using python)
[Python] Mention to multiple people with Slack API
Push notifications from Python to Android using Google's API
[Question] About API conversion of chat bot using Python
[Python] Using Line API [1st Creation of Beauty Bot]
Speech file recognition by Google Speech API v2 using Python
How to operate Discord API with Python (bot registration)
Create a Mastodon bot with a function to automatically reply with Python
Add a function to heat transfer + heat input by temperature to heatrapy
To return char * in a callback function using ctypes in Python
Tweet Now Playing to Twitter using the Spotify API. [Python]
Output product information to csv using Rakuten product search API [Python]
I made a Chatbot using LINE Messaging API and Python