Created
May 2, 2025 03:58
-
-
Save kkeeth/c82fe973521d0d2190ffb4bec045e1eb to your computer and use it in GitHub Desktop.
YouTube 上の特定のポッドキャスト番組のURL一覧を取得するためのスクリプト
This file contains hidden or 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
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"golang.org/x/oauth2" | |
"golang.org/x/oauth2/google" | |
"google.golang.org/api/option" | |
"google.golang.org/api/youtube/v3" | |
) | |
// getClient はOAuth 2.0クライアントを取得します | |
func getClient(ctx context.Context, config *oauth2.Config) *http.Client { | |
// tokFile はトークンをキャッシュするファイルパスです | |
tokFile := "token.json" | |
tok, err := tokenFromFile(tokFile) | |
if err != nil { | |
tok = getTokenFromWeb(config) | |
saveToken(tokFile, tok) | |
} | |
return config.Client(ctx, tok) | |
} | |
// getTokenFromWeb はウェブフローからトークンを取得します | |
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { | |
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) | |
fmt.Printf("以下のURLにアクセスして認証コードを取得してください:\n%v\n", authURL) | |
var authCode string | |
fmt.Println("認証コードを入力してください:") | |
if _, err := fmt.Scan(&authCode); err != nil { | |
log.Fatalf("認証コードの読み取りに失敗しました: %v", err) | |
} | |
tok, err := config.Exchange(context.TODO(), authCode) | |
if err != nil { | |
log.Fatalf("トークン取得に失敗しました: %v", err) | |
} | |
return tok | |
} | |
// tokenFromFile はファイルからトークンを読み込みます | |
func tokenFromFile(file string) (*oauth2.Token, error) { | |
f, err := os.Open(file) | |
if err != nil { | |
return nil, err | |
} | |
defer f.Close() | |
tok := &oauth2.Token{} | |
err = json.NewDecoder(f).Decode(tok) | |
return tok, err | |
} | |
// saveToken はトークンをファイルに保存します | |
func saveToken(path string, token *oauth2.Token) { | |
fmt.Printf("トークンを %s に保存します\n", path) | |
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) | |
if err != nil { | |
log.Fatalf("トークン保存用ファイルを開けませんでした: %v", err) | |
} | |
defer f.Close() | |
json.NewEncoder(f).Encode(token) | |
} | |
func main() { | |
ctx := context.Background() | |
// credentials.jsonファイルの読み込み | |
// credentialsPath := filepath.Join(home, "credentials.json") | |
credentialsPath := "./credentials.json" | |
b, err := os.ReadFile(credentialsPath) | |
if err != nil { | |
log.Fatalf("credentials.jsonの読み込みに失敗しました (%s): %v", credentialsPath, err) | |
fmt.Println("Google Cloud ConsoleからOAuth 2.0クライアントIDの認証情報をダウンロードし、") | |
fmt.Println("credentials.jsonという名前でホームディレクトリに保存してください。") | |
return | |
} | |
// OAuth設定の初期化 | |
config, err := google.ConfigFromJSON(b, youtube.YoutubeReadonlyScope) | |
if err != nil { | |
log.Fatalf("OAuth設定の解析に失敗しました: %v", err) | |
} | |
client := getClient(ctx, config) | |
// YouTube APIクライアントの初期化 | |
youtubeService, err := youtube.NewService(ctx, option.WithHTTPClient(client)) | |
if err != nil { | |
log.Fatalf("YouTubeサービスの作成に失敗しました: %v", err) | |
} | |
// プレイリストIDを設定 | |
playlistID := "PLVncrZRHU7RjSBziqoUGmfsyM41SY_l4u" // 実際のプレイリストIDに置き換えてください | |
videoURLs := []string{} | |
nextPageToken := "" | |
for { | |
// プレイリスト項目の取得リクエスト | |
call := youtubeService.PlaylistItems.List([]string{"snippet"}). | |
PlaylistId(playlistID). | |
MaxResults(50) // 一度に取得する最大件数(最大50) | |
// ページトークンがある場合は設定 | |
if nextPageToken != "" { | |
call = call.PageToken(nextPageToken) | |
} | |
// リクエストの実行 | |
response, err := call.Do() | |
if err != nil { | |
log.Fatalf("プレイリスト項目の取得に失敗しました: %v", err) | |
} | |
// 動画URLの抽出 | |
for _, item := range response.Items { | |
videoID := item.Snippet.ResourceId.VideoId | |
videoURL := fmt.Sprintf("https://www.youtube.com/watch?v=%s", videoID) | |
videoURLs = append(videoURLs, videoURL) | |
} | |
// 次のページトークンの取得 | |
nextPageToken = response.NextPageToken | |
if nextPageToken == "" { | |
break | |
} | |
} | |
// 取得した動画URL一覧を表示 | |
for _, url := range videoURLs { | |
fmt.Println(url) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使い方
許可を与えると、redirect_uriパラメータで指定された場所(例: http://localhost)にリダイレクトされます。