Python基于釘釘監(jiān)控發(fā)送消息提醒的實現(xiàn)
一.使用前設置釘釘
1.既然是使用釘釘消息提醒,那么第需要有釘釘。
2.第二步自定義機器人是群機器人,所以需要有個群。

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

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

二.安全設置
1.有三種安全設置方式:自定義關鍵詞、加簽、IP地址。
2.自定義關鍵詞:簡單來說就是你發(fā)送的內(nèi)容必須包含這個關鍵詞,才能發(fā)送成功。
3.加簽:就是生成你特定的簽名,在程序中,進行加密生成參數(shù),請求時,攜帶此參數(shù),才能發(fā)送成功。
4.IP地址:就是在設置的指定IP地址范圍內(nèi)進行請求,才能發(fā)送成功。
5.選擇適合自己的安全設置方式,這里選擇的是加簽,即配置好后,代碼在使用、復用、遷移等方面會稍加靈活一點,如果在公司,按實際需求選擇就行。把這個簽名記錄下來,待會需要它來加密生成參數(shù)。
6.點擊完成之后,就可以看到自己的Webhook,記下來,待會需要用到。

三.發(fā)送請求
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 = "{}×tamp={}&sign={}".format(webhook, timestamp, sign) # 如果你的不是加簽的安全方式,即可省去 ×tamp={}&sign={} 部分參數(shù)
# 配置請求headers
self.headers = {
"Content-Type": "application/json",
"Charset": "UTF-8" # 發(fā)起POST請求時,必須將字符集編碼設置成UTF-8。
}
2.其次,發(fā)送請求
def send_req(self, message):
"""
發(fā)送請求
:param message: 你的消息體
:return:
"""
# 將請求數(shù)據(jù)進行json數(shù)據(jù)封裝
form_data = json.dumps(message)
# 發(fā)起請求
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# 打印返回的結(jié)果
print('郵件發(fā)送結(jié)果:', res_info.json())
print('通知成功!' if (res_info.json())['errmsg'] == 'ok' else '通知失??!')
3.再次,構(gòu)造消息體,釘釘給出6種消息類型體
3.1.第一種、text型文本數(shù)據(jù)
def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
"""
發(fā)送text型文本數(shù)據(jù)
:param content: 消息內(nèi)容
:param at_mobiles: 傳入列表類型數(shù)據(jù),@出現(xiàn)在列表中的電話聯(lián)系人,如果群里沒有該聯(lián)系人,則不會@(可選參數(shù))
:param is_at_all: 是否@所有人,默認不艾特(可選參數(shù))
:return:
"""
message = {
"msgtype": "text", # 消息類型
"text": {
"content": content
},
"at": {
"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發(fā)送消息
a.調(diào)用
DingTalkWarn().send_text_msg('測試消息發(fā)送!')
b.效果圖

3.2.第二種、link型文本數(shù)據(jù)
def send_link_msg(self, text, title, message_url, pic_url=None):
"""
發(fā)送link型文本數(shù)據(jù)
:param text: 消息內(nèi)容
:param title: 消息標題
:param message_url: 點擊消息跳轉(zhuǎn)的URL
:param pic_url: 圖片URL(可選參數(shù))
:return:
"""
message = {
"msgtype": "link",
"link": {
"text": text, # 消息內(nèi)容,如果太長只會部分展示
"title": title, # 消息標題
"picUrl": pic_url, # 圖片URL
"messageUrl": message_url # 點擊消息跳轉(zhuǎn)的URL
}
}
self.send_req(message) # 發(fā)送消息
a.調(diào)用
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型文本數(shù)據(jù)
def send_markdown_msg(self, text, title, at_mobiles=None, is_at_all=False):
"""
發(fā)送markdown型文本數(shù)據(jù)
:param text: markdown格式內(nèi)容
:param title: 標題
:param at_mobiles: 傳入列表類型數(shù)據(jù),@出現(xiàn)在列表中的電話聯(lián)系人,如果群里沒有該聯(lián)系人,則不會@(可選參數(shù))
:param is_at_all: 是否@所有人,默認不艾特(可選參數(shù))
:return:
"""
message = {
"msgtype": "markdown",
"markdown": {
"title": title,
"text": text
},
"at": {
"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發(fā)送消息
a.調(diào)用
DingTalkWarn().send_markdown_msg(
text="## 這是一個二級標題\n \n###### {}發(fā)布".format(time.strftime("%Y-%m-%d %H:%M:%S")),
title='markdown格式數(shù)據(jù)',
)
b.效果圖

3.4.第四種、整體跳轉(zhuǎn)ActionCard類型的數(shù)據(jù)
def send_all_action_card_msg(self, text, title, single_url, single_title='閱讀全文'):
"""
發(fā)送整體跳轉(zhuǎn)ActionCard類型的數(shù)據(jù)
:param text: markdown格式內(nèi)容
: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) # 發(fā)送消息
a.調(diào)用
DingTalkWarn().send_all_action_card_msg(
text='## 抓包工具-mitmproxy前奏\n \n介紹:mitmproxy類似于Fiddler、Charles的功能,可以支持HTTP跟HTTPS請求,只不過它是通過控制臺的形式進行操作。mitmproxy有兩個關聯(lián)的組件,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.第五種、獨立跳轉(zhuǎn)ActionCard類型的數(shù)據(jù)
def send_alone_action_card_msg(self, text, title, btn_orientation=1, btns=None):
"""
發(fā)送獨立跳轉(zhuǎn)ActionCard類型的數(shù)據(jù)
:param text: markdown格式文本數(shù)據(jù)
:param title: 標題
:param btn_orientation: 0-按鈕豎直排列;1-按鈕橫向排列
:param btns: 列表數(shù)據(jù),里面存字符串,用來放按鈕信息跟鏈接,如下
[
{
"title": "內(nèi)容不錯",
"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) # 發(fā)送消息
a.調(diào)用
DingTalkWarn().send_alone_action_card_msg(
text='### 查看好友博客\n',
title='查看好友博客',
btns=[
{
"title": "不感興趣",
"actionURL": "https://www.dingtalk.com/"
},
{
"title": "我看看",
"actionURL": "https://blog.csdn.net/qq_45352972/"
}
]
)
b.效果圖

3.6.第六種、FeedCard類型數(shù)據(jù)
def send_feed_card_msg(self, links):
"""
發(fā)送FeedCard類型數(shù)據(jù)
: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) # 發(fā)送消息
a.調(diào)用
DingTalkWarn().send_feed_card_msg(
links=[
{
"title": "爬蟲之解決需要登錄的網(wǎng)站",
"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": "控制臺簡單實現(xiàn)打印顯示進度條",
"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'
# 如果你的不是加簽的安全方式,即可省去 ×tamp={}&sign={} 部分參數(shù)
self.webhook = "{}×tamp={}&sign={}".format(webhook, timestamp, sign)
# 配置請求headers
self.headers = {
"Content-Type": "application/json",
"Charset": "UTF-8" # 發(fā)起POST請求時,必須將字符集編碼設置成UTF-8。
}
def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
"""
發(fā)送text型文本數(shù)據(jù)
:param content: 消息內(nèi)容
:param at_mobiles: 傳入列表類型數(shù)據(jù),@出現(xiàn)在列表中的電話聯(lián)系人,如果群里沒有該聯(lián)系人,則不會@(可選參數(shù))
:param is_at_all: 是否@所有人,默認不艾特(可選參數(shù))
:return:
"""
message = {
"msgtype": "text", # 消息類型
"text": {
"content": content
},
"at": {
"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發(fā)送消息
def send_link_msg(self, text, title, message_url, pic_url=None):
"""
發(fā)送link型文本數(shù)據(jù)
:param text: 消息內(nèi)容
:param title: 消息標題
:param message_url: 點擊消息跳轉(zhuǎn)的URL
:param pic_url: 圖片URL(可選參數(shù))
:return:
"""
message = {
"msgtype": "link",
"link": {
"text": text, # 消息內(nèi)容,如果太長只會部分展示
"title": title, # 消息標題
"picUrl": pic_url, # 圖片URL
"messageUrl": message_url # 點擊消息跳轉(zhuǎn)的URL
}
}
self.send_req(message) # 發(fā)送消息
def send_markdown_msg(self, text, title, at_mobiles=None, is_at_all=False):
"""
發(fā)送markdown型文本數(shù)據(jù)
:param text: markdown格式內(nèi)容
:param title: 標題
:param at_mobiles: 傳入列表類型數(shù)據(jù),@出現(xiàn)在列表中的電話聯(lián)系人,如果群里沒有該聯(lián)系人,則不會@(可選參數(shù))
:param is_at_all: 是否@所有人,默認不艾特(可選參數(shù))
:return:
"""
message = {
"msgtype": "markdown",
"markdown": {
"title": title,
"text": text
},
"at": {
"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 發(fā)送消息
def send_all_action_card_msg(self, text, title, single_url, single_title=u'閱讀全文'):
"""
發(fā)送整體跳轉(zhuǎn)ActionCard類型的數(shù)據(jù)
:param text: markdown格式內(nèi)容
: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) # 發(fā)送消息
def send_alone_action_card_msg(self, text, title, btn_orientation=1, btns=None):
"""
發(fā)送獨立跳轉(zhuǎn)ActionCard類型的數(shù)據(jù)
:param text: markdown格式文本數(shù)據(jù)
:param title: 標題
:param btn_orientation: 0-按鈕豎直排列;1-按鈕橫向排列
:param btns: 列表數(shù)據(jù),里面存字符串,用來放按鈕信息跟鏈接,如下
[
{
"title": "內(nèi)容不錯",
"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) # 發(fā)送消息
def send_feed_card_msg(self, links):
"""
發(fā)送FeedCard類型數(shù)據(jù)
: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) # 發(fā)送消息
def send_req(self, message):
"""
發(fā)送請求
:param message: 你的消息體
:return:
"""
# 將請求數(shù)據(jù)進行json數(shù)據(jù)封裝
form_data = json.dumps(message)
# 發(fā)起請求
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# 打印返回的結(jié)果
print(u'郵件發(fā)送結(jié)果:', res_info.json())
print(u'通知成功!' if (res_info.json())['errmsg'] == 'ok' else u'通知失敗!')
if __name__ == '__main__':
"""測試發(fā)送消息"""
DingTalkWarn().send_text_msg(u'測試消息發(fā)送!')
"""
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 \n###### {}發(fā)布".format(time.strftime("%Y-%m-%d %H:%M:%S")),
title='markdown格式數(shù)據(jù)',
)
DingTalkWarn().send_all_action_card_msg(
text='## 抓包工具-mitmproxy前奏\n \n介紹:mitmproxy類似于Fiddler、Charles的功能,可以支持HTTP跟HTTPS請求,只不過它是通過控制臺的形式進行操作。mitmproxy有兩個關聯(lián)的組件,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',
title='查看好友博客',
btns=[
{"title": "不感興趣",
"actionURL": "https://www.dingtalk.com/"
},
{
"title": "我看看",
"actionURL": "https://blog.csdn.net/qq_45352972/"
}
]
)
DingTalkWarn().send_feed_card_msg(
links=[
{
"title": "爬蟲之解決需要登錄的網(wǎng)站",
"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": "控制臺簡單實現(xiàn)打印顯示進度條",
"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"
}
]
)
"""
到此這篇關于Python基于釘釘監(jiān)控發(fā)送消息提醒的實現(xiàn)的文章就介紹到這了,更多相關Python 釘釘監(jiān)控發(fā)送消息提醒內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
淺談keras中的目標函數(shù)和優(yōu)化函數(shù)MSE用法
這篇文章主要介紹了淺談keras中的目標函數(shù)和優(yōu)化函數(shù)MSE用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python自動計算圖像數(shù)據(jù)集的RGB均值
這篇文章主要為大家詳細介紹了python自動計算圖像數(shù)據(jù)集的RGB均值,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06
Python 使用ConfigParser操作ini配置文件
這篇文章主要介紹了Python 使用ConfigParser操作ini配置文件的相關資料,需要的朋友可以參考下2023-05-05
python如何實現(xiàn)讀取并顯示圖片(不需要圖形界面)
這篇文章主要介紹了python如何實現(xiàn)讀取并顯示圖片,文中示例代碼非常詳細,幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07
python把數(shù)據(jù)框?qū)懭隡ySQL的方法
這篇文章主要介紹了如何讓python把數(shù)據(jù)框?qū)懭隡ySQL,下文利用上海市2016年9月1日公共交通卡刷卡數(shù)據(jù)的一份數(shù)據(jù)單展開其方法,需要的小伙伴可以參考一下2022-03-03
使用Tensorflow實現(xiàn)可視化中間層和卷積層
今天小編就為大家分享一篇使用Tensorflow實現(xiàn)可視化中間層和卷積層,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

