当前位置:网站首页>How to build a nail robot that can automatically reply

How to build a nail robot that can automatically reply

2022-07-06 15:18:00 Jane said Python

Pay attention to me , Learn with an old watch Python、 Cloud server

Learn cloud server development with Lao Biao Related articles ( If you are reading this series for the first time , It is strongly recommended to study the following articles first ):

Forerunner : Having a server , I'm so cool ?

Alternative items :10 Line of code to write a resume page !

Teach you how to apply for a domain name for free SSL certificate

Linux Pagoda in , The real pagoda ! Detailed tutorial

Finally, there is a website that everyone can visit

How to use Python Send alarm notification to nail ?

Python Automation practice , Automatically log in and send microblog

finally “ make ” A tool that can be programmed anytime, anywhere

One 、 Previous review

Articles shared before How to use Python Send alarm notification to nail ? In this paper, we realize the timing of nail swarm robots / Alarms send custom messages , It is very suitable for general monitoring scenarios , such as : Send your favorite stocks every morning / Fund opening 、 Trend data 、 Stock decline alarm, etc .

But in other scenarios , such as : Knowledge base query 、 Content verification, etc , This kind of interactive query cannot be realized , This is the time , We need more advanced robots : Nail enterprise robot , This article will teach you how to create an enterprise robot , Realize interactive query .

The complete code of this article can pay attention to my other official account 【 Jane said programming 】, reply : Code   obtain .( Be careful ️, See how to get it ).

Two 、 Share summary

  • System : Alibaba cloud ECS Shared n4 The server 1 nucleus 2g Storage 50g

1e5bd3c24e1b5d0d39dea98c3f676f5a.png
  • Environmental Science : Bring their own python3.6.8 Easy to demonstrate , Use it directly

It is still used today Linux Server demo , Use Windows The operation of the server is similar to .

3、 ... and 、 Start thinking

3.1 Create an enterprise by yourself

you 're right , Create an enterprise by yourself , At present, nailing has no restrictions on the creation of enterprises , Everyone can create , Then you can use the nail enterprise to manage all the relevant ( free ) The function of .

It is very easy to create an enterprise by nailing , After logging in to nail , Click on The workbench , If you haven't joined before, you can directly see Create a business / organization / The team Button , If you have joined , As shown in the figure , County level drop-down button , You can see that Create a business / organization / The team It's a button , Click to create your own enterprise .

c5a76788e4971b4d25a201cfa1b137b5.png

3.2 Log in to nail developer background , Create an enterprise robot

This operation allows you to view the official document of nailing :https://open.dingtalk.com/document/robots/enterprise-created-chatbot

Login nail developer background address :

https://open-dev.dingtalk.com/?spm=ding_open_doc.document.0.0.5d08722fvbdReF

After logging in , We click application development -> Enterprise internal development , Enter the enterprise's internal development application management background .

9caff1f08b9d0d9607e05363aff90f15.png

Click on robot , And then click Create an , Enter the basic information of the robot .

ca8616ad89a7cef127a7c77f12f2641b.png

Once created , We will see the basic information of the robot , It mainly includes : Application information 、 Development management 、 Permission management, etc. , First of all, we need to configure Development management , Here we need to start a service on the server , Used to receive and send pinning messages .

5dbdc90d192e12be625478d4d94b5c2e.png

3.3 To start a web service , Used to receive and send data

General situation , We may not have a domain name that has been equipped with a certificate and can be accessed , So we can use it http: Public network ip: Port number As the address for receiving data , Here we use flask To build this service ( Relatively simple ).

Teach you how to buy and apply for domain names for free SSL certificate

First, we need to connect to the server , I log in directly using the pagoda panel , If you don't know how to install and use the pagoda, you can see Linux Pagoda in , The real pagoda ! Detailed tutorial , After connecting to the server directly through the pagoda , Click on terminal , You can enter the server command mode , To operate .

Before you write the code , We need to install the related libraries ,

pip3 install flask

Next , We go into the project catalog , Then create a new project folder EnterpriseBot, And go to the project directory , Here you can store the project in the location where you store the project , Just give me a proper name .

cd Project/Little_project/DingdingBot && mkdir EnterpriseBot
cd EnterpriseBot
b4e135334ecbc3cd008508770f930a02.png

Let's write a simple one first flask service , as follows : Create a new one rt_data.py file , Here we use it directly nano Directive to create and edit files ,

nano rt_data.py

After entering edit mode , Write the following code ,7 Line of code simply writes a flask service , Appoint host by 0.0.0.0, So all the extranets ip You can access the server services , In addition, the service running port is set port by 8083, The default port is 5000, You can change it at will ,( Pay attention , The selected port should not be the same as the port you are using , Avoid service conflicts , Program does not work properly ).

