程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

First: Python sends message reminders based on nail monitoring

編輯:Python

One . Set nails before use

1. Since you are using the nail message to remind , Then you need nails .

2. The second step is to customize the robot group , So you need to have a group .

3. Add robots , Click on the picture > Robot Management > Custom robots

4. Give the robot a name > Select which group to add to > Choose your own security settings > complete

Two . Security Settings

1. There are three security settings : Custom keywords 、 The signature of the 、IP Address .

2. Custom keywords : Simply put, the content you send must contain this keyword , To send successfully .

3. The signature of the : Is to generate your specific signature , In the program , Generate parameters for encryption , When asked , Carry this parameter , To send successfully .

4.IP Address : It is specified in the settings IP Request within address range , To send successfully .

5. Choose your own security settings , Here we choose to add a signature , After configuration , The code is in use 、 Reuse 、 The migration and other aspects will be a little more flexible , If in the company , Just choose according to your actual needs . Record this signature , You will need it later to encrypt the generation parameters .

6. Click finish , You can see your own Webhook, write down , I need to use it later .

3、 ... and . Send a request

1. First , stay __init__ In the method , Configure the robot information .

def __init__(self):
# The security settings use the signature method 
timestamp = str(round(time.time() * 1000))
secret = 'SEC7******fe0a' # The signature just recorded 
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
# The above is the security configuration for signing , Other security settings , No need to configure the above information 
# webhook Address 
webhook = 'https://oapi.dingtalk.com/robot/send?******' # Just recorded webhook
self.webhook = "{}&timestamp={}&sign={}".format(webhook, timestamp, sign) # If your is not a safe way to sign , It can be omitted &timestamp={}&sign={} Some parameters 
# Configuration request headers
self.headers = {

"Content-Type": "application/json",
"Charset": "UTF-8" # launch POST When asked , The character set encoding must be set to UTF-8.
}

2. secondly , Send a request

def send_req(self, message):
""" Send a request :param message: Your message body :return: """
# The requested data is processed json Data encapsulation 
form_data = json.dumps(message)
# Initiate request 
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# Print the returned results 
print(' Email results :', res_info.json())
print(' Successful notification !' if (res_info.json())['errmsg'] == 'ok' else ' Inform the failure !')

3. Again , Construct the message body , Nail given 6 Message type body

3.1. The first one is 、text Type text data

