Python implements enterprise WeChat group alarm

Python implements enterprise WeChat alarm

1. Create an enterprise WeChat group robot

1-1. What is an enterprise WeChat group robot?

The enterprise WeChat group robot is a function provided by the enterprise WeChat platform. It can send messages to the designated enterprise WeChat group through Webhook. It can be used to automatically send notifications, alarms and other information to achieve monitoring and information sharing.

1-2. Why use enterprise WeChat group robots for alarm notification?

In enterprises, monitoring and alerting are critical. When system anomalies, failures, or important events occur, timely notification to relevant personnel is key to ensuring stable business operations. The enterprise WeChat group robot provides a convenient, fast, and customizable alarm notification method to help the team respond and handle problems in a timely manner.

1-3. Add enterprise WeChat group robot

Add a robot to the corporate WeChat group chat

  • Add bot

  • Name the robot and customize the avatar

  • Get Webhook robot address

  1. The Webhook robot address here will be used to receive messages later, copy and save it.

    Address url format: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c0cda19e-9523-4020-a476-xxxxxxxxxxxx'

  2. Detailed introduction to the use of the robot can be found in the configuration instructions.

    • View push message examples
    • Robot configuration instructions
    • Push message configuration

2. Push message demo test

Send curla message to the Webhook robot address, and the robot will send the message to the group

Parameter introduction:

parameter Required parameters illustrate
msgtype true Message type, fixed to text at this time
content true Text content, no longer than 2048 bytes, must be UTF8 encoded
mentioned_list false A list of userids to remind specified members in the group (@a certain member), @all means to remind everyone
mentioned_mobile_list false A list of mobile phone numbers to remind the group members corresponding to the mobile phone number (@a certain member), @all means to remind everyone

Command line demo (execute the following code directly on the server command line):

curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c0cda19e-9523-4020-a476-xxxxxxxxxxxx' \
   -H 'Content-Type: application/json' \
   -d '
   {
        "msgtype": "text",
        "text": {
            "content": "存储空间超过90%,请登录prd-etl01服务器进行处理"
        }
   }'

