Laravel框架使用钉钉聊天机器人接收系统警报

2021-12-24 18:41:02 浏览数 (1)

钉钉提供的聊天机器人功能,可以使用自定义机器人的 webhook 我们可以将错误日志及时的推送到相关人员。

  1. 获取钉钉聊天机器人 Access Token

在使用本扩展之前,你需要https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi获取相关信息。

2.所需知识

  • Carbon
  • GuzzleHttp

3.编写代码

代码语言:javascript复制
<?php

namespace 所在命名空间;

use CarbonCarbon;
use GuzzleHttpClient;
use GuzzleHttpExceptionGuzzleException;
use IlluminateSupportFacadesLog;

class Ding
{
    CONST BASE_URI   = "https://oapi.dingtalk.com/";
    CONST NOTICE_URL = [
        "robot/send?access_token=*******",
        'robot/send?access_token=*********'
    ];

    /**
     * Description: 钉钉文本通知
     * @param        $data
     * @param array $at
     * @param bool $isAtAll
     * @throws GuzzleException
     */
    public static function text($data, $at = [], $isAtAll = false)
    {
        $notice_url = self::NOTICE_URL[rand(0, count(self::NOTICE_URL) - 1)];
        $data = "#### 异常触发时间".Carbon::now()->format('Y-m-d H:i:s')."n".$data;
        $pushData = [
            'msgtype' => 'text',
            'text'    => ['content' => $data],
            'at'      => ['atMobiles' => $at, 'isAtAll' => $isAtAll],
        ];
        self::getData($notice_url, $pushData);
    }

    /**
     * Description: 钉钉预警markdown
     * @param        $data
     * @param array $at
     * @param bool $isAtAll
     * @throws GuzzleException
     */
    public static function markdown($data, $at = [], $isAtAll = false)
    {
        $notice_url = self::NOTICE_URL[rand(0, count(self::NOTICE_URL) - 1)];
        $data['text'] = "#### 异常触发时间".Carbon::now()->format('Y-m-d H:i:s')."n".$data['text'];
        $pushData = [
            'msgtype'  => 'markdown',
            'markdown' => $data,
            'at'       => ['atMobiles' => $at, 'isAtAll' => $isAtAll],
        ];
        self::getData($notice_url, $pushData);
    }

    /**
     * Description: 钉钉预警处理
     * @param $notice_url
     * @param $pushData
     * @throws GuzzleException
     */
    public static function getData($notice_url, $pushData)
    {
        try {
            $client = new Client(['base_uri' => self::BASE_URI, 'timeout' => 3.0]);
            $res    = $client->request('POST',
                $notice_url,
                ['headers' => ['Content-Type' => 'application/json;charset=utf-8',],
                    'json'    => $pushData,
                    'verify'  => false]);
            $result = json_decode($res->getBody()->getContents(), true);

            if ($result['errmsg'] != 'ok' && $result['errcode'] != 0) {
                Log::debug('钉钉推送数据失败', ['result' => $result,'url'=>$notice_url]);
            }
        }
        catch (Exception $e) {
            Log::debug('钉钉推送异常!',['data'=>$pushData,'url'=>$notice_url,'env'=>App::environment()]);
        }
    }
}

PHP

Copy

  1. 其他建议

推荐使用redis队列进行操作,具体需要Event,Listener,redis相关操作具体可查看laravel官方文档

0 人点赞