This is the first day of my participation in the First Challenge 2022

Learn about cloud server development with my boss (if you are reading this series for the first time, it is highly recommended to learn the following articles) :

Pilot: Have a server, I unexpectedly so cool?

Alternative project: write a resume page in 10 lines of code!

How to apply for a free SSL certificate for a domain name

A pagoda in Linux, a real pagoda! Detailed tutorial

Finally, a website that everyone can visit

How to send alarm notifications to spikes using Python?

How to send tweets automatically in Python?

Finally, I “built” a job that could program anywhere, anytime

Previously on

In the previous shared article, how to send alarm notifications to spikes using Python? In this paper, we realized the group robot timing/alarm to send customized messages, which is very suitable for general monitoring scenarios, such as: every morning to send their own concerns about the stock/fund opening, trend data, stock decline alarm.

But in other scenarios, such as: knowledge base query, content verification, etc., this kind of interactive query can not be realized. At this time, we need a more advanced robot: Dingdingenterprise robot. This article will teach you how to create enterprise robot by hand to achieve interactive query.

Ii. Sharing summary

  • System: Ali Cloud ECS shared N4 server 1 core 2g storage 50G

  • Environment: python3.6.8 comes with it for easy demonstration, so use it directly

Today, the demo is still using a Linux server, and the operation is similar with a Windows server.

Three, start using your head

3.1 Create a business by yourself

Yes, create your own business, currently There are no restrictions on creating a business, anyone can create, and then you can use all the business management related (free) features of The business.

Nailing create enterprise is very simple, login after nailing, click on the workbench, if not join before should be directly see create enterprise/organization/team button, if to join before, as the chart shows, the drop-down button at the county level, enterprise/organization/team can see the button, click to create a belong to my own business.

3.2 Log in the background of Dingding developers to create enterprise robots

This operation can view nailing the official document: open.dingtalk.com/document/ro…

Login dingpin developer background address:

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

After login, we click Application Development -> Enterprise internal development to enter the enterprise internal development application management background.

Click the robot, then click Create Application, and enter the basic information of the robot.

After the successful creation, we will see the basic information of the robot, mainly including: application information, development management, permission management, etc. First of all, we need to configure the development management, here we need to open a service on the server, used to receive and send pin messages.

3.3 Enabling a Web service for receiving and sending data

In general, we may not have a domain name that has been equipped with certificates and can be accessed, so we can use HTTP: public IP: port number as the address for receiving data. Here we use flask to set up this service (relatively simple).

How to apply for a free SSL certificate for a domain name

First we need to connect to the server, I directly use the pagoda panel login, if you do not know how to install the pagoda readers can see the Linux pagoda, the real pagoda! Detailed tutorial, directly through the pagoda connected to the server, click the terminal, you can enter the server command mode, operation.

Before we write the code, we need to install the libraries,

pip3 install flask
Copy the code

Next, we will go to the project directory, and create a new project folder, EnterpriseBot, and go to the project directory, where you can put your project in the same location as you put your project, and give it a proper name like I did.

cd Project/Little_project/DingdingBot && mkdir EnterpriseBot
cd EnterpriseBot 
Copy the code

We’ll start by writing a simple flask service like this: create a new rt_data.py file, and use the nano command to create and edit the file.

nano rt_data.py
Copy the code

How to set the flask service port to 8083 (default port: 5000), set the flask service port to 0.0.0.0 (default port: 5000), set the flask service port to 8083 (default port: 5000), and set the flask service port to 0.0.0.0 (default port: 5000). The selected port should not be the same as the port you are using to avoid service conflicts and normal operation of the program.

Rt_data.py Receiver Transmitter Data

from flask import Flask


app = Flask(__name__)

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

if __name__ == '__main__':
    # specify host and port
    app.run(host='0.0.0.0', port=8083)
Copy the code

Then press CTRL + O to save the file and CTRL + X to exit editing mode.

Before running the service, add the port where the service resides to the firewall or security policy group. After the service is enabled, IP address 8083 can be used to access the service.

3.4 Accessing the Server Background To allow external users to access the server through port 8083

Ali cloud server is a security policy group, Tencent cloud server is a firewall, to the corresponding location to add ports.

Enter the server background (take Ali Cloud as an example), click Instance -> Security Group -> Configuration Rules, you can enter.

Input port range: 8083/8083, authorization object: 0.0.0.0, and then save. (Note that the selected port is not the same as the port you are using, to avoid service conflict, the program cannot run normally)

After the specified port is added successfully, we can start the service, directly enter the following command in the terminal.

python3 rt_data.py 
Copy the code

