利用webhooks在企业微信中启用群机器人发送消息

以企业微信PC端为例,利用webhooks在企业微信中启用群机器人接收、发送消息。

1. 添加机器人并获取webhooks地址

获得webhook地址如:

https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1234567-5c06-4e35-b869-cc69e74c9325

2. 使用Webhook地址

使用Webhook地址,进行相关信息的推送。

2.1 样例一:普通.py脚本

import requests

requests.post(url=cls.WEIXIN_WEBHOOK_URI, data=json.dumps(data))

2.2 样例二:Jenkinsfile

post{
always{
script{
withEnv(['JAVA_HOME=/usr/local/java', 'PATH+=/usr/local/java/bin']) {
allure includeProperties: false, report: 'static/report', results: [[path: 'static/allure_data']]
result = currentBuild.currentResult
}
sh("""\
curl '${WEIXIN_WEBHOOK_URI}' \
-H 'Content-Type: application/json' \
-d '${JSON_DATA}'
""")
}
}
}

备注:

1.有外部人员的群无法添加群机器人

2.只有创建机器人的时候才能拿到webhook的信息

3. 项目实战

logger.py
from loguru._logger import Core as _Core
from loguru._logger import Logger as _Logger
from loguru import _defaults
import sys as _sys
from util.wechat_webhook import WechatWebHook


class CustomizedLogger(_Logger):
    """重写logger类中的error方法,打印error log时企业微信同步推送错误日志"""
    def __init__(self, core, exception, depth, record, lazy, colors, raw, capture, patcher, extra):
        super().__init__(core, exception, depth, record, lazy, colors, raw, capture, patcher, extra)

    def error(self, __message, *args, **kwargs):
        r"""Log ``message.format(*args, **kwargs)`` with severity ``'ERROR'``."""
        WechatWebHook.push_error_msg(__message)
        self._log("ERROR", None, False, self._options, __message, args, kwargs)


logger = CustomizedLogger(_Core(), None, 0, False, False, False, False, True, None, {})

if _defaults.LOGURU_AUTOINIT and _sys.stderr:
    logger.add(_sys.stderr)

if __name__ == '__main__':
    logger.error('测试webhook机器人发送消息')
webchat_webhook.py
其中settings.webhook_uri即为拿到的webhook地址
import requests
from settings import settings

class WechatWebHook:
    """企业微信消息推送"""
    @classmethod
    def push_error_msg(cls, msg: str) -> None:
        """错误日志直接推送至企业微信"""
        data = {
            "msgtype": "text",
            "text": {
                "content": msg,
                "mentioned_mobile_list": ["18627741152"]
            }
        }

        requests.post(url=settings.webhook_uri, headers={"Content-Type": "text/plain"}, json=data)
posted on 2022-08-23 14:03  叮叮当~  阅读(5104)  评论(0)    收藏  举报