Skip to content

Refactor: 봇 prefix 슬래시로 변경#21

Merged
DevelopLee20 merged 2 commits intomasterfrom
refactor-prefix
Aug 24, 2025
Merged

Refactor: 봇 prefix 슬래시로 변경#21
DevelopLee20 merged 2 commits intomasterfrom
refactor-prefix

Conversation

@DevelopLee20
Copy link
Owner

@DevelopLee20 DevelopLee20 commented Aug 24, 2025

Summary by CodeRabbit

  • New Features

    • 단어검색과 안녕 명령을 슬래시 명령어로 제공(/단어검색, /안녕). 명령 설명과 사용자 멘션을 포함해 상호작용 방식으로 응답하며 대기(Thinking) 상태 표시를 지원합니다.
  • Refactor

    • 텍스트 기반 명령을 슬래시 명령 흐름으로 전환해 호출·응답 방식과 사용자 경험을 통일했습니다.
  • Chores

    • 봇 명령 접두사를 “!”에서 “/”로 변경하고, 확장 로드 후 앱 커맨드 동기화 기능을 추가해 슬래시 명령 표시 안정성을 개선했습니다.

@coderabbitai
Copy link

coderabbitai bot commented Aug 24, 2025

Walkthrough

텍스트 기반 명령을 Discord 슬래시(app) 명령으로 이관했다. 두 개의 Cog(gemini, hello)의 핸들러가 ctx에서 interaction 흐름으로 전환되었고, gemini 명령에 interaction.response.defer(thinking=True)interaction.followup.send 사용이 추가되었으며 main.py에서 접두사 변경과 앱 커맨드 트리 동기화를 수행한다.

Changes

Cohort / File(s) Summary
Slash 명령 이관 (Cogs)
cogs/gemini.py, cogs/hello.py
@commands.command@app_commands.command 전환, 함수 시그니처 ctxinteraction 변경, ctx.author.mentioninteraction.user.mention 교체, discordapp_commands 임포트 추가.
Gemini 명령 비동기 응답 흐름
cogs/gemini.py
Interaction에서 처리 상태 표시를 위해 interaction.response.defer(thinking=True) 호출을 추가하고 최종 응답은 interaction.followup.send로 전송하도록 변경. 기존 GeminiClient 호출 및 상태 처리 로직은 유지.
봇 설정/동기화
main.py
commands.Bot 접두사 "!""/" 변경, setup_hookawait bot.tree.sync() 추가하여 앱 커맨드 동기화 수행.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor U as 사용자
    participant D as Discord
    participant B as Bot
    participant C1 as HelloCog
    participant C2 as GeminiCog
    participant G as GeminiClient

    rect rgba(230,245,255,0.6)
    Note over U,D: 사용자 슬래시 명령 호출
    U->>D: /안녕 또는 /단어검색 input_word
    D->>B: Interaction Create 이벤트
    end

    alt 명령: 안녕
        B->>C1: hello_text_command(interaction)
        C1->>B: interaction.response.send_message(...)
        B-->>D: 응답 페이로드
        D-->>U: 인사 메시지
    else 명령: 단어검색
        B->>C2: gemini_response_command(interaction, input_word)
        C2->>B: interaction.response.defer(thinking=True)
        C2->>G: query(input_word)
        G-->>C2: status_text, 응답
        C2->>B: interaction.followup.send(...)
        B-->>D: 응답 페이로드
        D-->>U: 검색 결과
    end

    rect rgba(240,255,240,0.6)
    Note over B: 부팅 시 확장 로드 후<br/>bot.tree.sync() 실행
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

작은 발톱 톡톡, 슬래시 길을 열었네 🐇
!는 쉬고 /는 춤추니, 반짝이는 밤⭐
안녕은 곧장, 단어검색은 생각 톡—
디퍼(defer)하고 잠시, 답은 followup으로 전해요
깡총깡총, 코드도 준비 완료! 🥕

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-prefix

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
cogs/hello.py (1)

13-14: 함수명 정리 및 메시지 소음 완화(ephemeral) 권장

  • 핸들러명이 *_text_command로 남아있어 혼동 소지가 있습니다. 슬래시 명령임을 반영해 간결하게 변경하면 좋습니다.
  • 단순 인사 응답은 채널 소음을 줄이기 위해 ephemeral=True를 고려해 주세요.