Then we go back to the development and management background of the nail robot, the server public IP and server address (http://server public IP address: port number).

3.5 Robot development: Data acquisition

Now that we’ve completed some basic setup, we’re ready to start developing the Dingding auto-reply robot feature.

The header and body contents of the post request sent by the system after the user @robot is provided on the official website of Dingding Open Platform are as follows:

  • http header

  • http body

First of all, we need to use timestamp and sign in the header for digital signature verification. The official website has provided the Python verification code, which can be directly copied and used, and we write it into the 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
Copy the code

There are two parameters involved, one is: app_secret, fixed, we can see in the application information in the background of the development and management of the nail robot.

The other parameter is timestamp, which is the timestamp in the HTTP header.

# Save space, only put part of the main program code # How to build a nail robot that can automatically reply

@app.route("/", methods=["POST"])
def get_data() :
    Step 1 verify whether it is a POST request
    if request.method == "POST":
        # print(request.headers)
        Get Timestamp and Sign from headers
        timestamp = request.headers.get('Timestamp')
        sign = request.headers.get('Sign')
        Step 2 verify that the signature is valid
        if check_sig(timestamp) == sign:
            # Get the data and print it out
            text_info = request.data
            print(text_info)
            print('Verified')
            return str(text_info)
        print('Verification failed')
        return str(timestamp)
    print('Get request')
        
    return str(request.headers)
Copy the code

The returned data is bytes, so we need to change the encoding first and then convert it to a dictionary with a line of code:

# text_info = request.data
text_info = json.loads(str(request.data, 'utf-8'))
Copy the code

Now the return data is a normal dictionary, we can easily retrieve: sender information and sent content, and then match the corresponding content back.

3.6 Robot development: Return data

To return data, the logic is the same as that of the individual nail group robot written before, after obtaining the communication URL, send a POST request, in the system returned HTTP body sessionWebhook is.

In order to facilitate development and testing, before the official release of the robot, we can click version Management and Debugging -> Debugging in the background of Dingdingrobot development management, and the system will automatically help us create a debugging group.

In the code section, we can start by writing a message sending template (using markdown messages as an example) to see how to send alarm notifications to pins in Python. Readers should be familiar with the format and content of the article, you can take a look at the previous article or the official nail document.

The official documentation address: developers.dingtalk.com/document/ro…

# Send markDown message
def send_md_msg(userid, title, message, webhook_url) :
    Userid: @user pin ID title: message title: message body content webhook_URL: communication URL
    data = {
        "msgtype": "markdown"."markdown": {
            "title":title,
            "text": message
        },
        ''' "msgtype": "text", "text": { "content": message }, '''
        "at": {
            "atUserIds": [
              userid
          ],
        }
    }
    Use requests to send post requests
    req = requests.post(webhook_url, json=data)
Copy the code

We then write a function that handles user messages, specifically to handle user messages, and returns the specified content as follows:

# Handle auto-reply messages
def handle_info(req_data) :
    # resolve the webhook_url for user sent messages
    text_info = req_data['text'] ['content'].strip()
    webhook_url = req_data['sessionWebhook']
    senderid = req_data['senderId']
    # print('***************text_info: ', text_info)
    # if determines the keyword triggered by the user's message and returns the corresponding content
    Python3.10 switch case
    if text_info == 'welfare':
        title = "[Simple Python] Welfare of the Day"
        text = Hello, I am old cousin, with me to learn Python, cloud server development knowledge! \n >! [] (https://img-blog.csdnimg.cn/246a90c55c4e46dca089731c5fd00833.png) * * [class blog, has launched] (https://python-brief.com/) * * \ n "" "
        Call the function and send the markdown message
        send_md_msg(senderid, title, text, webhook_url)
    if text_info == 'xxx':
      print('You can write more matching, response patterns')
Copy the code

Above just as an example, if the real use, every time we encounter an autoresponder matching, the response is to write an if judgment, that would be a little trouble, so in this case, you can maintain a knowledge base, such as an excel spreadsheet, which contain questions and answers, each match files directly read data, then to the matching results.

Finally, the main service module, call the above function, pass the parameters, as follows:

@app.route("/", methods=["POST"])
def get_data() :
    Step 1 verify whether it is a POST request
    if request.method == "POST":
        # print(request.headers)
        Get Timestamp and Sign from headers
        timestamp = request.headers.get('Timestamp')
        sign = request.headers.get('Sign')
        Step 2 verify that the signature is valid
        if check_sig(timestamp) == sign:
            # Get and process data
            req_data = json.loads(str(request.data, 'utf-8'))
            # print(req_data)
            Call the data handler function
            handle_info(req_data)
            print('Verified')
            return 'hhh'
            
        print('Verification failed')
        return 'ppp'
        
    print('Get request')
    return 'sss'
Copy the code

After the server is started, the effect is as follows: @ robot in the group can also be private chat.

3.7 Creating a daemon process for an Application

After we finished the feature development, we found that once we closed the application, the auto reply service would also stop, so we need to create a daemon to protect our process.

In my case, after logging into the pagoda panel, go to /etc/systemd/system and create a new 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
Copy the code

After saving the file, we can directly execute the following command in the terminal to start the daemon process. After running, it will enter the daemon state. We can press CTRL + C to exit without affecting the daemon process:

systemctl start ding_bot
Copy the code

After the code is modified, the daemon process needs to be restarted for the modification to take effect. The restart command is as follows:

systemctl restart ding_bot
Copy the code

If you do not want to set up the daemon, you can stop the service (and the program will also stop) by executing the stop command:

systemctl stop ding_bot
Copy the code

Next up

After a whole afternoon, the liver came out, but there are still some defects, such as: There is no robot reply @user (there is senderId in HTTP body, but it is encrypted, do not see what encryption method), just simple automatic reply (can create knowledge base management questions and answers, but also can be combined with the previous data monitoring function).

We welcome you to understand the reader to study and exchange, progress together.

Recently, I have arranged time to optimize a wave, and I do have relevant needs, such as: do inspiration record, to-do list reminder, website query, etc.

Like to see the message forwarding, four support, the original is not easy. Ok, see you next time, I love the cat love technology, more love si si’s old cousin Da Mian ଘ(˙꒳˙)ଓ Di Di