百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

ubuntu每五分钟执行企业微信机器人推送

nanshan 2025-05-21 15:22 16 浏览 0 评论

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 22 09:05:46 2025

@author: 1
"""

import requests
import time
import schedule
import sched
from datetime import datetime, timedelta
import threading
import pymysql  # 用于连接MySQL数据库
from mysql.connector import Error

# 信息等级定义
INFO_LEVELS = {
    '紧急': {'retry_interval': 60, 'max_retries': 3},
    '重要': {'retry_interval': 60, 'max_retries': 3},
    '一般': {'retry_interval': 60, 'max_retries': 3}
}

def send_message(group, message, info_level):
    headers = {'Content-Type': 'application/json'}
    payload = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    try:
        print(13)
        print(group)
        response = requests.post(group['robot_webhook'], json=payload, headers=headers)
        print(14)
        if response.status_code == 200 and response.json().get('errcode') == 0:
            print(15)
            print(f"[{datetime.now()}] 成功发送到群 {group['group_name']}")
            return True
        else:
            print(16)
            print(f"[{datetime.now()}] 发送到群 {group['group_name']} 失败,状态码: {response.status_code}")
            return False
    except Exception as e:
        print(17)
        print(f"[{datetime.now()}] 发送到群 {group['group_name']} 异常: {e}")
        return False

def retry_send(group, message, info_level, attempt=1):
    max_retries = INFO_LEVELS[info_level]['max_retries']
    retry_interval = INFO_LEVELS[info_level]['retry_interval']
    print(6)
    if attempt > max_retries:
        print(f"[{datetime.now()}] 最终发送失败到群 {group['group_name']},将在1小时后重试")
        time.sleep(3600)  # 等待1小时后重试
        attempt = 1
    print(7)
    success = send_message(group, message, info_level)
    print(8)
    if not success:
        time.sleep(retry_interval)
        retry_send(group, message, info_level, attempt + 1)

def send_to_superior_groups(group, message, info_level):
    current_group = group
    while current_group['parent_group_id'] is not None:
        superior = find_group_by_id(current_group['parent_group_id'])
        if superior:
            retry_send(superior, message, info_level)
            current_group = superior
        else:
            break

def find_group_by_id(group_id):
    try:
        # 连接数据库
        connection = pymysql.connect(**DB_CONFIG)
        with connection.cursor() as cursor:
            # 查询未发送的紧急消息
            sql = "select id,group_name,level,robot_webhook,parent_group_id from wechat_groups where id = %s"
            cursor.execute(sql, (group_id,))
            results = cursor.fetchall()
            
            for row in results:
                target_group = row['id']  # 根据 upno 找到对应的群组
                if target_group == group_id:
                    return row
            return None
    except Exception as e:
        print(f"[{datetime.now()}] 遍历机器人时出错: {e}")
        return None
    finally:
        if connection:
            connection.close()
            
def find_group_by_name(group_name):
    try:
        # 连接数据库
        connection = pymysql.connect(**DB_CONFIG)
        with connection.cursor() as cursor:
            # 查询未发送的紧急消息
            sql = "select id,group_name,level,robot_webhook,parent_group_id from wechat_groups where group_name = %s"
            cursor.execute(sql, (group_name,))
            results = cursor.fetchall()
            
            for row in results:
                target_group = row['group_name']  # 根据 upno 找到对应的群组
                if target_group == group_name:
                    return row
            return None
    except Exception as e:
        print(f"[{datetime.now()}] 遍历机器人时出错: {e}")
        return None
    finally:
        if connection:
            connection.close()

def schedule_message(group, message, info_level, send_time):
    print(9)
    delay = (send_time - datetime.now()).total_seconds()
    print(10)
    if delay > 0:
        print(11)
        scheduler = sched.scheduler(time.time, time.sleep)
        scheduler.enterabs(send_time.timestamp(), 1, retry_send, argument=(group, message, info_level))
        scheduler.run()
    else:
        print(12)
        retry_send(group, message, info_level)

def send_message_with_scheduling(group, message, info_level, send_time=None):
    if send_time:
        schedule_message(group, message, info_level, send_time)
    else:
        retry_send(group, message, info_level)
    if group['parent_group_id'] is not None:
        send_to_superior_groups(group, message, info_level)

def run_scheduler():
    while True:
        schedule.run_pending()
        time.sleep(1)

# 数据库连接配置
DB_CONFIG = {
    'host': '*********',
    'user': 'root',
    'password': '************',
    'database': '*************',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

def check_and_send_urgent_messages():
    try:
        # 连接数据库
        connection = pymysql.connect(**DB_CONFIG)
        with connection.cursor() as cursor:
            # 查询未发送的紧急消息
            sql = "SELECT id, sqlcmd, result, createdate, role, details, levelname, upno FROM ai_dayairesult WHERE levelname = '紧急' AND isend = 0"
            cursor.execute(sql)
            results = cursor.fetchall()
            print(1)
            
            for row in results:
                message = f"紧急通知: {row['result']}"  # 只发送result字段内容
                target_group = find_group_by_name(row['role'])  # 根据role字段找到对应的群组
                print(2)
                if target_group:
                    print(3)
                    print(target_group)
                    print(31)
                    send_message_with_scheduling(target_group, message, "紧急")
                    print(4)
                    # 更新数据库状态为已发送
                    update_sql = "UPDATE ai_dayairesult SET isend = 1 WHERE id = %s"
                    cursor.execute(update_sql, (row['id'],))
                    print(5)
            # 提交事务
            connection.commit()
    except Exception as e:
        print(f"[{datetime.now()}] 检查并发送紧急消息时出错: {e}")
    finally:
        if connection:
            connection.close()

def schedule_next_check():
    # 设置每5分钟检查一次紧急消息
    schedule.every(5).minutes.do(check_and_send_urgent_messages)

# 示例用法
if __name__ == "__main__":
    # 启动调度器线程
    scheduler_thread = threading.Thread(target=run_scheduler)
    scheduler_thread.daemon = True
    scheduler_thread.start()
    
    # 设置定时检查紧急消息
    schedule_next_check()
    
    # 立即执行一次检查
    check_and_send_urgent_messages()
    
    # 保持主线程运行
    while True:
        schedule.run_pending()
        time.sleep(1)

相关推荐

0722-6.2.0-如何在RedHat7.2使用rpm安装CDH(无CM)

文档编写目的在前面的文档中,介绍了在有CM和无CM两种情况下使用rpm方式安装CDH5.10.0,本文档将介绍如何在无CM的情况下使用rpm方式安装CDH6.2.0,与之前安装C5进行对比。环境介绍:...

ARM64 平台基于 openEuler + iSula 环境部署 Kubernetes

为什么要在arm64平台上部署Kubernetes,而且还是鲲鹏920的架构。说来话长。。。此处省略5000字。介绍下系统信息;o架构:鲲鹏920(Kunpeng920)oOS:ope...

生产环境starrocks 3.1存算一体集群部署

集群规划FE:节点主要负责元数据管理、客户端连接管理、查询计划和查询调度。>3节点。BE:节点负责数据存储和SQL执行。>3节点。CN:无存储功能能的BE。环境准备CPU检查JDK...

在CentOS上添加swap虚拟内存并设置优先级

现如今很多云服务器都会自己配置好虚拟内存,当然也有很多没有配置虚拟内存的,虚拟内存可以让我们的低配服务器使用更多的内存,可以减少很多硬件成本,比如我们运行很多服务的时候,内存常常会满,当配置了虚拟内存...

国产深度(deepin)操作系统优化指南

1.升级内核随着deepin版本的更新,会自动升级系统内核,但是我们依旧可以通过命令行手动升级内核,以获取更好的性能和更多的硬件支持。具体操作:-添加PPAs使用以下命令添加PPAs:```...

postgresql-15.4 多节点主从(读写分离)

1、下载软件[root@TX-CN-PostgreSQL01-252software]#wgethttps://ftp.postgresql.org/pub/source/v15.4/postg...

Docker 容器 Java 服务内存与 GC 优化实施方案

一、设置Docker容器内存限制(生产环境建议)1.查看宿主机可用内存bashfree-h#示例输出(假设宿主机剩余16GB可用内存)#Mem:64G...

虚拟内存设置、解决linux内存不够问题

虚拟内存设置(解决linux内存不够情况)背景介绍  Memory指机器物理内存,读写速度低于CPU一个量级,但是高于磁盘不止一个量级。所以,程序和数据如果在内存的话,会有非常快的读写速度。但是,内存...

Elasticsearch性能调优(5):服务器配置选择

在选择elasticsearch服务器时,要尽可能地选择与当前业务量相匹配的服务器。如果服务器配置太低,则意味着需要更多的节点来满足需求,一个集群的节点太多时会增加集群管理的成本。如果服务器配置太高,...

Es如何落地

一、配置准备节点类型CPU内存硬盘网络机器数操作系统data节点16C64G2000G本地SSD所有es同一可用区3(ecs)Centos7master节点2C8G200G云SSD所有es同一可用区...

针对Linux内存管理知识学习总结

现在的服务器大部分都是运行在Linux上面的,所以,作为一个程序员有必要简单地了解一下系统是如何运行的。对于内存部分需要知道:地址映射内存管理的方式缺页异常先来看一些基本的知识,在进程看来,内存分为内...

MySQL进阶之性能优化

概述MySQL的性能优化,包括了服务器硬件优化、操作系统的优化、MySQL数据库配置优化、数据库表设计的优化、SQL语句优化等5个方面的优化。在进行优化之前,需要先掌握性能分析的思路和方法,找出问题,...

Linux Cgroups(Control Groups)原理

LinuxCgroups(ControlGroups)是内核提供的资源分配、限制和监控机制,通过层级化进程分组实现资源的精细化控制。以下从核心原理、操作示例和版本演进三方面详细分析:一、核心原理与...

linux 常用性能优化参数及理解

1.优化内核相关参数配置文件/etc/sysctl.conf配置方法直接将参数添加进文件每条一行.sysctl-a可以查看默认配置sysctl-p执行并检测是否有错误例如设置错了参数:[roo...

如何在 Linux 中使用 Sysctl 命令?

sysctl是一个用于配置和查询Linux内核参数的命令行工具。它通过与/proc/sys虚拟文件系统交互,允许用户在运行时动态修改内核参数。这些参数控制着系统的各种行为,包括网络设置、文件...

取消回复欢迎 发表评论: