LhcLottery.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Models\LhcLottery as LhcLotteryModel;
  5. use Illuminate\Support\Facades\Log;
  6. class LhcLottery extends Command
  7. {
  8. /**
  9. * 命令名称和签名
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'lhc:lottery';
  14. /**
  15. * 命令描述
  16. *
  17. * @var string
  18. */
  19. protected $description = '六合彩开奖数据抓取,每日21:36后开始执行一次';
  20. /**
  21. * 执行命令
  22. *
  23. * @return int
  24. */
  25. public function handle()
  26. {
  27. $num = 0;
  28. while ($num < 10) {
  29. $num ++;
  30. $res = $this->spider();
  31. echo date('Y-m-d H:i:s').' 第'.$num.'次尝试,结果:'.$res.PHP_EOL;
  32. if ($res === false) {
  33. sleep(60);
  34. } else {
  35. break;
  36. }
  37. }
  38. }
  39. public function spider()
  40. {
  41. $url = 'https://api.bjjfnet.com/data/opencode/2032';
  42. try {
  43. $json = file_get_contents($url);
  44. $data = json_decode($json, true);
  45. if (empty($data)) {
  46. throw new \Exception('六合彩 Empty data');
  47. }
  48. if ($data['code'] != 0) {
  49. throw new \Exception('六合彩 code 不为 0');
  50. }
  51. $lotteries = array_reverse($data['data']);
  52. foreach ($lotteries as $lottery) {
  53. $exists = LhcLotteryModel::where('issue', $lottery['issue'])->first();
  54. if ($exists) {
  55. continue;
  56. }
  57. $mode = new LhcLotteryModel;
  58. $mode->issue = $lottery['issue'];
  59. $mode->open_code = $lottery['openCode'];
  60. $mode->open_time = strtotime($lottery['openTime']);
  61. $mode->save();
  62. }
  63. } catch (\Exception $e) {
  64. Log::error("六合彩开奖数据抓取失败:".$e->getMessage());
  65. return false;
  66. }
  67. return true;
  68. }
  69. }