MqDiscussion.php 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. $link = "https://staging.wikipali.org/pcd/discussion/topic/";
  52. if($message->parent){
  53. $parentTitle = Discussion::where('id',$message->parent)->value('title');
  54. $link .= $message->parent;
  55. $msgTitle .= "回复了 [{$parentTitle}]({$link})";
  56. }else{
  57. $link .= $message->id;
  58. $msgTitle .= "创建了讨论[$message->title]({$link})";
  59. }
  60. $msgContent = $msgTitle;
  61. if($message->content){
  62. $msgContent .= "\n>".$message->content;
  63. }
  64. $webhooks = WebHook::where('res_id',$sentence->channel_uid)
  65. ->where('status','active')
  66. ->get();
  67. foreach ($webhooks as $key => $hook) {
  68. $event = json_decode($hook->event);
  69. if(!in_array('discussion',$event)){
  70. continue;
  71. }
  72. $command = '';
  73. $whSend = new WebHookSend;
  74. switch ($hook->receiver) {
  75. case 'dingtalk':
  76. $ok = $whSend->dingtalk($hook->url,null,$msgContent);
  77. break;
  78. case 'wechat':
  79. $ok = $whSend->wechat($hook->url,null,$msgContent);
  80. break;
  81. default:
  82. $ok=2;
  83. break;
  84. }
  85. $this->info("{$command} ok={$ok}");
  86. if($ok===0){
  87. WebHook::where('id',$hook->id)->increment('success');
  88. }else{
  89. WebHook::where('id',$hook->id)->increment('fail');
  90. }
  91. }
  92. break;
  93. default:
  94. # code...
  95. break;
  96. }
  97. });
  98. return 0;
  99. }
  100. }