当前位置:网站首页>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
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 .
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 .
Click on robot
, And then click Create an
, Enter the basic information of the robot .
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 .
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
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 .
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 .
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 )
After the specified port is added successfully , We can start the service , Directly input the following commands at the terminal .
python3 rt_data.py
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 .
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 header
http body
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 .
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)
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'))
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 .
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 .
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 :
边栏推荐
- Contest3145 - the 37th game of 2021 freshman individual training match_ A: Prizes
- Interview answering skills for software testing
- 自动化测试中敏捷测试怎么做?
- 软件测试需求分析之什么是“试纸测试”
- 软件测试行业的未来趋势及规划
- Brief introduction to libevent
- Report on the double computer experiment of scoring system based on 485 bus
- C language do while loop classic Level 2 questions
- What are the software testing methods? Show you something different
- [200 opencv routines] 98 Statistical sorting filter
猜你喜欢
Build your own application based on Google's open source tensorflow object detection API video object recognition system (I)
Leetcode simple question: check whether the numbers in the sentence are increasing
[Ogg III] daily operation and maintenance: clean up archive logs, register Ogg process services, and regularly back up databases
C4D quick start tutorial - creating models
Introduction to safety testing
STC-B学习板蜂鸣器播放音乐2.0
CSAPP家庭作業答案7 8 9章
UCORE lab7 synchronous mutual exclusion experiment report
In Oracle, start with connect by prior recursive query is used to query multi-level subordinate employees.
How to transform functional testing into automated testing?
随机推荐
软件测试有哪些常用的SQL语句?
Heap, stack, queue
Stc-b learning board buzzer plays music 2.0
C4D quick start tutorial - creating models
Contest3145 - the 37th game of 2021 freshman individual training match_ A: Prizes
Should wildcard import be avoided- Should wildcard import be avoided?
Cc36 different subsequences
软件测试行业的未来趋势及规划
150 common interview questions for software testing in large factories. Serious thinking is very valuable for your interview
What to do when programmers don't modify bugs? I teach you
Global and Chinese markets for GaN on diamond semiconductor substrates 2022-2028: Research Report on technology, participants, trends, market size and share
[HCIA continuous update] advanced features of routing
UCORE lab5 user process management experiment report
The minimum sum of the last four digits of the split digit of leetcode simple problem
Daily code 300 lines learning notes day 9
Leetcode simple question: check whether two strings are almost equal
MySQL数据库(四)事务和函数
Global and Chinese markets of MPV ACC ECU 2022-2028: Research Report on technology, participants, trends, market size and share
Install and run tensorflow object detection API video object recognition system of Google open source
UCORE lab1 system software startup process experimental report