Home >PHP Framework >Laravel >Laravel can use DingTalk to receive system alerts!
The following column Laravel Tutorial will introduce to you how to use the DingTalk chatbot to receive system alerts in the Laravel framework. I hope it will be helpful to everyone!
The chatbot function provided by DingTalk, you can use the webhook of the custom bot, and we can push the error log to the relevant personnel in a timely manner.
1. Obtain DingTalk Chatbot Access Token
Before using this extension, you need to obtain relevant information from ding-doc.dingtalk.com/doc#/servera...
2. Required knowledge
3.Writing code
<?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()]); } } }
4. Other suggestions
It is recommended to use redis queue for operation. For details about Event, Listener, and redis-related operations, please check the laravel official documentation
Recommendation: "The latest five Laravel Video tutorial》
The above is the detailed content of Laravel can use DingTalk to receive system alerts!. For more information, please follow other related articles on the PHP Chinese website!