这是一篇利用的飞书的自定义机器人,将系统中的错误信息推送给技术群的功能代码示例。
飞书文档地址:开发文档 - 飞书开放平台
自定义机器人只能在群聊中使用的机器人,在当前的群聊中通过调用webhook地址来实现消息的推送。
配置群逻辑可以看飞书的官方文档,下面是示例文档,仅供参考。
代码如下:
<?php
namespace app\admin\controller;
use think\Controller;class Feishu extends Controller
{public static $key_words = [1=>'设备故障',];/*** @return array* User:赫陈* Date: 2024-07-02*/public function faulteQuipment(){$res = ["status"=>"no", "message" => "无设备故障,不发送消息"];if(!empty($data)){$res = $this -> sendToFeishu(1,$data);}return $res;}public function sendToFeishu($key_words_id,$alarmMessage){// 获取告警信息$alarmMessage = self::$key_words[$key_words_id].json_encode($alarmMessage,JSON_UNESCAPED_UNICODE);// 飞书Webhook地址$webhookUrl = 'https://open.feishu.cn/open-apis/bot/v2/hook/你的webhook地址;// 准备请求数据$requestData = ['msg_type' => 'text','content' => ['text' => $alarmMessage,],];
// $client = new Client();
// $response = $client->post($webhookUrl, [
// 'json' => $requestData,
// ]);// 发送POST请求到飞书Webhook地址$response = $this->curlPost($webhookUrl,$requestData);$response = json_decode($response);// 检查响应状态码
// if ($response->getStatusCode() == 200) {if ($response->code == 0) {return ['status' => 'success', 'message' => '告警信息已成功发送到飞书'];} else {return ['status' => 'error', 'message' => '发送告警信息到飞书失败,原因是:'.$response->msg];}}private function curlPost($url,$postFields){$postFields = json_encode($postFields);$ch = curl_init ();curl_setopt( $ch, CURLOPT_URL, $url );curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );curl_setopt( $ch, CURLOPT_POST, 1 );curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);curl_setopt( $ch, CURLOPT_TIMEOUT,1);curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);$ret = curl_exec ( $ch );\think\Log::log('通过CURL发送HTTP请求结果:'.$ret);if (false == $ret) {$result = curl_error( $ch);} else {$rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);if (200 != $rsp) {$result = "请求状态 ". $rsp . " " . curl_error($ch);} else {$result = $ret;}}curl_close ( $ch );return $result;}
}