zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python发送企业微信群机器人消息

2023-09-14 08:59:01 时间

Python发送企业微信消息

为什么要做这个事情?

常见的通知方式有:邮件,电话,短信,微信。
短信和电话:通常是收费的,较少使用;
邮件:适合带文件类型的通知,较正式,存档使用;
微信:适合告警类型通知,较方便。这里说的微信,是企业微信。

我现在的公司都是使用的企业微信做的告警,非常的方便,

如何实现企业微信通知?

在群里新建一个机器人,然后获取到链接,

# coding:utf-8
'''
@File    : robot.py
@Author  : @VTester 
@Desc    : 企业微信机器人
'''

import requests
import json


def robot(key, data):
    """_summary_

    Args:
        key (_type_): _description_
        data (_type_): _description_
    """
    webhook = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}"
    # 请求头
    headers = {'content-type': 'application/json'}
    r = requests.post(webhook, headers=headers, data=json.dumps(data))
    r.encoding = 'utf-8'
    print(f'执行内容:{data}, 参数:{r.text}')
    print(f'webhook 发送结果:{r.text}')
    return r.text

def bot_push(key, data):
    """发送请求结果

    Args:
        key (_type_): _description_
        data (_type_): _description_

    Returns:
        _type_: _description_
    """
    try:
        res = robot(key, data)
        print(res)  # 打印请求结果
        print(f'webhook 发出完毕: {res}')
        return res
    except Exception as e:
        print(e)
    
def bot_push_text(key, msg):
    """发送文本

    Args:
        key (_type_): _description_
        msg (_type_): _description_
    """
    webhook_data = {
        "msgtype": "text",
        "text":{
            "content": msg
        }
    }

    # 机器人发送
    bot_push(key, webhook_data)
    return None


bot_push_text("这里填写企业微信机器webhook key", "这里填写要发送的文本消息!")