3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

QitaAPIを使って週ごとの投稿数を取得

Last updated at Posted at 2024-10-18
qita-api.ps1
# Qiita API用のパラメータ
$clientId = "hoge"
$clientSecret = "foo"
$redirectUri = "http://localhost:8000"
$scope = "read_qiita"

# 認証URLを生成
$authUrl = "https://qiita.com/api/v2/oauth/authorize?client_id=$clientId&scope=$([System.Web.HttpUtility]::UrlEncode($scope))&redirect_uri=$([System.Web.HttpUtility]::UrlEncode($redirectUri))"

# ユーザーに認証URLを表示
Write-Host "以下のURLをブラウザで開いて認証してください:"
Write-Host $authUrl

# ユーザーから認証後のリダイレクトURLを入力してもらう
$redirectedUrl = Read-Host "認証後にリダイレクトされたURLを入力してください"

# リダイレクトURLから認証コードを抽出
$authCode = [System.Web.HttpUtility]::ParseQueryString($redirectedUrl.Split('?')[1]).Get("code")

# アクセストークンを取得
$tokenUrl = "https://qiita.com/api/v2/access_tokens"
$body = @{
    client_id = $clientId
    client_secret = $clientSecret
    code = $authCode
}

try {
    $response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body ($body | ConvertTo-Json) -ContentType "application/json"
    $accessToken = $response.token

    # 投稿一覧を取得
    $itemsUrl = "https://qiita.com/api/v2/authenticated_user/items"
    $headers = @{
        "Authorization" = "Bearer $accessToken"
    }

    $allItems = @()
    $page = 1
    $perPage = 100  # 最大値を使用

    do {
        $encodedUrl = [System.Uri]::EscapeUriString("$itemsUrl`?page=$page&per_page=$perPage")
        Write-Host "Fetching page $page..."
        $itemsResponse = Invoke-RestMethod -Uri $encodedUrl -Headers $headers -Method Get
        $allItems += $itemsResponse
        $page++

        # API制限を避けるために短い待機時間を設ける
        Start-Sleep -Milliseconds 100

        # 進捗状況を表示
        Write-Host "Total items fetched: $($allItems.Count)"

    } while ($itemsResponse.Count -eq $perPage)

    # 週ごとの投稿を集計
    $weeklyPosts = @{}

    foreach ($item in $allItems) {
        $createdDate = [DateTime]::Parse($item.created_at)
        $weekStart = $createdDate.Date.AddDays(-([int]$createdDate.DayOfWeek))
        $weekEnd = $weekStart.AddDays(6)
        $weekKey = "$($weekStart.ToString('yyyy-MM-dd')) to $($weekEnd.ToString('yyyy-MM-dd'))"

        if (-not $weeklyPosts.ContainsKey($weekKey)) {
            $weeklyPosts[$weekKey] = @{
                Count = 0
                Titles = @()
            }
        }
        $weeklyPosts[$weekKey].Count++
        $weeklyPosts[$weekKey].Titles += $item.title
    }

    # 結果を表示
    Write-Host "`n週ごとの投稿数と記事タイトル:"
    $weeklyPosts.GetEnumerator() | Sort-Object {[DateTime]::ParseExact($_.Key.Split(' ')[0], 'yyyy-MM-dd', $null)} -Descending | ForEach-Object {
        Write-Host "`n週: $($_.Key)"
        Write-Host "投稿数: $($_.Value.Count) 件"
        Write-Host "記事タイトル:"
        $_.Value.Titles | ForEach-Object { Write-Host " - $_" }
    }

    # 総投稿数を表示
    Write-Host "`n総投稿数: $($allItems.Count) 件"
}
catch {
    Write-Error "エラーが発生しました: $_"
    Write-Host "詳細なエラー情報:"
    Write-Host $_.Exception.Message
    if ($_.Exception.Response) {
        $result = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($result)
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd()
        Write-Host $responseBody
    }
}

スクリーンショット 2024-10-18 214508.png

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?