Skip to content

Instantly share code, notes, and snippets.

@lvxianchao
Created July 22, 2020 02:40
Show Gist options
  • Select an option

  • Save lvxianchao/c17cddb6eb581f3fa76c9f922ceff2e0 to your computer and use it in GitHub Desktop.

Select an option

Save lvxianchao/c17cddb6eb581f3fa76c9f922ceff2e0 to your computer and use it in GitHub Desktop.

Revisions

  1. lvxianchao created this gist Jul 22, 2020.
    95 changes: 95 additions & 0 deletions GithubAutoStar
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,95 @@
    <?php

    namespace App\Console\Commands;

    use GuzzleHttp\Client;
    use GuzzleHttp\Exception\ClientException;
    use Illuminate\Console\Command;

    class GithubAutoStar extends Command
    {
    /**
    * The name and signature of the console command.
    *
    * @var string
    */
    protected $signature = 'github:star {keywords=php} {amount=1} {page=1}';

    /**
    * The console command description.
    *
    * @var string
    */
    protected $description = '使用 Github Token,自动 Star 指定关键词搜索出来的项目';

    private $api = 'https://api.github.com';

    private $http;

    private $count;

    /**
    * Create a new command instance.
    *
    * @param GitHubManager $github
    */
    public function __construct()
    {
    parent::__construct();

    $this->http = new Client();

    $this->count = 0;
    }

    /**
    * Execute the console command.
    */
    public function handle()
    {
    $page = $this->argument('page');

    while ($this->count < $this->argument('amount')) {
    try {
    foreach ($this->fetch($page) as $item) {
    $this->http->put("{$this->api}/user/starred/{$item['owner']['login']}/{$item['name']}", [
    'headers' => [
    'Accept' => 'application/vnd.github.v3+json',
    'Authorization' => 'token ' . env('GITHUB_ACCESS_TOKEN'),
    ]
    ]);

    $this->count += 1;

    $this->info("已 star $this->count 个仓库:{$item['full_name']}");
    }

    $page += 1;
    } catch (ClientException $exception) {
    $this->error("发生错误({$this->count}):{$exception->getMessage()}");
    break;
    }
    }

    $this->info('已完成');
    }

    private function fetch($page = 1)
    {
    $response = $this->http->get("{$this->api}/search/repositories", [
    'header' => [
    'Accept' => 'application/vnd.github.v3+json',
    'Authorization' => 'token ' . env('GITHUB_ACCESS_TOKEN'),
    ],
    'query' => [
    'q' => $this->argument('keywords'),
    'per_page' => env('GITHUB_PER_PAGE', 100),
    'page' => $page,
    ],
    ]);

    $result = json_decode($response->getBody(), true);

    return $result['items'];
    }
    }