I tried to make an air lip detection & automatic response BOT for remote work

Due to the influence of Corona, remote work has come to me, who is the next contractor for many years. You can work in a quiet environment at home. I don't have to take a commuter train, and I know that I've been doing a lot of waste.

By the way, the problem I have with such remote work is "chat". I have quite a lot of channels such as my company and customer department, There, the air lip event of "my name comes out without mention" often occurs. As the number of remote work personnel increases, the flow rate of chat also increases, and it is difficult to pick it up.

This itself is "make mentions properly if there is a need" "set keyword notification" It is a story that should be managed with the operation side cover, but this time it is a big deal ** Let's implement "Analyze the contents of the air lip and separate the BOT response depending on the contents" **.

The image looks like this. bot_flow.png

Creating a chat bot

It doesn't matter what you use. With Python, there should be something for any chat platform, Qiita also has a lot of good articles.

I thought about using it in my company Slack, but before that, I want to check the operation properly, so This time, I'm going to use Telegram, which has a lot of acquaintances on my internet.

Also, if the COTOHA used this time is only a function for developers, as per the terms of use, https://www.ntt.com/content/dam/nttcom/hq/jp/about-us/disclosure/tariff/pdf/c256.pdf Please be careful when using it as it will cause a license problem if you use it for business purposes.

I will use this BOT that I made before. https://qiita.com/Ovismeme/items/cc59a2de1cf537c977cf https://github.com/ovismeme/telegram_autoreply_bot

At the time of making this, I wrote it by imitating the sample code in "I don't understand Python". When I looked back for the first time in a year, I said, "What's this garbage. Who wrote it!", So I fixed it a lot. The readability has improved a little, but the main part of this article is not there, so I will omit it.

Please refer to the original article for how to make it, As a requirement of BOT, anything is fine as long as it has the functions of "picking up what was spoken" and "speaking". A module should also be provided, but the mechanism for picking up utterances differs depending on the item, so be sure to read the document carefully.

Use COTOHA API

account registration

To determine "whether the text is negative or positive" We will use COTOHA provided by NTT Communications Co., Ltd. for developers.

COTOHA API

Explain how to register very easily
![c99dba0e850d24459e47cb2889b10af6.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211046/ee0f6b61-a23d-1a6e-c9a9-73126c277b37.png) Click here to enter your e-mail address and follow the link in the returned e-mail to complete the registration.

86f90895a0c958336f53ca6a7e57dbd2.png

After registration, you will be able to see the account portal, where your Client ID and Client Secret will be issued.

API call

How to get an access token Emotion Analysis API The method is written here.

Just hitting the API is just hitting it, but I'll paste the code that is actually running. Access information and URLs are included in the config, so when you use it yourself, Please move it by hard code or calling config.

API call

cotoha.py


import requests
import configparser
import pprint

class CotohaController:
    def __init__(self):
        config_file = './settings/config.ini'
        self.config = configparser.ConfigParser()
        self.config.read(config_file, 'utf-8')
        self.base_url = str(self.config.get('cotoha_auth', 'base_url'))
        self.headers = {
            'Content-Type' : 'application/json;charset=UTF-8'
        }
        self.get_accesstoken()

    def get_accesstoken(self):
        request_body = {
            "grantType": "client_credentials",
            "clientId": str(self.config.get('cotoha_auth', 'client_id')),
            "clientSecret": str(self.config.get('cotoha_auth', 'client_secret'))
        }
        auth_url = str(self.config.get('cotoha_auth', 'auth_url'))
        responce = requests.post(auth_url, headers=self.headers, json=request_body)
        self.headers.update(Authorization = 'Bearer ' + responce.json()['access_token'])

    def emotion_analysis(self, text):
        request_body = {
            "sentence": str(text)
        }
        url = self.base_url + '/nlp/v1/sentiment'
        responce = requests.post(url, headers=self.headers, json=request_body)
        return responce.json()['result']['sentiment']


