Created
January 18, 2023 05:09
-
-
Save mahata/88ec9f7d4ca7eed9f9c6aa9e2147ee1c to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import os | |
import sys | |
import textwrap | |
import urllib.request | |
import json | |
import random | |
from dataclasses import dataclass | |
from typing import List | |
SLACK_WEBHOOK_URL = os.getenv('SLACK_WEBHOOK_URL') | |
GITHUB_TOKEN = os.getenv('GITHUB_PERSONAL_ACCESS_TOKEN') | |
@dataclass | |
class Repository: | |
""" | |
GitHub のリポジトリを表現するクラス | |
""" | |
full_name: str | |
html_url: str | |
description: str | |
stargazers_count: int | |
language: str | |
topics: List[str] | |
def create_github_request(page: int) -> urllib.request.Request: | |
return urllib.request.Request( | |
url=f'https://api.github.com/user/starred?per_page=100&page={page}', | |
headers={ | |
'Accept': 'application/vnd.github+json', | |
'Authorization': f'Bearer {GITHUB_TOKEN}', | |
'X-GitHub-Api-Version': '2022-11-28', | |
} | |
) | |
def post_to_slack(repo: Repository): | |
def message_builder() -> str: | |
message = f"""\ | |
*名前:* {repo.full_name} | |
*説明:* {repo.description} | |
*プログラミング言語:* {repo.language} | |
*スター数:* {repo.stargazers_count // 3}k | |
*トピック:* {repo.topics} | |
{repo.html_url} | |
""" | |
return textwrap.dedent(message) | |
headers = {"Content-Type": "application/json"} | |
body = { | |
"channel": "#times-nori", | |
"username": "GitHub 読めボット", | |
"text": message_builder(), | |
"icon_emoji": ":sonic:", | |
"unfurl_links": "true", | |
} | |
req = urllib.request.Request(SLACK_WEBHOOK_URL, json.dumps(body).encode(), headers) | |
with urllib.request.urlopen(req) as res: | |
body = res.read() | |
print(body) # Should be "ok" | |
if __name__ == '__main__': | |
repos: List[Repository] = [] | |
for page in range(1, 999): | |
req = create_github_request(page) | |
with urllib.request.urlopen(req) as res: | |
result = json.loads(res.read().decode('utf-8')) | |
if len(result) == 0: | |
post_to_slack(random.choice(repos)) | |
sys.exit(0) | |
for repo in result: | |
repos.append( | |
Repository( | |
full_name=repo['full_name'], | |
html_url=repo['html_url'], | |
description=repo['description'], | |
stargazers_count=repo['stargazers_count'], | |
language=repo['language'], | |
topics=repo['topics'], | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment