即时消息通知方案
企业微信群机器人
拉群至少3个人, 但是只要有一个人群也能存在;拉两个人后踢掉,且那两个人也不会察觉
群管理新建一个机器人, 这样你就有了你的专属通知机器人
这个是最方便也是成本最低的方案,
创建完成后会给你一个 webhook_key
, 通过该参数可实现使用该机器人向群中发送消息
def send_webhook(content: str, at_users: str | list = None, at_all: bool = False):
"""
发送企业微信群机器人webhook消息
:param content: 消息内容
:param at_users: 需要@的用户列表(真名全拼, 比如yujing), 一个人可直接传入字符串, 多人请传入一个列表
:param at_all: 是否@所有人
:return: 返回发送结果
"""
content = f"""
项目: {PROJECT["name"]} v{PROJECT["version"]}
时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
设备: {device_id}
{content}
"""
if at_users is None:
at_users = []
if isinstance(at_users, str):
at_users = [at_users]
headers = {
"Content-Type": "application/json",
}
params = {
"key": webhook_key,
}
if at_all:
at_users.append("@all")
# logger.debug(f"艾特 {at_users} 发送消息: {content}")
json_data = {
"msgtype": "text",
"text": {
"content": content,
"mentioned_list": at_users, # @all 表示所有人
},
}
response = requests.post(
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send",
params=params,
headers=headers,
json=json_data,
)
response.raise_for_status()
json_data = response.json()
logger.debug(f"Webhook 发送结果: {json_data}")
if json_data["errcode"] != 0:
raise requests.exceptions.RequestException(f"发送失败: {json_data['errmsg']}")
return json_data
效果如图:
更多配置: 群机器人配置说明 - 文档 - 企业微信开发者中心
Gotify
gotify是一个开源的实时消息推送系统, 需要一个服务器
1panel可以一键安装, 像应用商店装软件一样; 不过由于docker服务器在海外的原因,可能导致镜像拉去失败, 需替换国内镜像源
服务搭建完成后, 进入web界面, 创建APP, 获取app_token
使用 app_token 发送消息/通知
def send_gotify(message: str, priority=5, title: str = "标题"):
"""gotify 发送消息
Args:
message (str): _描述信息_
priority (int, optional): 4个等级: <1 , 1-3, 4-7, >7
title (str, optional): _description_. Defaults to "标题".
Returns:
_type_: _description_
"""
headers = {
"accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {app_token}",
}
content = f"""
项目: {PROJECT["name"]} v{PROJECT["version"]}
时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
设备: {device_id}
内容: {message}
"""
json_data = {
"message": content,
"priority": priority,
"title": title,
}
response = requests.post(
"http://127.0.0.1/message", headers=headers, json=json_data
)
response.raise_for_status()
json_data = response.json()
logger.debug(f"Gotify 发送结果: {json_data}")
return json_data
这样你的通知就可以在网页端查看了
但是还不够方便, 可以下载Gotify Android APP: gotify/android: An app for creating push notifications for new messages posted to gotify/server.
这样就可以在手机上查看通知
还可以根据不同的通知等级, 设置不同的通知方式
其他
钉钉也有机器人, 不过现在公司没有用钉钉,就没使用了
邮箱也可以而且免费,参考: Python SMTP发送邮件 | 菜鸟教程
短信/电话 通知需借助平台购买收费: 短信通知 - 搜索, 短信服务_企业短信营销推广_验证码通知-阿里云, 语音服务_语音通知_语音验证码_云通信_阿里云
Apprise
https://github.com/caronc/apprise
pip install apprise
自行实现代码可能有点多, 更简单的可以使用第三方的库;配合logger, 可以异常时自动通知;
关于国内其他邮箱的问题: 适用于中国的电子邮件服务设置合集,包括但不限于QQ邮箱、163邮箱。 · Issue #496 · caronc/apprise
import apprise
from loguru import logger
# Prepare the object to send Discord notifications.
notifier = apprise.Apprise()
# 企业微信机器人通知
notifier.add(f"wecombot://https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<webhook_key>")
# 使用 sender@163.com 向 receiver1@foxmail.com,receiver2@qq.com 多个地址发送邮件
# 没有 to 参数时,会自己给自己发邮件
notifier.add('mailtos://163.com?smtp=smtp.163.com&mode=ssl&user=sender@163.com&pass=<授权码>&to=receiver1@foxmail.com,receiver2@qq.com')
# # 命令行测试
# apprise -vv -t "测试标题" -b "测试内容" "wecombot://https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<webhook_key>"
# 异常通知
logger.add(notifier.notify, level="ERROR", filter={"apprise": False})
# logger.exception(0/1)
response = notifier.notify("这是一条测试通知")
print(response) # 发送结果