if __name__ == '__main__':
    cotoha = CotohaController()
    print(cotoha.emotion_analysis('I'll do my best today as well!'))

If you pass the text to ʻemotion_analysis (), the API will analyze your emotions and return Positive`` Negative Neutral`.

PS D:\src\telegram_autoreply_bot> python .\cotoha.py
Positive

The sample code looks like this.

BOT side setting

try:
    cth = cotoha.CotohaController()
    emote = cth.emotion_analysis(rcv_text)
    reply_list = self.replyLists['cotoha'][emote]
    return_text = reply_list[random.randrange(len(reply_list))]
except Exception:
    return_text = "・ ・ ・"

When there is a trigger utterance, hit the API call module created earlier and return a response randomly from the definition file according to the sentiment analysis of the API.


 [
   "regex:.*Memetan.*",
   "regex:.*(sheep|sheep|Sheep).*"
 ]

In my implementation, it fires when it matches this regex.

For reference, the definition part of the response looks like this.

definition json
  "cotoha" : {
    "Positive" : [
      "Compliment more! !!",
      "That's it! That's it! !!",
      "It stretches when you praise it (under your nose)"
    ],
    "Negative" : [
      "I can hear you!",
      "What are you waiting for! !!",
      "What a sneak! !!",
      "No bad talk! !!"
    ],
    "Neutral" : [
      "No air lip! !!",
      "called? You called it! ?? You called it! ??",
      "Please tell us the requirements and pay 10,000 yen when you use it.",
      "Did you say anything?"
    ]
  }

By the way, not the implementation of "responding" There are many evil implementations like ** "Sneak a ticking mention to yourself when a negative word comes in" **. I am refraining from doing various things this time, but please let me know if you have any interesting implementations.

motion

29cf765e043a4d68331e75ebd750ea64.png

It has been well received and is above all.

Be careful and talk about Yomoyama

About call triggers

https://api.ce-cotoha.com/contents/reference/apireference.html#parsing It's a cooler implementation to do this morphological analysis and pick up your name from the morphemes.

However, Japanese natural language processing is vulnerable to proper nouns. In particular, you can't pick up names that you don't understand the meaning of hiragana, and it may cause some malfunctions. I think that COTOHA API or NTT products are more accurate, but Still, it's difficult to pick up exactly something like a nickname. My screen name "Memetan" may also be decomposed like "Memetan" depending on the context. Therefore, there is no mistake in the form of firing with a regular expression without using morphological analysis for the trigger.

About sentiment analysis

I'm sorry to have read this far, but it may be difficult to say. To be honest, do you say that there are few variations of bad words, or are they made without assuming bad words? I'm not sure if "bad talk" and "Negative" are different, but Currently, the "Negative" flag is not very high. I was hurting my heart and writing bad words about myself, but I was a little disappointed. afc12487ec568fb355eec13a260ce6bb.png

I have high expectations for that area in the future. As a cover on the operation side, my BOT side implements that even "Neutral" returns a similar answer. For those who want to make a ticking BOT, it may be better to make it work other than "Positive".

You can't use it for commercial purposes! What is it for remote work!

You can use it for 130,000 yen a month including voice input! !! It's cheap! !! (I'm not saying to pay) Of course, I don't think it's possible to include this function alone, but if you propose it as a set with other functions, the company may pass it. Please use at your own risk.

At the end

I used a ready-made chat bot, but since I prepared the API call only this morning, Perhaps everyone who sees Qiita will be able to use it without much effort. Natural language processing has a lot of silly uses, and it's a lot of fun to make for fun, so please show us your ideas.

Thank you for visiting.

Recommended Posts

I tried to make an air lip detection & automatic response BOT for remote work
I tried to make AI for Smash Bros.
I tried my best to make an optimization function, but it didn't work.
I tried to make an OCR application with PySimpleGUI
I tried to make an automatic character dialogue generator by N floor Markov chain
I tried to create a bot for PES event notification
I tried to make an activity that collectively sets location information
I tried to make an image classification BOT by combining TensorFlow Lite and LINE Messaging API
I tried to make an analysis base of 5 patterns in 3 years
[Python] Simple Japanese ⇒ I tried to make an English translation tool
I tried to make a strange quote for Jojo with LSTM
I tried to make an image similarity function with Python + OpenCV
I tried to make a face diagnosis AI for a female professional golfer ①
I tried to make an open / close sensor (Twitter cooperation) with TWE-Lite-2525A
I tried to make a face diagnosis AI for a female professional golfer ②
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I want to make an automation program!
I tried to make a Web API
I tried to make a translation BOT that works on Discord using googletrans
I tried to automate the face hiding work of the coordination image for wear
An introduction to machine learning for bot developers
I tried to get an image by scraping
I tried to detect an object with M2Det!
I tried to operate Linux with Discord Bot
I tried to make a ○ ✕ game using TensorFlow
A Python beginner made a chat bot, so I tried to summarize how to make it.
I tried to build an environment for machine learning with Python (Mac OS X)
I tried to make a "fucking big literary converter"
I wrote an automatic kitting script for OpenBlocks IoT
Continuation ・ I tried to make Slackbot after studying Python3
I tried to implement an artificial perceptron with python
I tried to get an AMI using AWS Lambda
I tried to become an Ann Man using OpenCV
I wrote an automatic installation script for Arch Linux
I tried to find an alternating series with tensorflow
I tried to implement automatic proof of sequence calculation
[Python] I tried to make an application that calculates salary according to working hours with tkinter
[For those who want to use TPU] I tried using the Tensorflow Object Detection API 2
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
I tried to make a bot that randomly acquires Wikipedia articles and tweets once a day