def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
""" send out text Type text data :param content: The message content :param at_mobiles: Incoming list type data ,@ Phone contacts that appear in the list , If there is no such contact in the group , Will not be @( Optional parameters ) :param is_at_all: whether @ All the people , The default is not Aite ( Optional parameters ) :return: """
message = {

"msgtype": "text", # Message type 
"text": {

"content": content
},
"at": {

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # Send a message 

a. call

DingTalkWarn().send_text_msg(' Test message sending !')

b. design sketch

3.2. The second kind 、link Type text data

def send_link_msg(self, text, title, message_url, pic_url=None):
""" send out link Type text data :param text: The message content :param title: Message title :param message_url: Click on the message to jump to URL :param pic_url: picture URL( Optional parameters ) :return: """
message = {

"msgtype": "link",
"link": {

"text": text, # The message content , If it's too long, it'll only show part of it 
"title": title, # Message title 
"picUrl": pic_url, # picture URL
"messageUrl": message_url # Click on the message to jump to URL
}
}
self.send_req(message) # Send a message 

a. call

DingTalkWarn().send_link_msg(
text=' Love sharing , Love toss , Love life , Willing to share some of my own experiences in the learning process 、 experience .',
title='a'ゞ Pistachio blog ',
message_url='https://blog.csdn.net/qq_45352972',
pic_url='https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png'
)

b. design sketch

3.3. The third kind of 、markdown Type text data

def send_markdown_msg(self, text, title, at_mobiles=None, is_at_all=False):
""" send out markdown Type text data :param text: markdown Format content :param title: title :param at_mobiles: Incoming list type data ,@ Phone contacts that appear in the list , If there is no such contact in the group , Will not be @( Optional parameters ) :param is_at_all: whether @ All the people , The default is not Aite ( Optional parameters ) :return: """
message = {

"msgtype": "markdown",
"markdown": {

"title": title,
"text": text
},
"at": {

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # Send a message 

a. call

DingTalkWarn().send_markdown_msg(
text="## This is a secondary title \n ![news](https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png)\n###### {} Release ".format(time.strftime("%Y-%m-%d %H:%M:%S")),
title='markdown Format data ',
)

b. design sketch

3.4. A fourth 、 Jump as a whole ActionCard Data of type

def send_all_action_card_msg(self, text, title, single_url, single_title=' Read the whole passage '):
""" Send overall jump ActionCard Data of type :param text: markdown Format content :param title: title :param single_url: details url Address :param single_title: Click the enter details button :return: """
message = {

"actionCard": {

"title": title,
"text": text,
"singleTitle": single_title,
"singleURL": single_url
},
"msgtype": "actionCard"
}
self.send_req(message) # Send a message 

a. call

DingTalkWarn().send_all_action_card_msg(
text='## Caught tools -mitmproxy Prelude \n ![](https://img-blog.csdnimg.cn/20201211103655824.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70)\n Introduce :mitmproxy Be similar to Fiddler、Charles The function of , Can support HTTP Follow HTTPS request , But it is operated through the console .mitmproxy There are two associated components ,mitmdump Follow mitmweb.mitmdump yes mitmproxy Command line interface for ;mitmweb It's a web Program , You can pass ...',
title=' Caught tools -mitmproxy Prelude ',
single_url='https://blog.csdn.net/qq_45352972/article/details/111028741?spm=1001.2014.3001.5501'
)

b. design sketch

3.5. The fifth 、 Independent jump ActionCard Data of type

def send_alone_action_card_msg(self, text, title, btn_orientation=1, btns=None):
""" Send an independent jump ActionCard Data of type :param text: markdown Formatted text data :param title: title :param btn_orientation: 0- Buttons arranged vertically ;1- Buttons are arranged horizontally :param btns: The list of data , Save string inside , Used to put button information and links , as follows [ { "title": " Good content ", "actionURL": "https://www.dingtalk.com/" }, { "title": " Not interested in ", "actionURL": "https://www.dingtalk.com/" } ] :return: """
message = {

"msgtype": "actionCard",
"actionCard": {

"title": title,
"text": text,
"hideAvatar": "0",
"btnOrientation": btn_orientation,
"btns": btns
}
}
self.send_req(message) # Send a message 

a. call

DingTalkWarn().send_alone_action_card_msg(
text='### Check your friends' blogs \n![](https://profile.csdnimg.cn/C/B/7/1_qq_45352972)',
title=' Check your friends' blogs ',
btns=[
{

"title": " Not interested in ",
"actionURL": "https://www.dingtalk.com/"
},
{

"title": " Let me see ",
"actionURL": "https://blog.csdn.net/qq_45352972/"
}
]
)

b. design sketch

3.6. 6 kinds of 、FeedCard Type data

def send_feed_card_msg(self, links):
""" send out FeedCard Type data :param links: List the type , The format is as follows [ { "title": " The train of the times is moving forward 1", "messageURL": "https://www.dingtalk.com/", "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" }, { "title": " The train of the times is moving forward 2", "messageURL": "https://www.dingtalk.com/", "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" } ] :return: """
message = {

"msgtype": "feedCard",
"feedCard": {

"links": links
}
}
self.send_req(message) # Send a message 

a. call

DingTalkWarn().send_feed_card_msg(
links=[
{

"title": " The solution of the crawler needs to log in to the website ",
"messageURL": "https://blog.csdn.net/qq_45352972/article/details/113831698?spm=1001.2014.3001.5501",
"picURL": "https://img-blog.csdnimg.cn/20210217102838577.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70#pic_center"
},
{

"title": " The console simply prints and displays the progress bar ",
"messageURL": "https://blog.csdn.net/qq_45352972/article/details/112191329?spm=1001.2014.3001.5501",
"picURL": "https://img-blog.csdnimg.cn/20210104184651355.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70"
},
{

"title": "Email Email reminders ",
"messageURL": "https://blog.csdn.net/qq_45352972/article/details/109280576?spm=1001.2014.3001.5501",
"picURL": "https://img-blog.csdnimg.cn/2020102522530334.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70#pic_center"
}
]
)

b. design sketch

Four . Complete code

import base64
import hashlib
import hmac
import time
import urllib.parse
import requests
import json
class DingTalkWarn:
""" Nail message notice """
def __init__(self):
# The security settings use the signature method 
timestamp = str(round(time.time() * 1000))
# The signature just recorded 
secret = 'SEC24e640447734a80b9d430d678765a103652b33f334a69974cfda88415e601d22'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
# The above is the security configuration for signing , Other security settings , No need to configure the above information 
# webhook Address ( Just recorded webhook)
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=5f56131ba70c78f42a10c7e9531c8da55def990313a4a74cfc87bf82c4bb8b7b'
# If your is not a safe way to sign , It can be omitted &timestamp={}&sign={} Some parameters 
self.webhook = "{}&timestamp={}&sign={}".format(webhook, timestamp, sign)
# Configuration request headers
self.headers = {

"Content-Type": "application/json",
"Charset": "UTF-8" # launch POST When asked , The character set encoding must be set to UTF-8.
}
def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
""" send out text Type text data :param content: The message content :param at_mobiles: Incoming list type data ,@ Phone contacts that appear in the list , If there is no such contact in the group , Will not be @( Optional parameters ) :param is_at_all: whether @ All the people , The default is not Aite ( Optional parameters ) :return: """
message = {

"msgtype": "text", # Message type 
"text": {

"content": content
},
"at": {

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # Send a message 
def send_link_msg(self, text, title, message_url, pic_url=None):
""" send out link Type text data :param text: The message content :param title: Message title :param message_url: Click on the message to jump to URL :param pic_url: picture URL( Optional parameters ) :return: """
message = {

"msgtype": "link",
"link": {

"text": text, # The message content , If it's too long, it'll only show part of it 
"title": title, # Message title 
"picUrl": pic_url, # picture URL
"messageUrl": message_url # Click on the message to jump to URL
}
}
self.send_req(message) # Send a message 
def send_markdown_msg(self, text, title, at_mobiles=None, is_at_all=False):
""" send out markdown Type text data :param text: markdown Format content :param title: title :param at_mobiles: Incoming list type data ,@ Phone contacts that appear in the list , If there is no such contact in the group , Will not be @( Optional parameters ) :param is_at_all: whether @ All the people , The default is not Aite ( Optional parameters ) :return: """
message = {

"msgtype": "markdown",
"markdown": {

"title": title,
"text": text
},
"at": {

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # Send a message 
def send_all_action_card_msg(self, text, title, single_url, single_title=u' Read the whole passage '):
""" Send overall jump ActionCard Data of type :param text: markdown Format content :param title: title :param single_url: details url Address :param single_title: Click the enter details button :return: """
message = {

"actionCard": {

"title": title,
"text": text,
"singleTitle": single_title,
"singleURL": single_url
},
"msgtype": "actionCard"
}
self.send_req(message) # Send a message 
def send_alone_action_card_msg(self, text, title, btn_orientation=1, btns=None):
""" Send an independent jump ActionCard Data of type :param text: markdown Formatted text data :param title: title :param btn_orientation: 0- Buttons arranged vertically ;1- Buttons are arranged horizontally :param btns: The list of data , Save string inside , Used to put button information and links , as follows [ { "title": " Good content ", "actionURL": "https://www.dingtalk.com/" }, { "title": " Not interested in ", "actionURL": "https://www.dingtalk.com/" } ] :return: """
message = {

"msgtype": "actionCard",
"actionCard": {

"title": title,
"text": text,
"hideAvatar": "0",
"btnOrientation": btn_orientation,
"btns": btns
}
}
self.send_req(message) # Send a message 
def send_feed_card_msg(self, links):
""" send out FeedCard Type data :param links: List the type , The format is as follows [ { "title": " The train of the times is moving forward 1", "messageURL": "https://www.dingtalk.com/", "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" }, { "title": " The train of the times is moving forward 2", "messageURL": "https://www.dingtalk.com/", "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" } ] :return: """
message = {

"msgtype": "feedCard",
"feedCard": {

"links": links
}
}
self.send_req(message) # Send a message 
def send_req(self, message):
""" Send a request :param message: Your message body :return: """
# The requested data is processed json Data encapsulation 
form_data = json.dumps(message)
# Initiate request 
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# Print the returned results 
print(u' Email results :', res_info.json())
print(u' Successful notification !' if (res_info.json())['errmsg'] == 'ok' else u' Inform the failure !')
if __name__ == '__main__':
""" Test sending messages """
DingTalkWarn().send_text_msg(u' Test message sending !')
""" DingTalkWarn().send_link_msg( text=' Love sharing , Love toss , Love life , Willing to share some of my own experiences in the learning process 、 experience .', title='a'ゞ Pistachio blog ', message_url='https://blog.csdn.net/qq_45352972', pic_url='https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png' ) DingTalkWarn().send_markdown_msg( text="## This is a secondary title \n ![news](https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png)\n###### {} Release ".format(time.strftime("%Y-%m-%d %H:%M:%S")), title='markdown Format data ', ) DingTalkWarn().send_all_action_card_msg( text='## Caught tools -mitmproxy Prelude \n ![](https://img-blog.csdnimg.cn/20201211103655824.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70)\n Introduce :mitmproxy Be similar to Fiddler、Charles The function of , Can support HTTP Follow HTTPS request , But it is operated through the console .mitmproxy There are two associated components ,mitmdump Follow mitmweb.mitmdump yes mitmproxy Command line interface for ;mitmweb It's a web Program , You can pass ...', title=' Caught tools -mitmproxy Prelude ', single_url='https://blog.csdn.net/qq_45352972/article/details/111028741?spm=1001.2014.3001.5501' ) DingTalkWarn().send_alone_action_card_msg( text='### Check your friends' blogs \n![](https://profile.csdnimg.cn/C/B/7/1_qq_45352972)', title=' Check your friends' blogs ', btns=[ {"title": " Not interested in ", "actionURL": "https://www.dingtalk.com/" }, { "title": " Let me see ", "actionURL": "https://blog.csdn.net/qq_45352972/" } ] ) DingTalkWarn().send_feed_card_msg( links=[ { "title": " The solution of the crawler needs to log in to the website ", "messageURL": "https://blog.csdn.net/qq_45352972/article/details/113831698?spm=1001.2014.3001.5501", "picURL": "https://img-blog.csdnimg.cn/20210217102838577.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70#pic_center" }, { "title": " The console simply prints and displays the progress bar ", "messageURL": "https://blog.csdn.net/qq_45352972/article/details/112191329?spm=1001.2014.3001.5501", "picURL": "https://img-blog.csdnimg.cn/20210104184651355.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70" }, { "title": "Email Email reminders ", "messageURL": "https://blog.csdn.net/qq_45352972/article/details/109280576?spm=1001.2014.3001.5501", "picURL": "https://img-blog.csdnimg.cn/2020102522530334.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzUyOTcy,size_16,color_FFFFFF,t_70#pic_center" } ] ) """

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved