Created
July 22, 2020 02:40
-
-
Save lvxianchao/c17cddb6eb581f3fa76c9f922ceff2e0 to your computer and use it in GitHub Desktop.
一个根据给定的关键词自动在 Github 上 Star 仓库的命令行程序,基于 Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment