"""
1、设置钉钉群消息助手
2、钉钉群消息提醒Webhook :https://oapi.dingtalk.com/robot/send?access_token=
3、钉钉接口文档:https://developers.dingtalk.com/document/app/document-upgrade-notice
第一种方式:自定义关键词,发送:最多可以设置10个关键词,消息中至少包含其中1个关键词才可以发送成功
第二种方式:加签、发送:
(1)把timestamp+"\n"+密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。
第三种方式:IP段发送
"""
import urllib, time, hashlib, base64, hmac, requests
from urllib.parse import quote, unquote
def createDingSign():
secret = 'xxxx'
timestamp = int(time.time() * 1000)
signBefore = ('%s\n%s' % (timestamp, secret)).encode('utf-8')
hsha256 = hmac.new(secret.encode('utf-8'), signBefore, hashlib.sha256)
signSha256 = hsha256.digest()
base = base64.b64encode(signSha256)
sign = quote(base)
return {"timestamp": timestamp, "sign": sign}
def sendMessageDing(msg='大家好,我是钉钉群助手机器人'):
url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxx'
json = {
"msgtype": "text",
"text": {
"content": msg,
},
"at": {
"atMobiles": [
""
],
"isAtAll": False
}
}
sign = createDingSign()
r = requests.post(url=url, params=sign, json=json)
print(r.json())
if __name__ == "__main__":
createDingSign()
"""
1、设置飞书群消息助手
2、飞书群消息提醒Webhook:
https://open.feishu.cn/open-apis/bot/v2/hook/
3、安全设置:
(1)、关键字
(2)、加签:
签名的算法:把 timestamp + "\n" + 密钥 当做签名字符串,使用 HmacSHA256 算法计算签名,再进行 Base64 编码。
(3)、IP白名单
"""
import time, hmac, base64, requests, hashlib
from hashlib import sha256
def createFeiSign():
secret = 'xxx'
timestamp = int(time.time())
secretBefore = ('%s\n%s' % (timestamp, secret)).encode('utf-8')
msg = ""
msgEncode = msg.encode('utf-8')
hsha256 = hmac.new(secretBefore, msgEncode, digestmod=hashlib.sha256).digest()
sign = base64.b64encode(hsha256).decode()
return {"timestamp": timestamp, "sign": sign}
def sendMessageFei(text='大家好,我是飞书群助手机器人'):
url = 'https://open.feishu.cn/open-apis/bot/v2/hook/xx'
json = {
"timestamp": createFeiSign().get('timestamp'),
"sign": createFeiSign().get('sign'),
"msg_type": "text",
"content": {
"text": text
}
}
r = requests.post(url=url, json=json)
print(r.json())
if __name__ == "__main__":
sendMessageFei()
import os, sys, platform
ini = """[global]
index-url = https://pypi.doubanio.com/simple/
[install]
trusted-host=pypi.doubanio.com
"""
os_version = platform.platform()
if 'Windows' in os_version:
os_flag = False
file_name = 'pip.ini'
else:
os_flag = True
file_name = 'pip.conf'
if os_flag == True:
pippath = os.environ["HOME"] + os.sep + ".pip" + os.sep
else:
pippath = os.environ["USERPROFILE"] + os.sep + "pip" + os.sep
if not os.path.exists(pippath):
os.mkdir(pippath)
with open(pippath + file_name, "w") as f:
f.write(ini)
"""
企业微信
-*- coding: utf-8 -*-
@Author : ray
@Software: PyCharm
@Time : 2022/11/9 19:24
@File : webchat_webhook.py.py
"""
import requests
class WechatWebHook:
"""企业微信消息推送"""
@classmethod
def push_error_msg(cls, msg: str) -> None:
webhook_uri = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=00000000-0000-0000-0000-0000000"
"""错误日志直接推送至企业微信"""
data = {
"msgtype": "text",
"text": {
"content": msg,
"mentioned_mobile_list": ["18800110011"]
}
}
requests.post(url=webhook_uri, headers={"Content-Type": "text/plain"}, json=data)
if __name__ == '__main__':
WechatWebHook.push_error_msg("武汉市洪山区,当前气温18摄氏度,未来2小时不会下雨,出门佩戴口罩,保障您和家人的健康。")
"""
-*- coding: utf-8 -*-
@Author : ray
@Software: PyCharm
@Time : 2022/11/9 19:23
@File : logger.py.py
"""
from loguru._logger import Core as _Core
from loguru._logger import Logger as _Logger
from loguru import _defaults
import sys as _sys
from webchat_webhook import WechatWebHook
class CustomizedLogger(_Logger):
"""重写logger类中的error方法,打印error log时企业微信同步推送错误日志"""
def __init__(self, core, exception, depth, record, lazy, colors, raw, capture, patcher, extra):
super().__init__(core, exception, depth, record, lazy, colors, raw, capture, patcher, extra)
def error(self, __message, *args, **kwargs):
r"""Log ``message.format(*args, **kwargs)`` with severity ``'ERROR'``."""
WechatWebHook.push_error_msg(__message)
self._log("ERROR", None, False, self._options, __message, args, kwargs)
logger = CustomizedLogger(_Core(), None, 0, False, False, False, False, True, None, {})
if _defaults.LOGURU_AUTOINIT and _sys.stderr:
logger.add(_sys.stderr)
if __name__ == '__main__':
logger.error('测试webhook机器人发送消息')