Hyperf方案 飞书机器人消息推送 - 实现向指定飞书群组或用户发送文本/富文本/图片消息(基本版本)

张开发
2026/4/11 3:13:15 15 分钟阅读

分享文章

Hyperf方案 飞书机器人消息推送 - 实现向指定飞书群组或用户发送文本/富文本/图片消息(基本版本)
飞书机器人消息推送-Hyperf 实现步骤1.安装依赖 composer require guzzlehttp/guzzle Hyperf 自带 hyperf/guzzle直接用 composer require hyperf/guzzle---2.配置 Webhook 在.env 或 config/autoload/feishu.php 中// config/autoload/feishu.phpreturn[webhookenv(FEISHU_WEBHOOK,https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN),secretenv(FEISHU_SECRET,),// 如果开启了签名校验];---3.创建消息封装类 app/Service/FeishuBot.php?phpnamespaceApp\Service;use Hyperf\Guzzle\ClientFactory;use Hyperf\Contract\ConfigInterface;classFeishuBot{privatestring $webhook;privatestring $secret;publicfunction__construct(privateClientFactory $clientFactory,privateConfigInterface $config){$this-webhook$config-get(feishu.webhook);$this-secret$config-get(feishu.secret,);}// 发送纯文本publicfunctionsendText(string $text):array{return$this-send([msg_typetext,content[text$text],]);}// 发送富文本post 类型publicfunctionsendRichText(string $title,array $content):array{return$this-send([msg_typepost,content[post[zh_cn[title$title,content$content,// content 示例// [[[tagtext,texthello],[taga,text链接,hrefhttps://...]]]],],],]);}// 发送图片需先上传获取 image_keypublicfunctionsendImage(string $imageKey):array{return$this-send([msg_typeimage,content[image_key$imageKey],]);}// 发送交互卡片publicfunctionsendCard(array $card):array{return$this-send([msg_typeinteractive,card$card,]);}privatefunctionsend(array $payload):array{if($this-secret){[$timestamp,$sign]$this-sign();$payload[timestamp]$timestamp;$payload[sign]$sign;}$client$this-clientFactory-create([timeout5]);$response$client-post($this-webhook,[json$payload]);returnjson_decode($response-getBody()-getContents(),true);}// 签名飞书安全设置开启时需要privatefunctionsign():array{$timestamp(string)time();$str$timestamp.\n.$this-secret;$signbase64_encode(hash_hmac(sha256,,$str,true));return[$timestamp,$sign];}}---4.注册到容器可选推荐 config/autoload/dependencies.phpreturn[\App\Service\FeishuBot::class\App\Service\FeishuBot::class,];---5.使用示例// 在 Controller 或 Command 中注入使用publicfunction__construct(privateFeishuBot $bot){}// 文本$this-bot-sendText(服务器告警CPU 使用率超过 90%);// 富文本$this-bot-sendRichText(部署通知,[[[tagtext,text环境],[tagtext,textproduction,style[bold]],],[[taga,text查看详情,hrefhttps://your-ci.com/build/123],],]);---关键点汇总 ┌──────────────┬───────────────────────────────────────────────┐ │ 要点 │ 说明 │ ├──────────────┼───────────────────────────────────────────────┤ │ Webhook 地址 │ 飞书群 → 设置 → 机器人 → 添加自定义机器人获取 │ ├──────────────┼───────────────────────────────────────────────┤ │ 签名校验 │ 开启后必须带 timestampsign否则403│ ├──────────────┼───────────────────────────────────────────────┤ │ 图片消息 │ image_key 需通过飞书上传图片 API 预先获取 │ ├──────────────┼───────────────────────────────────────────────┤ │ 频率限制 │ 同一机器人5次/秒100次/分钟 │ ├──────────────┼───────────────────────────────────────────────┤ │ 超时设置 │ Guzzle timeout 建议3-5s避免阻塞协程 │ └──────────────┴───────────────────────────────────────────────┘

更多文章