-
Notifications
You must be signed in to change notification settings - Fork 0
Discord /stats 슬래시커맨드로 대시보드 지표 대화형 조회 #671
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| name: Discord 슬래시커맨드 등록 | ||
|
|
||
| # Discord admin 봇의 길드 슬래시커맨드(/piki-admin·/stats)를 등록/갱신한다. | ||
| # 봇 토큰은 secrets.DISCORD_BOT_TOKEN 을 러너 안에서만 꺼내 써서(로컬 curl 불필요) 노출되지 않는다. | ||
| # 길드 스코프라 즉시 반영. POST 는 개별 upsert 라 서로를 덮어쓰지 않는다. | ||
| # Actions 탭 → 이 워크플로 → Run workflow(초록 버튼) → command 선택 → 실행. | ||
| on: | ||
| workflow_dispatch: | ||
| inputs: | ||
| command: | ||
| description: "등록할 커맨드" | ||
| type: choice | ||
| required: true | ||
| default: all | ||
| options: | ||
| - all | ||
| - piki-admin | ||
| - stats | ||
|
|
||
| env: | ||
| APP_ID: "1522386661067980921" | ||
| GUILD_ID: "1520952901944475778" | ||
|
|
||
| jobs: | ||
| register: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - name: 슬래시커맨드 등록 | ||
| env: | ||
| BOT_TOKEN: ${{ secrets.DISCORD_BOT_TOKEN }} | ||
| COMMAND: ${{ inputs.command }} | ||
| run: | | ||
| set -euo pipefail | ||
| if [ -z "$BOT_TOKEN" ]; then echo "::error::secrets.DISCORD_BOT_TOKEN 이 비어 있음"; exit 1; fi | ||
|
|
||
| register() { | ||
| # $1: 표시용 이름, $2: 커맨드 JSON | ||
| local code | ||
| code=$(curl -s -o /tmp/resp.json -w '%{http_code}' \ | ||
| -X POST "https://discord.com/api/v10/applications/$APP_ID/guilds/$GUILD_ID/commands" \ | ||
| -H "Authorization: Bot $BOT_TOKEN" \ | ||
| -H "Content-Type: application/json" \ | ||
| -d "$2") | ||
| if [ "$code" = "200" ] || [ "$code" = "201" ]; then | ||
| echo "::notice::$1 등록 완료 (HTTP $code)" | ||
| else | ||
| echo "::error::$1 등록 실패 (HTTP $code) — $(cat /tmp/resp.json)" | ||
| exit 1 | ||
| fi | ||
| } | ||
|
|
||
| PIKI_ADMIN='{"name":"piki-admin","description":"백오피스 접근 링크 발급","options":[{"type":3,"name":"env","description":"접속 환경","required":true,"choices":[{"name":"dev","value":"dev"},{"name":"staging","value":"staging"},{"name":"prod","value":"prod"}]}]}' | ||
| STATS='{"name":"stats","description":"운영 지표 조회 (개발진 제외 기본)","options":[{"type":3,"name":"period","description":"조회 기간","required":true,"choices":[{"name":"오늘","value":"today"},{"name":"어제","value":"yesterday"},{"name":"최근 7일","value":"7d"},{"name":"최근 30일","value":"30d"}]},{"type":3,"name":"metric","description":"지표 섹션 (기본: 요약)","required":false,"choices":[{"name":"요약","value":"summary"},{"name":"가입","value":"signup"},{"name":"위시","value":"wish"},{"name":"토너먼트","value":"tournament"},{"name":"푸시","value":"push"}]}]}' | ||
|
|
||
| case "$COMMAND" in | ||
| piki-admin) register "piki-admin" "$PIKI_ADMIN" ;; | ||
| stats) register "stats" "$STATS" ;; | ||
| all) register "piki-admin" "$PIKI_ADMIN"; register "stats" "$STATS" ;; | ||
| *) echo "::error::알 수 없는 command=$COMMAND"; exit 1 ;; | ||
| esac |
31 changes: 31 additions & 0 deletions
31
src/main/kotlin/com/depromeet/piki/admin/access/AdminGrantCommandHandler.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package com.depromeet.piki.admin.access | ||
|
|
||
| import com.depromeet.piki.admin.config.AdminProperties | ||
| import com.depromeet.piki.admin.config.ConditionalOnAdminEnabled | ||
| import org.springframework.stereotype.Component | ||
|
|
||
| // `/piki-admin env:<dev|staging|prod>` — 선택한 환경의 원타임 grant 링크를 발급한다(#654). | ||
| // host 는 grantHosts 맵에서(요청 host 가 아니라) — 인터랙션 엔드포인트와 대상 env 가 다를 수 있어서다. | ||
| // 토큰은 그 env 에 바인딩 서명돼(GrantTokenCodec), 대상 env 만 소비할 수 있다(cross-env). | ||
| @Component | ||
| @ConditionalOnAdminEnabled | ||
| class AdminGrantCommandHandler( | ||
| private val allowlistService: AdminAllowlistService, | ||
| private val adminProperties: AdminProperties, | ||
| ) : DiscordCommandHandler { | ||
| override val commandName = "piki-admin" | ||
|
|
||
| override fun handle(interaction: DiscordInteraction): Map<String, Any> { | ||
| val env = DiscordInteractions.optionValue(interaction.root, "env") | ||
| val host = | ||
| adminProperties.grantHosts[env] | ||
| ?: return DiscordInteractions.embed(DiscordInteractions.COLOR_RED, "❌ 알 수 없는 환경", "지원하지 않는 환경입니다: `$env`") | ||
| val token = allowlistService.issueGrantToken(interaction.userId, interaction.userName, env) | ||
| val link = "$host/admin-access/grant?token=$token" | ||
| return DiscordInteractions.embed( | ||
| DiscordInteractions.COLOR_GREEN, | ||
| "✅ 관리자 인증됨 — ${interaction.userName}", | ||
| "**$env** 접속: 이 기기에서 3분 내 아래 링크를 여세요 (그 기기 IP 가 등록됩니다).\n$link", | ||
| ) | ||
| } | ||
| } |
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
73 changes: 73 additions & 0 deletions
73
src/main/kotlin/com/depromeet/piki/admin/access/DiscordInteractions.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| package com.depromeet.piki.admin.access | ||
|
|
||
| import tools.jackson.databind.JsonNode | ||
|
|
||
| // Discord 인터랙션 페이로드 파싱·응답 조립 공통 헬퍼(순수). 여러 커맨드 핸들러가 공유한다. | ||
| object DiscordInteractions { | ||
| const val TYPE_PING = 1 | ||
| const val TYPE_PONG = 1 | ||
| const val TYPE_CHANNEL_MESSAGE = 4 | ||
| const val FLAG_EPHEMERAL = 64 | ||
| const val COLOR_GREEN = 0x2ECC71 | ||
| const val COLOR_RED = 0xE74C3C | ||
|
|
||
| // data.name — 어느 슬래시커맨드인가(라우팅 키). | ||
| fun commandName(root: JsonNode): String = root.path("data").path("name").takeIf { it.isString }?.asString() ?: "" | ||
|
|
||
| // 최상위 커맨드 옵션 값(data.options[name==?].value). 서브커맨드 없이 인덱스 순회로 찾는다(Jackson 3). | ||
| fun optionValue( | ||
| root: JsonNode, | ||
| name: String, | ||
| ): String { | ||
| val opts = root.path("data").path("options") | ||
| if (!opts.isArray) return "" | ||
| for (i in 0 until opts.size()) { | ||
| val o = opts.get(i) | ||
| if (o.path("name").takeIf { it.isString }?.asString() == name) { | ||
| return o.path("value").takeIf { it.isString }?.asString() ?: "" | ||
| } | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| fun userId(root: JsonNode): String = root.path("member").path("user").path("id").takeIf { it.isString }?.asString() ?: "" | ||
|
|
||
| // 로그·감사 actor 이름 — 서버 별명(nick) 우선, 없으면 표시이름(global_name), 없으면 고유 핸들(username). | ||
| fun userName(root: JsonNode): String = | ||
| root.path("member").path("nick").takeIf { it.isString }?.asString() | ||
| ?: root.path("member").path("user").path("global_name").takeIf { it.isString }?.asString() | ||
| ?: root.path("member").path("user").path("username").takeIf { it.isString }?.asString() | ||
| ?: "unknown" | ||
|
|
||
| fun pong(): Map<String, Any> = mapOf("type" to TYPE_PONG) | ||
|
|
||
| // ephemeral(본인만 보임, flags 64) 단일 embed(제목+설명). 링크·거부 UI 가 채널에 새지 않게 항상 ephemeral. | ||
| fun embed( | ||
| color: Int, | ||
| title: String, | ||
| description: String, | ||
| ): Map<String, Any> = | ||
| mapOf( | ||
| "type" to TYPE_CHANNEL_MESSAGE, | ||
| "data" to | ||
| mapOf( | ||
| "embeds" to listOf(mapOf("title" to title, "description" to description, "color" to color)), | ||
| "flags" to FLAG_EPHEMERAL, | ||
| ), | ||
| ) | ||
| } | ||
|
|
||
| // 게이트(서명·채널·allowlist)를 통과한 인터랙션 컨텍스트. 핸들러는 이 값만 받아 커맨드를 처리한다. | ||
| data class DiscordInteraction( | ||
| val root: JsonNode, | ||
| val userId: String, | ||
| val userName: String, | ||
| val clientIp: String, | ||
| ) | ||
|
|
||
| // data.name 별 커맨드 처리기. 게이트는 컨트롤러가 공통으로 하고, 핸들러는 자기 커맨드 로직만 담는다. | ||
| interface DiscordCommandHandler { | ||
| val commandName: String | ||
|
|
||
| fun handle(interaction: DiscordInteraction): Map<String, Any> | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/main/kotlin/com/depromeet/piki/admin/access/StatsCommandHandler.kt
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package com.depromeet.piki.admin.access | ||
|
|
||
| import com.depromeet.piki.admin.config.ConditionalOnAdminEnabled | ||
| import com.depromeet.piki.metrics.dashboard.MetricsService | ||
| import org.springframework.stereotype.Component | ||
|
|
||
| // `/stats period:<오늘|어제|7일|30일> metric:<요약|가입|위시|토너먼트|푸시>` — 대시보드 지표를 Discord 에서 대화형 조회(#664). | ||
| // 집계는 MetricsService 를 그대로 재사용하고(중복 0), 여기선 옵션 파싱 + 섹션 embed 표현만 한다. LLM 없음. | ||
| // 개발진(developers 명단) 활동은 대시보드 기본과 동일하게 제외한다. | ||
| @Component | ||
| @ConditionalOnAdminEnabled | ||
| class StatsCommandHandler( | ||
| private val metricsService: MetricsService, | ||
| ) : DiscordCommandHandler { | ||
| override val commandName = "stats" | ||
|
|
||
| override fun handle(interaction: DiscordInteraction): Map<String, Any> { | ||
| val period = StatsPeriod.from(DiscordInteractions.optionValue(interaction.root, "period")) | ||
| val metric = StatsMetric.from(DiscordInteractions.optionValue(interaction.root, "metric")) | ||
|
|
||
| val range = metricsService.resolveRange(period.preset, null, null) | ||
| val snapshot = metricsService.snapshot(range.from, range.to, excludeInternal = true) | ||
|
|
||
| return StatsEmbed.build(metric, snapshot, period.label) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.