Skip to content

refactor: index.tsのclient.onを分割し、マジックナンバーを削減 - #50

Draft
sora81dev wants to merge 36 commits into
sf-kosen:mainfrom
sora81dev:refactor/conciseindexFile
Draft

refactor: index.tsのclient.onを分割し、マジックナンバーを削減#50
sora81dev wants to merge 36 commits into
sf-kosen:mainfrom
sora81dev:refactor/conciseindexFile

Conversation

@sora81dev

@sora81dev sora81dev commented Jun 12, 2026

Copy link
Copy Markdown
Member

About this PR

保守性・視認性を向上させることを目的としたリファクタリングです。

  • 長すぎるindex.tsを複数ファイルに分割
    client.onの連なりをhandlers/events/内に移動

  • configファイルの作成

    • env.tsの作成
      複数箇所でenvファイルを読み込むのではなく、1カ所で読み、他ではimport

    • config.tsの作成
      ファイル内で共通して使用する定数(ロールidなど)

    • runtimeConfig.tsの作成
      roleMessageIdなどready時に読み込まれる定数を管理

  • jobsフォルダにあるべきでないファイルの移動

  • servicesフォルダを作成

Progress

❌: backlog
🔄: in Progress
✅: completed

  • configFiles
    🔄 config.ts
    🔄 env.ts
    ✅ runtimeConfig.ts

  • index.ts(main refactoring target)
    326 Lines -> 282 Lines
    ✅ reactionRole
    ❌ autoRole
    ❌ VC
    ❌ recruitNotification

  • jobsFolder
    ❌ updateMembercount
    ❌ noticeNewRecruit

  • servicesFolder
    🔄 reactionRole
    ❌ autoRole
    ❌ VC
    ❌ recruitNotification

Summary by CodeRabbit

  • Refactor
    • Reorganized message reaction removal handling into a dedicated handler module for improved code structure and maintainability.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1779f487-b904-418d-97bf-253027cc3490

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This pull request extracts the inline messageReactionRemove event listener from index.ts into a dedicated handler file. The new onMessageReactionRemove handler validates guild members and emoji presence, conditionally matches message IDs, and removes reaction roles with error handling. The event listener is updated to delegate to this extracted handler.

Changes

Message Reaction Removal Handler Extraction

Layer / File(s) Summary
Extract reaction removal handler and wire event
src/handlers/events/onMessageReactionRemove.ts, src/index.ts
New onMessageReactionRemove handler resolves guild members, validates emoji, matches message IDs against reactionRoleMessage, and calls removeReactionRole with try/catch error logging. The handler is imported and wired to the messageReactionRemove event listener in index.ts, replacing 22 lines of inline logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A handler hops from inline to file,
Reaction removal styled with grace,
Event listeners delegated in style,
Discord events find their place! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title accurately describes the main refactoring work: extracting the onMessageReactionRemove handler from index.ts and reducing magic numbers by consolidating event listeners.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/handlers/events/onMessageReactionRemove.ts`:
- Around line 17-24: The handler references reactionRoleMessage from index but
that variable is no longer in scope; update the onMessageReactionRemove handler
(in onMessageReactionRemove.ts) to accept an extra parameter (e.g.,
reactionRoleMessage) alongside the existing parameters used by
removeReactionRole, update its exported function signature and types, and then
modify the event registration where you wire the handler (the
client.on("messageReactionRemove", ...) registration in index.ts) to pass
reactionRoleMessage into the handler via a closure (e.g., client.on(...,
(reaction, user) => onMessageReactionRemove(reaction, user,
reactionRoleMessage))). Ensure imports/exports for onMessageReactionRemove are
adjusted and any TypeScript types for member/reaction parameters remain correct.
- Line 8: The log in the onMessageReactionRemove handler is incorrect: update
the console.log call inside onMessageReactionRemove (currently logging
"messageReactionAdded") to a correct, descriptive message such as
"messageReactionRemoved" or "messageReactionRemove" so logs reflect reaction
removals; locate the console.log in onMessageReactionRemove and change only the
message string.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ee1da512-1047-48ba-821f-efa6faf8d316

📥 Commits

Reviewing files that changed from the base of the PR and between c918987 and 1b119c8.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • src/handlers/events/onMessageReactionRemove.ts
  • src/index.ts
  • src/services/reactionRole/addReactionRole.ts
  • src/services/reactionRole/removeReactionRole.ts

const message = reaction.message;
const member = message?.guild?.members.resolve(user.id);

console.log("[INFO] messageReactionAdded");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect log message — copy-paste from the "add" handler.

The log says "messageReactionAdded" but this handler processes reaction removals.

✏️ Proposed fix
-  console.log("[INFO]  messageReactionAdded");
+  console.log("[INFO]  messageReactionRemoved");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log("[INFO] messageReactionAdded");
console.log("[INFO] messageReactionRemoved");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/handlers/events/onMessageReactionRemove.ts` at line 8, The log in the
onMessageReactionRemove handler is incorrect: update the console.log call inside
onMessageReactionRemove (currently logging "messageReactionAdded") to a correct,
descriptive message such as "messageReactionRemoved" or "messageReactionRemove"
so logs reflect reaction removals; locate the console.log in
onMessageReactionRemove and change only the message string.

Comment on lines +17 to +24
if (message.id === reactionRoleMessage) {
try {
await removeReactionRole(member, reaction.emoji.name);
} catch (e) {
console.error(e);
// この先通知処理も追加
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Shared root cause: reactionRoleMessage is inaccessible after extraction.

The handler in src/handlers/events/onMessageReactionRemove.ts references reactionRoleMessage (line 17), but this variable is defined in src/index.ts (line 51) and not passed to the handler when wired at line 301. Both files need coordinated changes: the handler signature must accept reactionRoleMessage as a parameter, and the event registration must pass it via a closure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/handlers/events/onMessageReactionRemove.ts` around lines 17 - 24, The
handler references reactionRoleMessage from index but that variable is no longer
in scope; update the onMessageReactionRemove handler (in
onMessageReactionRemove.ts) to accept an extra parameter (e.g.,
reactionRoleMessage) alongside the existing parameters used by
removeReactionRole, update its exported function signature and types, and then
modify the event registration where you wire the handler (the
client.on("messageReactionRemove", ...) registration in index.ts) to pass
reactionRoleMessage into the handler via a closure (e.g., client.on(...,
(reaction, user) => onMessageReactionRemove(reaction, user,
reactionRoleMessage))). Ensure imports/exports for onMessageReactionRemove are
adjusted and any TypeScript types for member/reaction parameters remain correct.

@sora81dev
sora81dev force-pushed the refactor/conciseindexFile branch from 1b119c8 to c59b0e5 Compare June 12, 2026 03:25
@sora81dev
sora81dev marked this pull request as draft June 12, 2026 03:26
@sora81dev sora81dev changed the title refactor: index.tsのclient.onを分割 refactor: index.tsのclient.onを分割し、マジックナンバーを削減 Jun 12, 2026
Comment thread src/configs/env.ts Outdated
Comment on lines +1 to +9
import dotenv from "dotenv"

dotenv.config()

export const env = {
tokens: {
discordToken: process.env.DISCORD_TOKEN
}
}

@tanahiro2010 tanahiro2010 Jun 12, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
import dotenv from "dotenv"
dotenv.config()
export const env = {
tokens: {
discordToken: process.env.DISCORD_TOKEN
}
}
import dotenv from "dotenv";
dotenv.config();
export const env = {
tokens: {
discordToken: process.env.DISCORD_TOKEN
}
}

他のファイルの行末にはセミコロンがついているのにここだけない

Comment thread src/handlers/events/onMessageReactionRemove.ts
Comment thread src/index.ts Outdated
Comment on lines 225 to 229

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
await Promise.all([
addRoleSafely(member, "1454099602641780737", "bot"), // botロールを付与
addRoleSafely(member, "1454099602641780737", "student") // 学生ロールを付与
]);

並列実行で効率化

Comment thread src/handlers/events/onMessageReactionAdd.ts
@sora81dev

Copy link
Copy Markdown
Member Author

@tanahiro2010
runtimeConfigできた

@sora81dev
sora81dev force-pushed the refactor/conciseindexFile branch from 973f6f1 to 1862bd3 Compare July 24, 2026 17:34
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.

2 participants