'''
rt_data.py
Receiver Transmitter Data  Data receiver and transmitter 
'''

from flask import Flask


app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>Hello World</h1>'

if __name__ == '__main__':
    #  Appoint host and port
    app.run(host='0.0.0.0', port=8083)

Then press ctrl+o Save the file , Press again ctrl+x Exit edit mode .

2dc890a342994f9b0ff40b86fec5c3ff.png

Before formal operation , You also need to add the port where the service is located to the firewall / In the security policy group , The service can only be used normally after it is started ip Address :8083 Visit .

3.4 Enter the server background , Allow external passage 8083 Port access server

Alibaba cloud server is a security policy group , Tencent cloud server is a firewall , Add a port to the corresponding location .

Enter the server background ( Take Alibaba cloud as an example ), Click on example -> Security group -> Configuration rules , You can enter .

a0258d41e75e0732e505080acc40fd1d.png

Into the direction , Click Add manually , Whatever else , Main input port range :8083/8083, Authorized person :0.0.0.0, And save it .( Pay attention , The selected port should not be the same as the port you are using , Avoid service conflicts , Program does not work properly )

9623e24ad7cf9a36d1bd1b6c63f42f36.png
In the screenshot 8888 The port is the previous , Same steps

After the specified port is added successfully , We can start the service , Directly input the following commands at the terminal .

python3 rt_data.py
9a7dadf259dd05d9cf4bdf0fea702afe.png

Then we go back to the nail robot development and management background , Server public network IP And the server address (http:// Server public network ip: Port number ) that will do .a47b04f3d689533d81ef58d34853c1e9.png

3.5 Robot development : get data

We have completed some basic settings , Now let's officially develop the nail auto recovery robot function .

Users are listed on the official website of nailing open platform @ Behind the robot , The system sends post On request header and body Content , as follows :

  • http header830dd14ea830817fd661effed2a4b74b.png

  • http bodye09b864b79ef040620ad424f0969c034.png

First we need to make use of header Inside timestamp and sign Do digital signature verification , The official website has provided Python Validation code , Copy directly to use , We wrote check_sig Function .

#  Message digital signature calculation check 
def check_sig(timestamp):
    app_secret = ' Your own app_secret'
    app_secret_enc = app_secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, app_secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(app_secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign

There are two parameters involved , One is :app_secret, fixed , We are in the background of nail robot development and management Application information Can be seen in .

b22324a6c5286044f3725c3bbcce6d72.png

Another parameter is :timestamp, Namely http header Medium timestamp, We can get the incoming function through the code .

#  Save space , Only part of the code of the main program is put 
#  The complete code of the project can be found in official account : Jane said programming , reply : Code , obtain 

@app.route("/", methods=["POST"])
def get_data():
    #  The first step is to verify : Whether it is post request 
    if request.method == "POST":
        # print(request.headers)
        #  Signature verification   obtain headers Medium Timestamp and Sign
        timestamp = request.headers.get('Timestamp')
        sign = request.headers.get('Sign')
        #  Step 2 verification : Whether the signature is valid 
        if check_sig(timestamp) == sign:
            #  get data   Print it out 
            text_info = request.data
            print(text_info)
            print(' Verification passed ')
            return str(text_info)
        print(' Verification failed ')
        return str(timestamp)
    print(' Yes get request ')
        
    return str(request.headers)
a32a16cdcf19e846e8344867bc2f4fa5.png

The returned data is bytecode (bytes type ), So we need to change the code first , Then convert to dictionary type , Just modify one line of code :

# text_info = request.data  Change it to 
text_info = json.loads(str(request.data, 'utf-8'))
4a9f61d0f7afba6b981eb861c1b33e3a.png

Now the returned data is the normal dictionary , We can take it out easily : Sender information and content , Then match and return the corresponding content .

3.6 Robot development : Return the data

Return the data , The logic is the same as that of the personal nail swarm robot written before , Get communication url after , send out post The request can be , Returned in the system http body Medium sessionWebhook Namely .

To facilitate development and testing , Before the official release of the robot , We can click on the nail robot development and management background first Version management and debugging -> debugging , The system will automatically help us create a debugging group .

f7164e4eacb57f864ee16083426efe34.png

Code section , We can write a message sending template first ( With markdown Format message is an example ), seen How to use Python Send alarm notification to nail ? Its format and content should be familiar to the readers , You can read the previous articles or nail the official documents .

Official document address :https://developers.dingtalk.com/document/robots/customize-robot-security-settings

#  send out markdown news 
def send_md_msg(userid, title, message, webhook_url):
    '''
    userid: @ user   nailing id
    title :  Message title 
    message:  Message body content 
    webhook_url:  Communications url
    '''
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title":title,
            "text": message
        },
        '''
        "msgtype": "text",
        "text": {
            "content": message
        },
        '''
        "at": {
            "atUserIds": [
              userid
          ],
        }
    }
    #  utilize requests send out post request 
    req = requests.post(webhook_url, json=data)

Then we write a function that processes user messages , Specialized in handling user messages , Then return to the specified content , as follows :

#  Process auto reply messages 
def handle_info(req_data):
    #  Parsing messages sent by users   Communications webhook_url 
    text_info = req_data['text']['content'].strip()
    webhook_url = req_data['sessionWebhook']
    senderid = req_data['senderId']
    # print('***************text_info:', text_info)
    # if Determine the keyword triggered by the user message , Then return to the corresponding content 
    # python3.10  The above can also be used  switch case...
    if text_info == ' welfare ':
        title = "【 Jane said Python】 Benefits today "
        text = """###  Welfare Introduction 
 Hello , I'm an old watch , Study with me Python、 Cloud server development knowledge !\n
>![](https://img-blog.csdnimg.cn/246a90c55c4e46dca089731c5fd00833.png)
**[ Lao Biao's personal blog , Online ](https://python-brief.com/)**\n
            """
        #  Call function , send out markdown news 
        send_md_msg(senderid, title, text, webhook_url)
    if text_info == 'xxx':
      print(' You can also write more matches 、 Response patterns ')

The above is just an example , If in real use , Every time we come across an automatic reply, we write one if Judge the match 、 Respond to , That's a bit of a problem , So in this case , You can maintain a knowledge base , For example, a excel form , It contains questions and answers , Read the file data directly every time , Then match the results .

Last , It is the main service module , Call the above related functions , Just pass the parameters , as follows :

@app.route("/", methods=["POST"])
def get_data():
    #  The first step is to verify : Whether it is post request 
    if request.method == "POST":
        # print(request.headers)
        #  Signature verification   obtain headers Medium Timestamp and Sign
        timestamp = request.headers.get('Timestamp')
        sign = request.headers.get('Sign')
        #  Step 2 verification : Whether the signature is valid 
        if check_sig(timestamp) == sign:
            #  obtain 、 Processing data  
            req_data = json.loads(str(request.data, 'utf-8'))
            # print(req_data)
            #  Call the data processing function 
            handle_info(req_data)
            print(' Verification passed ')
            return 'hhh'
            
        print(' Verification failed ')
        return 'ppp'
        
    print(' Yes get request ')
    return 'sss'

After the server is started, the effect is as follows , Within the group @ robot , You can also talk privately .

40db9690f26ccb2f676993673eaa47a6.png
Group chat display
ed343f8783c8a0b57cd2d08e7425070a.png
Private chat shows

3.7 Create daemons for programs

After the above, we have completed the function development , But you will find , Once we close the program , The auto reply service will also stop , So we need to create a daemon to protect our process .

Take myself for example , After we log in to the pagoda panel , Get into /etc/systemd/system Under the folder , Create a new one ding_bot.service file , And write the following :

[Unit]
Description=Dingding Bot service

[Service]
Type=forking
ExecStart=/usr/bin/python3 /root/Project/Little_project/DingdingBot/EnterpriseBot/rt_data.py
KillMode=process
Restart=on-failure
RestartSec=3s

[Install]
WantedBy=multi-user.target

After saving the file , We can start the daemon by directly executing the following instructions in the terminal , After running, it will enter the daemon state , We can press ctrl+c sign out , Will not affect the daemon :

systemctl start ding_bot

After the code is modified , The daemon needs to be restarted , Modify the code to take effect , The restart command is as follows :

systemctl restart ding_bot

If you don't want to set up this daemon , perform stop The command can stop the service( The program will also stop ), The instructions are as follows :

systemctl stop ding_bot

Next up

After a long afternoon , Come out , However, there are still some defects , such as : Robot reply is not realized @ user (http body There are senderId, It's just encrypted , I don't know what the encryption method is ), Just a simple auto reply ( You can create a knowledge base to manage questions and answers , It can also be combined with the previous data monitoring function ) etc. .

Welcome readers who know you well to learn and exchange , Progress together .

Recently, I arranged a time to optimize a wave , I do have relevant needs , such as : Make inspiration notes 、 To do reminder 、 Website query, etc .

give the thumbs-up Looking at Leaving a message. forward  , The fourth company supports , Originality is not easy. . well , See you next time , I love cats and technology , More loving old watch ⁽⁽ଘ( ˙꒳˙ )ଓ⁾⁾

How to find me :

d863bfc92aba5620ab503b79ccb53eb6.png

原网站

版权声明
本文为[Jane said Python]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131319309988.html