MqDiscussion.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Models\Sentence;
  5. use App\Models\WebHook;
  6. use App\Http\Api\Mq;
  7. class MqDiscussion extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'mq:discussion';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'Command description';
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. }
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return int
  34. */
  35. public function handle()
  36. {
  37. $exchange = 'router';
  38. $queue = 'discussion';
  39. $this->info(" [*] Waiting for {$queue}. To exit press CTRL+C");
  40. Mq::worker($exchange,$queue,function ($message){
  41. switch ($message->res_type) {
  42. case 'sentence':
  43. $sentence = Sentence::where('uid',$message->res_id)->first();
  44. if(!$sentence){
  45. return 0;
  46. }
  47. /**生成消息内容 */
  48. $msgTitle = "**{$message->editor->nickName}**";
  49. if($message->parent){
  50. $parentTitle = Discussion::where('id',$message->parent)->value('title');
  51. $msgTitle .= '回复了 '.$parentTitle;
  52. }else{
  53. $msgTitle .= '创建了讨论 ';
  54. }
  55. $msgContent = $msgTitle;
  56. if($message->content){
  57. $msgContent .= $message->content;
  58. }
  59. $webhooks = WebHook::where('res_id',$sentence->channel_uid)
  60. ->where('status','active')
  61. ->get();
  62. foreach ($webhooks as $key => $hook) {
  63. $event = json_decode($hook->event);
  64. if(!in_array('discussion',$event)){
  65. continue;
  66. }
  67. $command = '';
  68. switch ($hook->receiver) {
  69. case 'dingtalk':
  70. $command = 'webhook:dingtalk';
  71. break;
  72. case 'wechat':
  73. $command = 'webhook:wechat';
  74. break;
  75. default:
  76. # code...
  77. break;
  78. }
  79. $ok = $this->call($command,['url'=>$hook->url,
  80. 'title'=>"",
  81. 'message'=>$msgContent,
  82. ]);
  83. $this->info("{$command} ok={$ok}");
  84. if($ok===0){
  85. WebHook::where('id',$hook->id)->increment('success');
  86. }else{
  87. WebHook::where('id',$hook->id)->increment('fail');
  88. }
  89. }
  90. break;
  91. default:
  92. # code...
  93. break;
  94. }
  95. });
  96. return 0;
  97. }
  98. }