A Python beginner made a chat bot, so I tried to summarize how to make it.

Recently, I went to an AI / IOT seminar. In terms of content, how about programming to improve the skills of clerical staff rather than for engineers? It was a kind of story, but it was enough for me to think that I should try Python! Thank you! (*'∀')

That's why this time, I'm a Python beginner, and I'm always trying to implement the LINEWORKS BOT in Python!

Production environment

Language: python WEB framework: Flask Editor: Visual Studio Code Server: Local environment (ngrok)

I don't have a verification server, so it's still local (laughs) I love ngrok! (゚ Д ゚)

Environment

I referred to the articles of my seniors for the detailed construction procedure! Thank you! (*'▽') I will not explain it here, so I will post a link ('ω') No Petapeta

  1. Install Python and Visual Studio Code on your PC (https://qiita.com/hashito/items/8f77a61ffdfe9f3d0ecb)
  2. Install Flask
  3. [Publish your local to the outside with ngrok](https://qiita.com/proken/items/80d20adcf24b2b53c149#%E3%82%84%E3%82%8A%E3%81%8B%E3%81 % 9F)
  4. [Settings and bot registration for using API in LINEWORKS](https://qiita.com/tokotan/items/f615f4a62219d655436f#developer-console%E3%81%A7api%E3%82%92%E4%BD% BF% E3% 81% 86% E3% 81% 9F% E3% 82% 81% E3% 81% AE% E8% A8% AD% E5% AE% 9A% E3% 81% A8bot% E3% 82% 92% E7% 99% BB% E9% 8C% B2% E3% 81% 99% E3% 82% 8B)

For the Callback URL when registering the BOT, use the URL obtained by ngrok. Of course, if you have your own server, please use it. This completes the settings!

Finally, we will make the BOT body with Python ~ (* ´Д `)

Receive a message to the BOT

Receive messages sent to the BOT using Flask.

Flask is a Python web framework. Django seems to be more famous and highly functional in Python, but since it was personally developed, I decided to use lightweight Flask.

I have a lot of knowledge and it really helps! (* ^ ▽ ^ *)

Now, let's first display the received message on the console. Like this.

1585814270.png

b'{"type":"message","source":{"accountId":"xxx@yyy-zzz"},"createdTime":1585813140779,"content":{"type":"text","text":"hoge"}}'

I will write the code.

bot.py


from flask import Flask, request
app = Flask(__name__)

@app.route('/callback', methods=['POST'])
def callback():
    data = request.get_data()
    print(data)
    return "200 ok"

##port setting
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=8000)

Where I stumbled

--To use request.get_data () to receive a message

It's the first line, but it seems that I can't receive the message if I just import flask. Follow it with , request and then import request as well.

--return I get angry if I don't enter

At first, I got angry when I emptied the return.

TypeError: The view function did not return a valid response. 
The function either returned None or ended without a return statement.

I received it for the time being! That's why I returned 200 ok. … Maybe there is a way to return it properly, like the javascript res.send. (.-`ω-)

--Port defaults to 5000

If you do nothing in the port setting, the default will be 5000.

if __name__ == "__main__":
    app.run(debug=True) #port is set to 5000

No, 5000 is fine, but ngrok set it to 8000 and it turned out to be "I can't connect! (゚ Д ゚)" w

I stumbled on it, but thanks to the knowledge of my seniors, I solved it myself! Thank you! (*'▽')

Let's move on to the next STEP!

Reply when you receive a message

I use the LINEWORKS API to reply, but some people have published the library to PyPI! Thanks! (* ^ ▽ ^ *) PyPI - lineworks 0.1.0

Let's install and use it immediately.

pip install lineworks

After installing, add the code referring to the sample.

lineworks_bot.py


from flask import Flask, request
app = Flask(__name__)

from lineworks import TalkBotApi
api_id = "your api id."
server_api_consumer_key = "your server api consumer key"
server_id = "your server id."
private_key = "your private key."
domain_id = "your domain id."
bot_no = "your bot number."

import json
@app.route('/callback', methods=['POST'])
def callback():
    data = json.loads(request.get_data())
    talk_bot = TalkBotApi(api_id, server_api_consumer_key, server_id, private_key, domain_id, bot_no)
    #Send message (return parrot)
    talk_bot.send_text_message(send_text=data['content']['text'], account_id=data['source']['accountId'])
    return "200 ok"

##port setting
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=8000)

Run it in Visual Studio Code and you're ready to go! Let's talk! (* ´ ▽ ` *)

1586240207.png

YES!NINJA! You returned the parrot properly! It's a success ♪

Where I stumbled

--How to write privateKey

This is a stumbling block, but as you can see from the actual authentication key, it is extremely long and has strange line breaks. So it's a little troublesome, " ----- BEGIN PRIVATE KEY ----- \ nMIIEvAIBADANBgkqhkiG9 ... \ n ----- END PRIVATE KEY ----- " \ nand\ n` so that Put the authentication key between and write it in one line.

--Handling of JSON data

Use it after parse it with loads in the JSON library. However, if you try to handle it with data.source.accountId and parameters like Javascript, an error will occur. (It's very possible that my method is wrong ...) Therefore, when extracting the contents, write data ['source'] ['accountId'] as described above. In the example, text and ʻaccountId` in the JSON data are extracted and used.

Anyway, it's done! (^ O ^)

in conclusion

Thank you for staying with us so far.

No, what I'm doing is the same as usual, but different languages are different. But I feel like I'm getting along a little!

With this momentum, I would like to develop BOTs that work with machine learning APIs. see you! (^^) /

I used it as a reference m (_ _) m

LINEWORKS Developers Install python and Visual Studio Code on windows 10 (April 2020 version) Easy to use Flask LINEbot development, I want to check the operation in the local environment First bot development in LINE WORKS! (Part 1) Use request.get_data () to receive the data posted in Flask as it is Created a Python library to call the LINE WORKS API

Recommended Posts

A Python beginner made a chat bot, so I tried to summarize how to make it.
[Python] I tried to implement stable sorting, so make a note
I tried to make a calculator with Tkinter so I will write it
I tried to summarize how to use matplotlib of python
I tried to summarize how to use pandas in python
How to make a slack bot
I tried "How to get a method decorated in Python"
I tried to make a stopwatch using tkinter in python
A python beginner tried to intern at an IT company
[Git] I tried to make it easier to understand how to use git stash using a concrete example
I made a function to crop the image of python openCV, so please use it.
[5th] I tried to make a certain authenticator-like tool with python
[2nd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
[3rd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "date" using Python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I made a segment tree with python, so I will introduce it
I tried to summarize Python exception handling
Python3 standard input I tried to summarize
I tried to make a Web API
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
I made a Discord bot in Python that translates when it reacts
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to discriminate a 6-digit number with a number discrimination application made with python
[Zaif] I tried to make it easy to trade virtual currencies with Python
I want to make a game with Python
I read "How to make a hacking lab"
I tried to make a ○ ✕ game using TensorFlow
I made a Mattermost bot with Python (+ Flask)
A python beginner tried to intern at an IT company [Day 2 chatbot survey]
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
A python beginner tried to intern at an IT company [Day 1 development process]
I tried to make a simple mail sending application with tkinter of Python
I made a Line Bot that uses Python to retrieve unread Gmail emails!
When I tried to make a VPC with AWS CDK but couldn't make it
[Patent analysis] I tried to make a patent map with Python without spending money
When I tried to create a virtual environment with Python, it didn't work
Python + chatwork + google extension = How to make an easy and funny chat BOT
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
I tried to make a translation BOT that works on Discord using googletrans
I didn't understand the Resize of TensorFlow so I tried to summarize it visually.
I set up TensowFlow and was addicted to it, so make a note
The tree.plot_tree of scikit-learn was very easy and convenient, so I tried to summarize how to use it easily.
I tried to make a "fucking big literary converter"
I made a Twitter BOT with GAE (python) (with a reference)
I tried to draw a route map with Python
I tried to implement a pseudo pachislot in Python
I made a Python module to translate comment outs
Continuation ・ I tried to make Slackbot after studying Python3
I made a LINE BOT with Python and Heroku
How to make a Python package using VS Code
I tried to automatically generate a password with Python3
I made a python library to do rolling rank