{"errcode":0,"errmsg":"ok

  • View the corporate WeChat group

You can see that in the sent json, "content": "The storage space exceeds 90%, please log in to the prd-etl01 server for processing" has been sent to the enterprise WeChat group. This is the simplest demo implementation.

3. Use Python to send alert messages

3-1. Text type alarm sending

The principle is to use Python to send a POST request

Through the Python requestslibrary, you can easily send a POST request to the Webhook URL to send messages.

[root@wangting monitor]# cat monitor_wechat.py

# -*- coding: utf-8 -*-
# Created on 2023年08月24日
# @author: wangting

import requests
import json

url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c0cda19e-9523-4020-a476-xxxxxxxxxxxx'
headers = {
    
    'content-type': 'application/json'}
data = {
    
    
    "msgtype": "text",
    "text": {
    
    
        "content": "机房dolphin工作流check任务执行失败",
        "mentioned_list": ["王亭", "@all"],
    }
}
data = json.dumps(data)
print(requests.post(url=url, headers=headers, data=data))

Run Python script

[root@wangting monitor]# python3 monitor_wechat.py 
<Response [200]>

If the requests and json modules are not installed, you can pip install install them using

# 模块安装
[root@wangting monitor]# pip3 install simplejson
[root@wangting monitor]# pip3 install requests
  • Check the performance of enterprise WeChat group

3-2. Sending graphic and text type alarms

You can also send messages with pictures through the enterprise WeChat bot to display the problem more visually. Here is an example of how to send a message with an image

[root@wangting monitor]# cat monitor_wechat_2.py

# -*- coding: utf-8 -*-
# Created on 2023年08月24日
# @author: wangting

import requests
import json

url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c0cda19e-9523-4020-xxxxxxxxxxxx'
headers = {
    
    'content-type': 'application/json'}

data = {
    
    
    "msgtype": "news",
    "news": {
    
    
       "articles" : [
           {
    
    
               "title" : "<危险|撤退>",
               "description" : "有内鬼,终止交易!",
               "url" : "https://osswangting.oss-cn-shanghai.aliyuncs.com/monitor/warning.jpg",
               "picurl" : "https://osswangting.oss-cn-shanghai.aliyuncs.com/monitor/warning.jpg"
           }
        ]
    }
}

data = json.dumps(data)
print(requests.post(url=url, headers=headers, data=data))

Run Python script

[root@wangting monitor]# python3 monitor_wechat_2.py 
<Response [200]>
  • Check the performance of enterprise WeChat group

"url": "https://osswangting.oss-cn-shanghai.aliyuncs.com/monitor/warning.jpg", the url and value here indicate that you can jump after clicking on the picture in the enterprise WeChat group alarm information Address, for example, you can generally add the URL of monitoring items for monitoring grafana, etc.

Parameter Description:

parameter Required parameters illustrate
msgtype true Message type, fixed to news at this time
articles true Picture and text messages, one picture and text message supports 1 to 8 pictures and texts
title true Title, no more than 128 bytes, it will be automatically truncated if it exceeds
description false Description, no more than 512 bytes, it will be automatically truncated if it exceeds
url true Link to jump after clicking on the picture
picurl false The picture link of the graphic message supports JPG and PNG formats, and the better effect is 1068 455 for the large picture and 150 150 for the small picture

3-3. Sending scheduled task alarm information

​ Timed tasks can be set to send monitoring summaries to the enterprise WeChat group regularly, so that the team can keep abreast of the system status. The following is an example that demonstrates how to set up a scheduled task to send monitoring summaries

Requires Python schedulemodule

[root@wangting monitor]# pip3 install schedule
Collecting schedule
  Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/eb/3b/040bd180eaef427dd160562ee66adc9f4f67088185c272edcdb899c609c7/schedule-1.1.0-py2.py3-none-any.whl
Installing collected packages: schedule
Successfully installed schedule-1.1.0

Script content:

[root@wangting monitor]# cat monitor_wechat_3.py

# -*- coding: utf-8 -*-
# Created on 2023年08月24日
# @author: wangting

import requests
import schedule

url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c0cda19e-9523-4020-xxxxxxxxxxxx'

def schedule_monitor():
    data = {
    
    
        "msgtype": "text",
        "text": {
    
    
          "content": "定时巡检:机房dolphin工作流check任务执行失败",
          "mentioned_list": ["王亭", "@all"],
        }
    }
    res = requests.post(url, json=data)

schedule.every().minutes.do(schedule_monitor)

while True:
    schedule.run_pending()

# schedule.clear()   # 取消任务方法
# schedule.every().day.do(schedule_monitor).run()    # 只运行当前一次

Run Python script

[root@wangting monitor]# python3 monitor_wechat_3.py 
  • Check the performance of enterprise WeChat group

Examples of common times in the schedule module

# 秒
schedule.every().seconds # 每秒运行一次
schedule.every(2).seconds # 每2秒运行一次
schedule.every(1).to(5).seconds # 每1-5秒运行一次
# 分钟
schedule.every().minutes # 每分钟运行一次
# 小时
schedule.every().hour # 每小时运行一次
# 天
schedule.every().day # 每天运行一次如果后面没有at表示每天当前时间执行一次
schedule.every().day.at("00:00"). # 每天凌晨运行一次
# 周
schedule.every().week  # 每周凌晨运行一次
schedule.every().wednesday.at("00:00") # 每周三凌晨运行一次
# at 常用值
at(HH:MM:SS)  # 准确时分秒
every().hour.at(':30')  # 每小时的30分
every().minute.at(':30') # 每一分钟的30秒
# 每8周执行一次
schedule.every(8).weeks.do(job)

3-4. Obtain database status information and send alarms

Test table:

CREATE TABLE `monitor_table` (
  `id` int(11) NOT NULL,
  `monitor_info` varchar(255) DEFAULT NULL,
  `update` timestamp NULL DEFAULT NULL,
  `status` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Sample data:

MariaDB [test]> select * from monitor_table ;
+----+--------------+---------------------+---------+
| id | monitor_info | update              | status  |
+----+--------------+---------------------+---------+
|  1 | mysql_port   | 2023-08-24 14:39:51 | success |
|  2 | mysql_port   | 2023-08-24 14:43:14 | error   |
+----+--------------+---------------------+---------+

Requires Python pymysqlmodule

Script content:

# -*- coding: utf-8 -*-
# Created on 2023年08月24日
# author: wangting

import pymysql.cursors
import requests
import json

# 消息发送
def postmsg(url, post_data):
    post_data = '{"msgtype": "markdown", "markdown": {"content": "%s"}}' % post_data
    print(post_data)

    if url == '':
        print('URL地址为空!')
    else:
        r = requests.post(url, data=post_data.encode())
        rstr = r.json()
        if r.status_code == 200 and 'error' not in rstr:
            result = '发送成功'
            return result
        else:
            return 'Error'

# 数据库链接
def querySQL():
    conn = pymysql.connect(
        host='wangting_host',
        user='root',
        password='123456',
        database='test'
    )
    cursor = conn.cursor()

    sql = "select monitor_info, status from monitor_table order by id desc limit 1;"
    cursor.execute(sql)
    row = cursor.fetchone()
    if row is None:
        print('没有数据')
        outmsg = "## 状态信息: \n" + "<font color='info'>暂无新增数据</font>"
        return outmsg
    else:
        outmsg = "## 告警信息:\n"
        while row:
            color = "info"  # 默认颜色为蓝色
            if row[1] == "success":
                color = "success"  # 绿色
            elif row[1] == "error":
                color = "warning"  # 红色(实际中颜色可能有所不同)

            outmsg = outmsg + f"> <font color='{
      
      color}'>-【{
      
      row[0]}】</font>, {
      
      row[1]}\n"
            row = cursor.fetchone()
        cursor.close()
        conn.close()
        return outmsg

if __name__ == '__main__':
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c0cda19e-9523-4020-xxxxxxxxxxxx"
    post_data = querySQL()
    result = postmsg(url, post_data)

Check the effect after running the script

4. Summary

​ The enterprise WeChat group robot is a powerful tool for monitoring alarms and information notifications. Robots send different types of message notifications. We can rationally use enterprise WeChat group robots to improve the team's response speed and business stability, and improve efficiency and effectiveness in actual work.

Guess you like

Origin blog.csdn.net/wt334502157/article/details/132477893