即时消息通知方案

即时消息通知方案

企业微信群机器人

拉群至少3个人, 但是只要有一个人群也能存在;拉两个人后踢掉,且那两个人也不会察觉

群管理新建一个机器人, 这样你就有了你的专属通知机器人

这个是最方便也是成本最低的方案,

image-20250612161313623

创建完成后会给你一个 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

效果如图:

image-20250612161549026

更多配置: 群机器人配置说明 - 文档 - 企业微信开发者中心

Gotify

gotify是一个开源的实时消息推送系统, 需要一个服务器

gotify/server: A simple server for sending and receiving messages in real-time per WebSocket. (Includes a sleek web-ui)

1panel可以一键安装, 像应用商店装软件一样; 不过由于docker服务器在海外的原因,可能导致镜像拉去失败, 需替换国内镜像源

image-20250612162220540

服务搭建完成后, 进入web界面, 创建APP, 获取app_token

image-20250612162608149

使用 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

这样你的通知就可以在网页端查看了

image-20250612162906337

但是还不够方便, 可以下载Gotify Android APP: gotify/android: An app for creating push notifications for new messages posted to gotify/server.

这样就可以在手机上查看通知

image-20250612163101177

还可以根据不同的通知等级, 设置不同的通知方式

image-20250612163146019

更多: 戈蒂ify ·用于发送和接收消息的简单服务器

其他

钉钉也有机器人, 不过现在公司没有用钉钉,就没使用了

邮箱也可以而且免费,参考: 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)  # 发送结果

image-20250623182438062

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦中千秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值