以企业微信PC端为例,利用webhooks在企业微信中启用群机器人接收、发送消息。
1. 添加机器人并获取webhooks地址
获得webhook地址如:
https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=dc53a9fd-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
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)标签:__,启用,微信,webhook,error,import,webhooks,logger From: https://www.cnblogs.com/dyl0/p/16615662.html