Python + chatwork + google extension = How to make an easy and funny chat BOT

Premise

The following can be prepared

Script implementation

Create a server that returns 200 OK in Python

webhookchatwork.py


import http.server
import socketserver
import json
import requests
class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        self.send_response(200)
        self.end_headers()
        content_leng  = int(self.headers.get("content-length"))
        req_body = self.rfile.read(content_leng).decode("utf-8")
        json_object = json.loads(req_body)
        print(json_object)
#Set 3000 ports in your local environment
with socketserver.TCPServer(("", 3000), MyHandler) as httpd:
    httpd.serve_forever() 

Publish localhost to the internet with Ngrok

python


ngrok http 3000

result: image.png

Works with Chatwork webhook and Ngrok

So far, the local webhookchatwork.py file has been published to the internet. When posting from ChatWork, you must set it to receive in webhookchatwork.py. image.png Enter the URL of ngrok in the red frame above After filling in, I think you can work with Chatwork webhook and Ngrok. Verification:

python


python3 webhookchatwork.py 

ChatBot script

There are two ways to handle ChatBot

webhookchatwork.py


APIKEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX' #Obtained from Chatwork API token
ENDPOINT = 'https://api.chatwork.com/v2'
ROOMID = 'XXXXXXXXX'  #The room you want to post
post_message_url = '{}/rooms/{}/messages'.format(ENDPOINT, ROOMID)
headers = { 'X-ChatWorkToken': APIKEY }
def checkAssignee(assigneenum): #Person to reply
    if assigneenum ==3987766: 
        assigneename = 'Mr. A'
    elif assigneenum ==4388605:
        assigneename = 'Mr. B'
    return assigneename

# #Send to chatwork- start
def sendtoChatworkRemind(answer,fromaccountid,sendtouser):
        headers = { 'X-ChatWorkToken': APIKEY }
        params = { 'body': '[To:'+str(fromaccountid)+']'+ sendtouser+ '\n' + str(answer)
                            }


        requests.post(post_message_url,
                         headers=headers,
                         params=params)
#Send to chatwork- end

webhookchatwork.py


        chatbot = ChatBot('EventosChatBot')
        trainer = ListTrainer(chatbot)

        traningjson = []
        print(json_object['webhook_event']['body'].find("[To:2555387]Chat Bot Eventos"))
        if "[To:2555387]Chat Bot Eventos" in json_object['webhook_event']['body'] :
            fromaccountid = json_object['webhook_event']['from_account_id']
            reponse = json_object['webhook_event']['body'].replace("[To:2555387]Chat Bot Eventos\n","")
            sendtouser = checkAssignee(fromaccountid)
            if "Let me tell you]:)" in json_object['webhook_event']['body'] :
                for item in json_object['webhook_event']['body'].split("\n"):
                    if "Question:" in item:
                        print(item.strip().replace("● Question: ",""))
                        if item.strip().replace("● Question: ","") != "":
                            traningjson.append(item.strip().replace("● Question: ",""))
                        else:
                            traningjson.append("")
                    if "Answer:" in item:
                        print(item.strip().replace("● Answer: ",""))
                        if item.strip().replace("● Answer: ","") != "":
                            traningjson.append(item.strip().replace("● Answer: ",""))
                        else:
                            traningjson.append()
                    trainer.train(traningjson)
                answer = "Thank you for teaching(bow)"
                sendtoChatworkRemind(answer,fromaccountid,sendtouser)
            else:
                answer = chatbot.get_response(reponse)
                sendtoChatworkRemind(answer,fromaccountid,sendtouser)

Made in Google extension

Create a Google extension so anyone can train on your chatbot

content_scropts.js


setTimeout(function(){
    $("#__chatworkInputTools_toolbarIcons").prepend('<li class="_showDescription __chatworkInputTools_toolbarIcon" id="teachChatbot"  role="button" aria-label="info: Surround selection with [chatbotEV] tag"><span class="btnDanger" style="padding: 3px 4px; font-size: 10px; border-radius: 3px; position: relative; top: -2px;">chatbotEV</span></li>');
    $("#teachChatbot").click(function(){
    $("#_chatText").val('[To:2555387]Chat Bot Eventos \n let me know]:) \n[info]\n ● Question: \n ● Answer: \n[/info]');
})
},1000);

result: image.png

It's OK. Finally test

Recommended Posts

Python + chatwork + google extension = How to make an easy and funny chat BOT
[Blender x Python] How to make an animation
A Python beginner made a chat bot, so I tried to summarize how to make it.
How to swap elements in an array in Python, and how to reverse an array.
How to make a Python package (written for an intern)
How to make a slack bot
Selenium and python to open google
[Python Tutorial] An Easy Introduction to Python
How to make a string into an array or an array into a string in Python
How to make a surveillance camera (Security Camera) with Opencv and Python
How to package and distribute Python scripts
[Rails] How to introduce Google Analytics [Easy]
How to make an artificial intelligence LINE bot with Flask + LINE Messaging API
How to install and use pandas_datareader [Python]
[Python] How to make a class iterable
python3 How to install an external module
How to update Google Sheets from Python
How to convert Python to an exe file
python: How to use locals () and globals ()
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
How to use is and == in Python
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)
How to use Service Account OAuth and API with Google API Client for python
How to make an embedded Linux device driver (11)
How to make an embedded Linux device driver (8)
How to generate permutations in Python and C ++
How to make an embedded Linux device driver (4)
How to make an embedded Linux device driver (2)
How to crop an image with Python + OpenCV
[Python] How to read data from CIFAR-10 and CIFAR-100
How to make an embedded Linux device driver (3)
Send messages to Skype and Chatwork in Python
How to convert SVG to PDF and PNG [Python]
How to make an embedded Linux device driver (6)
[Python] How to use hash function and tuple.
How to make Substance Painter Python plugin (Introduction)
[Blender x Python] How to make vertex animation
How to make an embedded Linux device driver (5)
How to make an embedded Linux device driver (10)
How to make Python faster for beginners [numpy]
How to make Python Interpreter changes in Pycharm
An easy way to call Java from Python
How to make an embedded Linux device driver (9)
How to plot autocorrelation and partial autocorrelation in python
How to make an arbitrary DictCursor with PyMySQL and not return None when NULL
[Python] Easy Google Translate app using Eel and Googletrans
Easy way to scrape with python using Google Colab
How to run Self bot on Discord.py [Easy vandalism! ]
How to make an interactive CLI tool in Golang
It's not easy to write Python, it's easy to write numpy and scipy
How to make a Python package using VS Code
[Python] How to sort dict in list and instance in list
How to make an HTTPS server with Go / Gin
[Python] How to split and modularize files (simple, example)
How to create an image uploader in Bottle (Python)
[Python] How to create Correlation Matrix and Heat Map
How to make an embedded Linux device driver (12) (Complete)
How to use Django on Google App Engine / Python
How to use Decorator in Django and how to make it