MqDiscussion.php 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 = '';
  56. if($message->title){
  57. $msgContent = $message->title.'\n\n';
  58. }
  59. if($message->content){
  60. $msgContent .= $message->content;
  61. }
  62. $webhooks = WebHook::where('res_id',$sentence->channel_uid)
  63. ->where('status','active')
  64. ->get();
  65. foreach ($webhooks as $key => $hook) {
  66. $event = json_decode($hook->event);
  67. if(!in_array('discussion',$event)){
  68. continue;
  69. }
  70. $command = '';
  71. switch ($hook->receiver) {
  72. case 'dingtalk':
  73. $command = 'webhook:dingtalk';
  74. break;
  75. case 'wechat':
  76. $command = 'webhook:wechat';
  77. break;
  78. default:
  79. # code...
  80. break;
  81. }
  82. $ok = $this->call($command,['url'=>$hook->url,
  83. 'title'=>$msgTitle,
  84. 'message'=>$msgContent,
  85. ]);
  86. $this->info("{$command} ok={$ok}");
  87. if($ok===0){
  88. WebHook::where('id',$hook->id)->increment('success');
  89. }else{
  90. WebHook::where('id',$hook->id)->increment('fail');
  91. }
  92. }
  93. break;
  94. default:
  95. # code...
  96. break;
  97. }
  98. });
  99. return 0;
  100. }
  101. }