-    async def hello_text_command(self, interaction: discord.Interaction):
-        await interaction.response.send_message(hello_message(interaction.user.mention))
+    async def hello_command(self, interaction: discord.Interaction):
+        await interaction.response.send_message(
+            hello_message(interaction.user.mention),
+            ephemeral=True
+        )
main.py (2)

50-50: 전역 sync는 레이트리밋 및 배포 지연 유발 — DEV는 길드 단위 sync로, PROD만 전역 sync 권장

개발 모드에서는 특정 길드로 제한된 동기화가 즉시 반영되고 제한도 덜합니다. 운영에서는 전역 동기화를 수행하세요. env.GUILD_ID(개발 길드 ID)를 사용해 분기하는 형태를 권장합니다.

-    await bot.tree.sync()
+    if env.MODE == "PROD":
+        await bot.tree.sync()
+    else:
+        dev_guild_id = getattr(env, "GUILD_ID", None)
+        if dev_guild_id:
+            await bot.tree.sync(guild=discord.Object(id=int(dev_guild_id)))
+        else:
+            # GUILD_ID 미설정 시 전역 sync로 폴백
+            await bot.tree.sync()

11-12: Privileged Intent 최소화 권장

슬래시 커맨드 중심이라면 message_content 인텐트는 필요 없습니다. 다른 Cog에서 메시지 콘텐츠를 직접 파싱하지 않는다면 비활성화해 권한 범위를 최소화하세요. 필요 시 DEV에서만 활성화하도록 분기하는 것도 좋습니다.

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f26a00d and 922db5b.

📒 Files selected for processing (3)
  • cogs/gemini.py (2 hunks)
  • cogs/hello.py (2 hunks)
  • main.py (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
cogs/hello.py (1)
core/messages.py (1)
  • hello_message (7-8)
cogs/gemini.py (2)
core/gemini_client.py (1)
  • create_gemini_message (22-28)
core/messages.py (1)
  • gemini_response_message (36-37)
🔇 Additional comments (3)
cogs/hello.py (1)

1-2: 슬래시 명령 전환을 위한 import 추가: OK

discord, app_commands 도입 적절합니다. Cog 구조와의 결합도 문제 없습니다.

cogs/gemini.py (1)

1-2: 슬래시 명령 전환을 위한 import 추가: OK

슬래시 명령 마이그레이션을 위한 의존성 도입이 올바릅니다.

main.py (1)

14-14: prefix 기반 커맨드 검증 요청

자동화 스크립트로 @commands.command, @bot.command, @command 데코레이터 및 .add_command 호출을 검색했으나, 레포 내에 prefix 기반 커맨드 정의가 발견되지 않았습니다.
하지만 스크립트만으로 모든 파일·패턴을 완벽히 커버하기 어려우므로, 다음 사항에 대해 수동 검증을 부탁드립니다:

  • 레포 전체에서 사용자 지정 prefix 명령을 선언하거나 호출하는 부분이 없는지 확인
  • Cog나 별도 모듈에서 동적으로 커맨드를 등록하는 코드가 없는지 검토

위 검증을 통해 실제로 prefix 명령이 전혀 없다면, command_prefix="/" 설정은 기존 커맨드에 아무런 영향을 주지 않습니다.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
cogs/gemini.py (1)

14-18: 치명적: 슬래시 명령 name은 ASCII 소문자/숫자/하이픈/언더스코어만 허용됩니다. "단어검색"은 등록 실패합니다.

Discord slash 명령 규칙상 비-ASCII 이름은 거부되어 트리 동기화가 실패할 가능성이 매우 큽니다. 한국어 표시는 로컬라이제이션으로 처리하고, canonical name은 ASCII로 두세요.

최소 수정안:

-    @app_commands.command(
-        name="단어검색", description="LLM으로 단어의 의미를 검색합니다."
-    )
+    @app_commands.command(
+        name="define", description="LLM으로 단어의 의미를 검색합니다."
+    )

선택사항(남용 방지 쿨다운):

     @app_commands.describe(input_word="검색할 단어")
+    @checks.cooldown(2, 10.0, key=lambda i: i.user.id)

참고:

  • 쿨다운을 쓰려면 임포트가 필요합니다.
    from discord.app_commands import checks
  • 한국어 표시는 라이브러리에서 지원하는 로컬라이제이션 API로 name/description을 현지화하세요(예: name은 ASCII, ko 로캘에 “단어검색” 노출).
🧹 Nitpick comments (3)
cogs/gemini.py (3)

1-2: app_commands 도입은 적절. 장문 응답 대비 BytesIO import 추가를 권장합니다.

현재 변경은 문제 없습니다. 아래 2000자 초과 대응(파일 전송) 제안을 적용하려면 BytesIO 임포트가 필요합니다.

추가(파일 상단 어딘가에 삽입):

from io import BytesIO

24-26: 이벤트 루프 블로킹 가능성: GeminiClient 내부가 동기 I/O로 보입니다.

core/gemini_client.pycreate_gemini_messageself.client.send_message(...)를 직접 호출하고 있어(비동기 await 없음) 이벤트 루프를 막을 수 있습니다. 해당 호출만 스레드 오프로딩하면 UI(디스코드 상호작용) 지연을 줄일 수 있습니다.

core/gemini_client.py 제안(라이브러리 구조에 맞게 조정):

# core/gemini_client.py
import asyncio

async def create_gemini_message(self, input_word: str) -> tuple[bool, str]:
    if self.client is None:
        await self.initialize()
    try:
        # send_message가 동기라면 to_thread로 오프로딩
        resp = await asyncio.to_thread(self.client.send_message, input_word)
        return True, resp.text
    except Exception as e:
        return False, f"GEMINI 오류 발생: {e}"

30-31: 2000자 메시지 제한 대응: 초과 시 파일 전송으로 폴백하세요.

LLM 응답이 길어질 수 있어 디스코드 2000자 제한에 걸릴 수 있습니다. 초과 시 파일로 전송하거나 청크로 분할하세요. 아래는 간단한 파일 전환 예시입니다.

-        # 생각중이라는 상태를 끝내고, 최종 결과 반환
-        await interaction.followup.send(text)
+        # 생각중이라는 상태를 끝내고, 최종 결과 반환 (2000자 제한 대응)
+        if len(text) > 2000:
+            await interaction.followup.send(
+                file=discord.File(BytesIO(text.encode("utf-8")), filename="gemini.txt")
+            )
+        else:
+            await interaction.followup.send(text)

위 변경에는 상단 임포트가 필요합니다(별도 코멘트 참고).

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 922db5b and 5f04272.

📒 Files selected for processing (1)
  • cogs/gemini.py (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: DevelopLee20
PR: DevelopLee20/DiePpi_bot#21
File: cogs/gemini.py:14-18
Timestamp: 2025-08-24T08:46:55.196Z
Learning: DevelopLee20 prefers a "working first, compliance later" approach during development stages. They're willing to accept potential API rule violations if the code functions properly during early development/testing phases.
📚 Learning: 2025-08-24T08:46:55.196Z
Learnt from: DevelopLee20
PR: DevelopLee20/DiePpi_bot#21
File: cogs/gemini.py:14-18
Timestamp: 2025-08-24T08:46:55.196Z
Learning: DevelopLee20 prefers a "working first, compliance later" approach during development stages. They're willing to accept potential API rule violations if the code functions properly during early development/testing phases.

Applied to files:

  • cogs/gemini.py
🧬 Code graph analysis (1)
cogs/gemini.py (2)
core/gemini_client.py (1)
  • create_gemini_message (22-28)
core/messages.py (1)
  • gemini_response_message (36-37)
🔇 Additional comments (2)
cogs/gemini.py (2)

19-23: 3초 타임아웃 회피를 위한 defer 사용 적절합니다.

슬래시 상호작용 ACK 타이밍을 잘 처리했습니다. 별도 이슈 없습니다.


26-26: ctx → interaction 전환 및 멘션 소스 변경 적절합니다.
interaction.user.mention 사용은 올바른 전환입니다.

@DevelopLee20 DevelopLee20 merged commit d9ab8af into master Aug 24, 2025
3 checks passed
@DevelopLee20 DevelopLee20 deleted the refactor-prefix branch August 24, 2025 08:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant