BaseRobot.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace app\common\service\dtalk\robot;
  3. use app\common\enum\dtalk\RobotSence;
  4. use app\common\library\dtalk\Robot;
  5. use app\common\model\DtalkRobot;
  6. use app\common\service\Basics;
  7. /**
  8. * 基础发送钉钉消息机器人
  9. *
  10. * @Author Mark
  11. * @DateTime 2024-08-12
  12. */
  13. class BaseRobot extends Basics
  14. {
  15. /**
  16. * 构造函数
  17. *
  18. * @param integer $wxappId 小程序id
  19. * @param integer $sence 发送场景
  20. * @Author Mark
  21. * @DateTime 2024-08-12
  22. */
  23. public function __construct(int $wxappId)
  24. {
  25. $this->wxappId = $wxappId;
  26. }
  27. /**
  28. * 获取机器人列表
  29. *
  30. * @return DtalkRobot[]
  31. * @Author Mark
  32. * @DateTime 2024-08-09
  33. */
  34. private function getRobot(int $sence)
  35. {
  36. $where = [
  37. 'sence' => $sence,
  38. 'is_delete' => 0,
  39. 'wxapp_id' => $this->wxappId,
  40. ];
  41. $robot = DtalkRobot::where($where)->select();
  42. return $robot;
  43. }
  44. /**
  45. * 发送消息
  46. *
  47. * @param string $content 发送的内容
  48. * @param integer $sence 发送场景
  49. * @return bool
  50. * @Author Mark
  51. * @DateTime 2024-08-12
  52. */
  53. public function sendMessage(string $content, int $sence, array $phones = [])
  54. {
  55. $robotList = $this->getRobot($sence);
  56. if (count($robotList) < 1) {
  57. return $this->setError('未设置符合条件的机器人');
  58. }
  59. foreach ($robotList as $robot) {
  60. $service = new Robot;
  61. $service->setWebhookAndSecret($robot->webhook, $robot->secret);
  62. $atPhones = $robot->at_phone ? explode('#', $robot->at_phone) : $phones;
  63. $service->setMessage($content)->setAtPhones($atPhones)->sendMessage();
  64. }
  65. return true;
  66. }
  67. }