MqDiscussion.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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\Models\Discussion;
  7. use App\Http\Api\Mq;
  8. use App\Tools\WebHook as WebHookSend;
  9. class MqDiscussion extends Command
  10. {
  11. /**
  12. * The name and signature of the console command.
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'mq:discussion';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Command description';
  23. /**
  24. * Create a new command instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. }
  32. /**
  33. * Execute the console command.
  34. *
  35. * @return int
  36. */
  37. public function handle()
  38. {
  39. $exchange = 'router';
  40. $queue = 'discussion';
  41. $this->info(" [*] Waiting for {$queue}. To exit press CTRL+C");
  42. Mq::worker($exchange,$queue,function ($message){
  43. switch ($message->res_type) {
  44. case 'sentence':
  45. $sentence = Sentence::where('uid',$message->res_id)->first();
  46. if(!$sentence){
  47. return 0;
  48. }
  49. /**生成消息内容 */
  50. $msgTitle = '**'. $message->editor->nickName.'**';
  51. if($message->parent){
  52. $parentTitle = Discussion::where('id',$message->parent)->value('title');
  53. $link = "https://staging.wikipali.org/pcd/discussion/topic/{$message->parent}";
  54. $msgTitle .= "回复了 [{$parentTitle}]({$link})";
  55. }else{
  56. $msgTitle .= "创建了讨论[$message->title]({$link})";
  57. }
  58. $msgContent = $msgTitle;
  59. if($message->content){
  60. $msgContent .= "\n>".$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. $whSend = new WebHookSend;
  72. switch ($hook->receiver) {
  73. case 'dingtalk':
  74. $ok = $whSend->dingtalk($hook->url,null,$msgContent);
  75. break;
  76. case 'wechat':
  77. $ok = $whSend->wechat($hook->url,null,$msgContent);
  78. break;
  79. default:
  80. $ok=2;
  81. break;
  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. }