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

第一:Python基於釘釘監控發送消息提醒

編輯:Python

一.使用前設置釘釘

1.既然是使用釘釘消息提醒,那麼第需要有釘釘。

2.第二步自定義機器人是群機器人,所以需要有個群。

3.添加機器人,點擊頭像>機器人管理>自定義機器人

4.給機器人取個名字>選擇添加到哪個群組>選擇適合自己的安全設置>完成

二.安全設置

1.有三種安全設置方式:自定義關鍵詞、加簽、IP地址。

2.自定義關鍵詞:簡單來說就是你發送的內容必須包含這個關鍵詞,才能發送成功。

3.加簽:就是生成你特定的簽名,在程序中,進行加密生成參數,請求時,攜帶此參數,才能發送成功。

4.IP地址:就是在設置的指定IP地址范圍內進行請求,才能發送成功。

5.選擇適合自己的安全設置方式,這裡選擇的是加簽,即配置好後,代碼在使用、復用、遷移等方面會稍加靈活一點,如果在公司,按實際需求選擇就行。把這個簽名記錄下來,待會需要它來加密生成參數。

6.點擊完成之後,就可以看到自己的Webhook,記下來,待會需要用到。

三.發送請求

1.首先,在__init__方法中,配置好機器人的信息。

def __init__(self):
# 安全設置使用加簽方式
timestamp = str(round(time.time() * 1000))
secret = 'SEC7******fe0a' # 剛才記錄下來的簽名
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))
# 以上就是加簽的安全配置,其它安全設置,無需配置以上信息
# webhook地址
webhook = 'https://oapi.dingtalk.com/robot/send?******' # 剛才記錄的webhook
self.webhook = "{}&timestamp={}&sign={}".format(webhook, timestamp, sign) # 如果你的不是加簽的安全方式,即可省去 &timestamp={}&sign={} 部分參數
# 配置請求headers
self.headers = {

"Content-Type": "application/json",
"Charset": "UTF-8" # 發起POST請求時,必須將字符集編碼設置成UTF-8。
}

2.其次,發送請求

def send_req(self, message):
""" 發送請求 :param message: 你的消息體 :return: """
# 將請求數據進行json數據封裝
form_data = json.dumps(message)
# 發起請求
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# 打印返回的結果
print('郵件發送結果:', res_info.json())
print('通知成功!' if (res_info.json())['errmsg'] == 'ok' else '通知失敗!')

3.再次,構造消息體,釘釘給出6種消息類型體

3.1.第一種、text型文本數據

def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
""" 發送text型文本數據 :param content: 消息內容 :param at_mobiles: 傳入列表類型數據,@出現在列表中的電話聯系人,如果群裡沒有該聯系人,則不會@(可選參數) :param is_at_all: 是否@所有人,默認不艾特(可選參數) :return: """
message = {

"msgtype": "text", # 消息類型
"text": {

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

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發送消息

a.調用

DingTalkWarn().send_text_msg('測試消息發送!')

b.效果圖

3.2.第二種、link型文本數據

def send_link_msg(self, text, title, message_url, pic_url=None):
""" 發送link型文本數據 :param text: 消息內容 :param title: 消息標題 :param message_url: 點擊消息跳轉的URL :param pic_url: 圖片URL(可選參數) :return: """
message = {

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

"text": text, # 消息內容,如果太長只會部分展示
"title": title, # 消息標題
"picUrl": pic_url, # 圖片URL
"messageUrl": message_url # 點擊消息跳轉的URL
}
}
self.send_req(message) # 發送消息

a.調用

DingTalkWarn().send_link_msg(
text='愛分享,愛折騰,愛生活,樂於分享自己在學習過程中的一些心得、體會。',
title='a'ゞ開心果的博客',
message_url='https://blog.csdn.net/qq_45352972',
pic_url='https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png'
)

b.效果圖

3.3.第三種、markdown型文本數據

def send_markdown_msg(self, text, title, at_mobiles=None, is_at_all=False):
""" 發送markdown型文本數據 :param text: markdown格式內容 :param title: 標題 :param at_mobiles: 傳入列表類型數據,@出現在列表中的電話聯系人,如果群裡沒有該聯系人,則不會@(可選參數) :param is_at_all: 是否@所有人,默認不艾特(可選參數) :return: """
message = {

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

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

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發送消息

a.調用

DingTalkWarn().send_markdown_msg(
text="## 這是一個二級標題\n ![news](https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png)\n###### {}發布".format(time.strftime("%Y-%m-%d %H:%M:%S")),
title='markdown格式數據',
)

b.效果圖

3.4.第四種、整體跳轉ActionCard類型的數據

def send_all_action_card_msg(self, text, title, single_url, single_title='閱讀全文'):
""" 發送整體跳轉ActionCard類型的數據 :param text: markdown格式內容 :param title: 標題 :param single_url: 詳情url地址 :param single_title: 點擊進入詳情按鈕 :return: """
message = {

"actionCard": {

"title": title,
"text": text,
"singleTitle": single_title,
"singleURL": single_url
},
"msgtype": "actionCard"
}
self.send_req(message) # 發送消息

a.調用

DingTalkWarn().send_all_action_card_msg(
text='## 抓包工具-mitmproxy前奏\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介紹:mitmproxy類似於Fiddler、Charles的功能,可以支持HTTP跟HTTPS請求,只不過它是通過控制台的形式進行操作。mitmproxy有兩個關聯的組件,mitmdump跟mitmweb。mitmdump是mitmproxy的命令行接口;mitmweb是一個web程序,可以通...',
title='抓包工具-mitmproxy前奏',
single_url='https://blog.csdn.net/qq_45352972/article/details/111028741?spm=1001.2014.3001.5501'
)

b.效果圖

3.5.第五種、獨立跳轉ActionCard類型的數據

def send_alone_action_card_msg(self, text, title, btn_orientation=1, btns=None):
""" 發送獨立跳轉ActionCard類型的數據 :param text: markdown格式文本數據 :param title: 標題 :param btn_orientation: 0-按鈕豎直排列;1-按鈕橫向排列 :param btns: 列表數據,裡面存字符串,用來放按鈕信息跟鏈接,如下 [ { "title": "內容不錯", "actionURL": "https://www.dingtalk.com/" }, { "title": "不感興趣", "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) # 發送消息

a.調用

DingTalkWarn().send_alone_action_card_msg(
text='### 查看好友博客\n![](https://profile.csdnimg.cn/C/B/7/1_qq_45352972)',
title='查看好友博客',
btns=[
{

"title": "不感興趣",
"actionURL": "https://www.dingtalk.com/"
},
{

"title": "我看看",
"actionURL": "https://blog.csdn.net/qq_45352972/"
}
]
)

b.效果圖

3.6.第六種、FeedCard類型數據

def send_feed_card_msg(self, links):
""" 發送FeedCard類型數據 :param links: 列表類型,格式如下 [ { "title": "時代的火車向前開1", "messageURL": "https://www.dingtalk.com/", "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" }, { "title": "時代的火車向前開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) # 發送消息

a.調用

DingTalkWarn().send_feed_card_msg(
links=[
{

"title": "爬蟲之解決需要登錄的網站",
"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": "控制台簡單實現打印顯示進度條",
"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郵件提醒",
"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.效果圖

四.完整代碼

import base64
import hashlib
import hmac
import time
import urllib.parse
import requests
import json
class DingTalkWarn:
"""釘釘消息通知"""
def __init__(self):
# 安全設置使用加簽方式
timestamp = str(round(time.time() * 1000))
# 剛才記錄下來的簽名
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))
# 以上就是加簽的安全配置,其它安全設置,無需配置以上信息
# webhook地址(剛才記錄的webhook)
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=5f56131ba70c78f42a10c7e9531c8da55def990313a4a74cfc87bf82c4bb8b7b'
# 如果你的不是加簽的安全方式,即可省去 &timestamp={}&sign={} 部分參數
self.webhook = "{}&timestamp={}&sign={}".format(webhook, timestamp, sign)
# 配置請求headers
self.headers = {

"Content-Type": "application/json",
"Charset": "UTF-8" # 發起POST請求時,必須將字符集編碼設置成UTF-8。
}
def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
""" 發送text型文本數據 :param content: 消息內容 :param at_mobiles: 傳入列表類型數據,@出現在列表中的電話聯系人,如果群裡沒有該聯系人,則不會@(可選參數) :param is_at_all: 是否@所有人,默認不艾特(可選參數) :return: """
message = {

"msgtype": "text", # 消息類型
"text": {

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

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發送消息
def send_link_msg(self, text, title, message_url, pic_url=None):
""" 發送link型文本數據 :param text: 消息內容 :param title: 消息標題 :param message_url: 點擊消息跳轉的URL :param pic_url: 圖片URL(可選參數) :return: """
message = {

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

"text": text, # 消息內容,如果太長只會部分展示
"title": title, # 消息標題
"picUrl": pic_url, # 圖片URL
"messageUrl": message_url # 點擊消息跳轉的URL
}
}
self.send_req(message) # 發送消息
def send_markdown_msg(self, text, title, at_mobiles=None, is_at_all=False):
""" 發送markdown型文本數據 :param text: markdown格式內容 :param title: 標題 :param at_mobiles: 傳入列表類型數據,@出現在列表中的電話聯系人,如果群裡沒有該聯系人,則不會@(可選參數) :param is_at_all: 是否@所有人,默認不艾特(可選參數) :return: """
message = {

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

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

"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發送消息
def send_all_action_card_msg(self, text, title, single_url, single_title=u'閱讀全文'):
""" 發送整體跳轉ActionCard類型的數據 :param text: markdown格式內容 :param title: 標題 :param single_url: 詳情url地址 :param single_title: 點擊進入詳情按鈕 :return: """
message = {

"actionCard": {

"title": title,
"text": text,
"singleTitle": single_title,
"singleURL": single_url
},
"msgtype": "actionCard"
}
self.send_req(message) # 發送消息
def send_alone_action_card_msg(self, text, title, btn_orientation=1, btns=None):
""" 發送獨立跳轉ActionCard類型的數據 :param text: markdown格式文本數據 :param title: 標題 :param btn_orientation: 0-按鈕豎直排列;1-按鈕橫向排列 :param btns: 列表數據,裡面存字符串,用來放按鈕信息跟鏈接,如下 [ { "title": "內容不錯", "actionURL": "https://www.dingtalk.com/" }, { "title": "不感興趣", "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) # 發送消息
def send_feed_card_msg(self, links):
""" 發送FeedCard類型數據 :param links: 列表類型,格式如下 [ { "title": "時代的火車向前開1", "messageURL": "https://www.dingtalk.com/", "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" }, { "title": "時代的火車向前開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) # 發送消息
def send_req(self, message):
""" 發送請求 :param message: 你的消息體 :return: """
# 將請求數據進行json數據封裝
form_data = json.dumps(message)
# 發起請求
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# 打印返回的結果
print(u'郵件發送結果:', res_info.json())
print(u'通知成功!' if (res_info.json())['errmsg'] == 'ok' else u'通知失敗!')
if __name__ == '__main__':
"""測試發送消息"""
DingTalkWarn().send_text_msg(u'測試消息發送!')
""" DingTalkWarn().send_link_msg( text='愛分享,愛折騰,愛生活,樂於分享自己在學習過程中的一些心得、體會。', title='a'ゞ開心果的博客', 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="## 這是一個二級標題\n ![news](https://cdn.jsdelivr.net/gh/King-ing/CDN/assets/background.png)\n###### {}發布".format(time.strftime("%Y-%m-%d %H:%M:%S")), title='markdown格式數據', ) DingTalkWarn().send_all_action_card_msg( text='## 抓包工具-mitmproxy前奏\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介紹:mitmproxy類似於Fiddler、Charles的功能,可以支持HTTP跟HTTPS請求,只不過它是通過控制台的形式進行操作。mitmproxy有兩個關聯的組件,mitmdump跟mitmweb。mitmdump是mitmproxy的命令行接口;mitmweb是一個web程序,可以通...', title='抓包工具-mitmproxy前奏', single_url='https://blog.csdn.net/qq_45352972/article/details/111028741?spm=1001.2014.3001.5501' ) DingTalkWarn().send_alone_action_card_msg( text='### 查看好友博客\n![](https://profile.csdnimg.cn/C/B/7/1_qq_45352972)', title='查看好友博客', btns=[ {"title": "不感興趣", "actionURL": "https://www.dingtalk.com/" }, { "title": "我看看", "actionURL": "https://blog.csdn.net/qq_45352972/" } ] ) DingTalkWarn().send_feed_card_msg( links=[ { "title": "爬蟲之解決需要登錄的網站", "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": "控制台簡單實現打印顯示進度條", "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郵件提醒", "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